clang 19.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"
20#include "clang/AST/Expr.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Sema.h"
36#include "clang/Sema/Template.h"
39#include "llvm/ADT/STLForwardCompat.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/TimeProfiler.h"
43#include <optional>
44
45using namespace clang;
46using namespace sema;
47
48//===----------------------------------------------------------------------===/
49// Template Instantiation Support
50//===----------------------------------------------------------------------===/
51
52namespace {
54struct Response {
55 const Decl *NextDecl = nullptr;
56 bool IsDone = false;
57 bool ClearRelativeToPrimary = true;
58 static Response Done() {
59 Response R;
60 R.IsDone = true;
61 return R;
62 }
63 static Response ChangeDecl(const Decl *ND) {
64 Response R;
65 R.NextDecl = ND;
66 return R;
67 }
68 static Response ChangeDecl(const DeclContext *Ctx) {
69 Response R;
70 R.NextDecl = Decl::castFromDeclContext(Ctx);
71 return R;
72 }
73
74 static Response UseNextDecl(const Decl *CurDecl) {
75 return ChangeDecl(CurDecl->getDeclContext());
76 }
77
78 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
79 Response R = Response::UseNextDecl(CurDecl);
80 R.ClearRelativeToPrimary = false;
81 return R;
82 }
83};
84
85// Retrieve the primary template for a lambda call operator. It's
86// unfortunate that we only have the mappings of call operators rather
87// than lambda classes.
88const FunctionDecl *
89getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
90 while (true) {
91 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
92 LambdaCallOperator->getDescribedTemplate());
93 FTD && FTD->getInstantiatedFromMemberTemplate()) {
94 LambdaCallOperator =
95 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
96 } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)
97 ->getInstantiatedFromMemberFunction())
98 LambdaCallOperator = Prev;
99 else
100 break;
101 }
102 return LambdaCallOperator;
103}
104
105struct EnclosingTypeAliasTemplateDetails {
106 TypeAliasTemplateDecl *Template = nullptr;
107 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
108 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
109
110 explicit operator bool() noexcept { return Template; }
111};
112
113// Find the enclosing type alias template Decl from CodeSynthesisContexts, as
114// well as its primary template and instantiating template arguments.
115EnclosingTypeAliasTemplateDetails
116getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
117 for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
119 TypeAliasTemplateInstantiation)
120 continue;
121 EnclosingTypeAliasTemplateDetails Result;
122 auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),
123 *Next = TATD->getInstantiatedFromMemberTemplate();
124 Result = {
125 /*Template=*/TATD,
126 /*PrimaryTypeAliasDecl=*/TATD,
127 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
128 };
129 while (Next) {
130 Result.PrimaryTypeAliasDecl = Next;
131 Next = Next->getInstantiatedFromMemberTemplate();
132 }
133 return Result;
134 }
135 return {};
136}
137
138// Check if we are currently inside of a lambda expression that is
139// surrounded by a using alias declaration. e.g.
140// template <class> using type = decltype([](auto) { ^ }());
141// By checking if:
142// 1. The lambda expression and the using alias declaration share the
143// same declaration context.
144// 2. They have the same template depth.
145// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
146// a DeclContext, nor does it have an associated specialization Decl from which
147// we could collect these template arguments.
148bool isLambdaEnclosedByTypeAliasDecl(
149 const FunctionDecl *PrimaryLambdaCallOperator,
150 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
151 return cast<CXXRecordDecl>(PrimaryLambdaCallOperator->getDeclContext())
152 ->getTemplateDepth() ==
153 PrimaryTypeAliasDecl->getTemplateDepth() &&
155 const_cast<FunctionDecl *>(PrimaryLambdaCallOperator)) ==
156 PrimaryTypeAliasDecl->getDeclContext();
157}
158
159// Add template arguments from a variable template instantiation.
160Response
161HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
163 bool SkipForSpecialization) {
164 // For a class-scope explicit specialization, there are no template arguments
165 // at this level, but there may be enclosing template arguments.
166 if (VarTemplSpec->isClassScopeExplicitSpecialization())
167 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
168
169 // We're done when we hit an explicit specialization.
170 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
171 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
172 return Response::Done();
173
174 // If this variable template specialization was instantiated from a
175 // specialized member that is a variable template, we're done.
176 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
177 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
178 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
180 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
181 if (!SkipForSpecialization)
182 Result.addOuterTemplateArguments(
183 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
184 /*Final=*/false);
185 if (Partial->isMemberSpecialization())
186 return Response::Done();
187 } else {
188 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
189 if (!SkipForSpecialization)
190 Result.addOuterTemplateArguments(
191 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
192 /*Final=*/false);
193 if (Tmpl->isMemberSpecialization())
194 return Response::Done();
195 }
196 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
197}
198
199// If we have a template template parameter with translation unit context,
200// then we're performing substitution into a default template argument of
201// this template template parameter before we've constructed the template
202// that will own this template template parameter. In this case, we
203// use empty template parameter lists for all of the outer templates
204// to avoid performing any substitutions.
205Response
206HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
208 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
209 Result.addOuterTemplateArguments(std::nullopt);
210 return Response::Done();
211}
212
213Response HandlePartialClassTemplateSpec(
214 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
215 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
216 if (!SkipForSpecialization)
217 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
218 return Response::Done();
219}
220
221// Add template arguments from a class template instantiation.
222Response
223HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
225 bool SkipForSpecialization) {
226 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
227 // We're done when we hit an explicit specialization.
228 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
229 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
230 return Response::Done();
231
232 if (!SkipForSpecialization)
233 Result.addOuterTemplateArguments(
234 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
235 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
236 /*Final=*/false);
237
238 // If this class template specialization was instantiated from a
239 // specialized member that is a class template, we're done.
240 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
241 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
242 return Response::Done();
243
244 // If this was instantiated from a partial template specialization, we need
245 // to get the next level of declaration context from the partial
246 // specialization, as the ClassTemplateSpecializationDecl's
247 // DeclContext/LexicalDeclContext will be for the primary template.
248 if (auto *InstFromPartialTempl = ClassTemplSpec->getSpecializedTemplateOrPartial()
250 return Response::ChangeDecl(InstFromPartialTempl->getLexicalDeclContext());
251 }
252 return Response::UseNextDecl(ClassTemplSpec);
253}
254
255Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
257 const FunctionDecl *Pattern, bool RelativeToPrimary,
258 bool ForConstraintInstantiation) {
259 // Add template arguments from a function template specialization.
260 if (!RelativeToPrimary &&
261 Function->getTemplateSpecializationKindForInstantiation() ==
263 return Response::Done();
264
265 if (!RelativeToPrimary &&
266 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
267 // This is an implicit instantiation of an explicit specialization. We
268 // don't get any template arguments from this function but might get
269 // some from an enclosing template.
270 return Response::UseNextDecl(Function);
271 } else if (const TemplateArgumentList *TemplateArgs =
272 Function->getTemplateSpecializationArgs()) {
273 // Add the template arguments for this specialization.
274 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
275 TemplateArgs->asArray(),
276 /*Final=*/false);
277
278 if (RelativeToPrimary &&
279 (Function->getTemplateSpecializationKind() ==
281 (Function->getFriendObjectKind() &&
282 !Function->getPrimaryTemplate()->getFriendObjectKind())))
283 return Response::UseNextDecl(Function);
284
285 // If this function was instantiated from a specialized member that is
286 // a function template, we're done.
287 assert(Function->getPrimaryTemplate() && "No function template?");
288 if (Function->getPrimaryTemplate()->isMemberSpecialization())
289 return Response::Done();
290
291 // If this function is a generic lambda specialization, we are done.
292 if (!ForConstraintInstantiation &&
294 // TypeAliasTemplateDecls should be taken into account, e.g.
295 // when we're deducing the return type of a lambda.
296 //
297 // template <class> int Value = 0;
298 // template <class T>
299 // using T = decltype([]<int U = 0>() { return Value<T>; }());
300 //
301 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef)) {
302 if (isLambdaEnclosedByTypeAliasDecl(
303 /*PrimaryLambdaCallOperator=*/getPrimaryTemplateOfGenericLambda(
304 Function),
305 /*PrimaryTypeAliasDecl=*/TypeAlias.PrimaryTypeAliasDecl))
306 return Response::UseNextDecl(Function);
307 }
308 return Response::Done();
309 }
310
311 } else if (Function->getDescribedFunctionTemplate()) {
312 assert(
313 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
314 "Outer template not instantiated?");
315 }
316 // If this is a friend or local declaration and it declares an entity at
317 // namespace scope, take arguments from its lexical parent
318 // instead of its semantic parent, unless of course the pattern we're
319 // instantiating actually comes from the file's context!
320 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
321 Function->getNonTransparentDeclContext()->isFileContext() &&
322 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
323 return Response::ChangeDecl(Function->getLexicalDeclContext());
324 }
325
326 if (ForConstraintInstantiation && Function->getFriendObjectKind())
327 return Response::ChangeDecl(Function->getLexicalDeclContext());
328 return Response::UseNextDecl(Function);
329}
330
331Response HandleFunctionTemplateDecl(const FunctionTemplateDecl *FTD,
333 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
334 Result.addOuterTemplateArguments(
335 const_cast<FunctionTemplateDecl *>(FTD),
336 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(),
337 /*Final=*/false);
338
340
341 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
342 if (NNS->isInstantiationDependent()) {
343 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
344 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
345 // Prefer template arguments from the injected-class-type if possible.
346 // For example,
347 // ```cpp
348 // template <class... Pack> struct S {
349 // template <class T> void foo();
350 // };
351 // template <class... Pack> template <class T>
352 // ^^^^^^^^^^^^^ InjectedTemplateArgs
353 // They're of kind TemplateArgument::Pack, not of
354 // TemplateArgument::Type.
355 // void S<Pack...>::foo() {}
356 // ^^^^^^^
357 // TSTy->template_arguments() (which are of PackExpansionType)
358 // ```
359 // This meets the contract in
360 // TreeTransform::TryExpandParameterPacks that the template arguments
361 // for unexpanded parameters should be of a Pack kind.
362 if (TSTy->isCurrentInstantiation()) {
363 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
364 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
365 Arguments = CTD->getInjectedTemplateArgs();
366 else if (auto *Specialization =
367 dyn_cast<ClassTemplateSpecializationDecl>(RD))
368 Arguments =
369 Specialization->getTemplateInstantiationArgs().asArray();
370 }
371 Result.addOuterTemplateArguments(
372 const_cast<FunctionTemplateDecl *>(FTD), Arguments,
373 /*Final=*/false);
374 }
375 }
376
377 NNS = NNS->getPrefix();
378 }
379 }
380
381 return Response::ChangeDecl(FTD->getLexicalDeclContext());
382}
383
384Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
386 ASTContext &Context,
387 bool ForConstraintInstantiation) {
388 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
389 assert(
390 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
391 "Outer template not instantiated?");
392 if (ClassTemplate->isMemberSpecialization())
393 return Response::Done();
394 if (ForConstraintInstantiation)
395 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
396 ClassTemplate->getInjectedTemplateArgs(),
397 /*Final=*/false);
398 }
399
400 if (const MemberSpecializationInfo *MSInfo =
402 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
403 return Response::Done();
404
405 bool IsFriend = Rec->getFriendObjectKind() ||
408 if (ForConstraintInstantiation && IsFriend &&
410 return Response::ChangeDecl(Rec->getLexicalDeclContext());
411 }
412
413 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
414 // TypeAliasTemplateDecl that this lambda is defined inside of.
415 if (Rec->isLambda()) {
416 if (const Decl *LCD = Rec->getLambdaContextDecl())
417 return Response::ChangeDecl(LCD);
418 // Retrieve the template arguments for a using alias declaration.
419 // This is necessary for constraint checking, since we always keep
420 // constraints relative to the primary template.
421 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef)) {
422 const FunctionDecl *PrimaryLambdaCallOperator =
423 getPrimaryTemplateOfGenericLambda(Rec->getLambdaCallOperator());
424 if (isLambdaEnclosedByTypeAliasDecl(PrimaryLambdaCallOperator,
425 TypeAlias.PrimaryTypeAliasDecl)) {
426 Result.addOuterTemplateArguments(TypeAlias.Template,
427 TypeAlias.AssociatedTemplateArguments,
428 /*Final=*/false);
429 // Visit the parent of the current type alias declaration rather than
430 // the lambda thereof.
431 // E.g., in the following example:
432 // struct S {
433 // template <class> using T = decltype([]<Concept> {} ());
434 // };
435 // void foo() {
436 // S::T var;
437 // }
438 // The instantiated lambda expression (which we're visiting at 'var')
439 // has a function DeclContext 'foo' rather than the Record DeclContext
440 // S. This seems to be an oversight to me that we may want to set a
441 // Sema Context from the CXXScopeSpec before substituting into T.
442 return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
443 }
444 }
445 }
446
447 return Response::UseNextDecl(Rec);
448}
449
450Response HandleImplicitConceptSpecializationDecl(
453 Result.addOuterTemplateArguments(
454 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
456 /*Final=*/false);
457 return Response::UseNextDecl(CSD);
458}
459
460Response HandleGenericDeclContext(const Decl *CurDecl) {
461 return Response::UseNextDecl(CurDecl);
462}
463} // namespace TemplateInstArgsHelpers
464} // namespace
465
466/// Retrieve the template argument list(s) that should be used to
467/// instantiate the definition of the given declaration.
468///
469/// \param ND the declaration for which we are computing template instantiation
470/// arguments.
471///
472/// \param DC In the event we don't HAVE a declaration yet, we instead provide
473/// the decl context where it will be created. In this case, the `Innermost`
474/// should likely be provided. If ND is non-null, this is ignored.
475///
476/// \param Innermost if non-NULL, specifies a template argument list for the
477/// template declaration passed as ND.
478///
479/// \param RelativeToPrimary true if we should get the template
480/// arguments relative to the primary template, even when we're
481/// dealing with a specialization. This is only relevant for function
482/// template specializations.
483///
484/// \param Pattern If non-NULL, indicates the pattern from which we will be
485/// instantiating the definition of the given declaration, \p ND. This is
486/// used to determine the proper set of template instantiation arguments for
487/// friend function template specializations.
488///
489/// \param ForConstraintInstantiation when collecting arguments,
490/// ForConstraintInstantiation indicates we should continue looking when
491/// encountering a lambda generic call operator, and continue looking for
492/// arguments on an enclosing class template.
493
495 const NamedDecl *ND, const DeclContext *DC, bool Final,
496 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
497 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
498 bool SkipForSpecialization) {
499 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
500 // Accumulate the set of template argument lists in this structure.
502
503 using namespace TemplateInstArgsHelpers;
504 const Decl *CurDecl = ND;
505
506 if (!CurDecl)
507 CurDecl = Decl::castFromDeclContext(DC);
508
509 if (Innermost) {
510 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
511 Final);
512 // Populate placeholder template arguments for TemplateTemplateParmDecls.
513 // This is essential for the case e.g.
514 //
515 // template <class> concept Concept = false;
516 // template <template <Concept C> class T> void foo(T<int>)
517 //
518 // where parameter C has a depth of 1 but the substituting argument `int`
519 // has a depth of 0.
520 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
521 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
522 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
523 }
524
525 while (!CurDecl->isFileContextDecl()) {
526 Response R;
527 if (const auto *VarTemplSpec =
528 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
529 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
530 } else if (const auto *PartialClassTemplSpec =
531 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
532 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
533 SkipForSpecialization);
534 } else if (const auto *ClassTemplSpec =
535 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
536 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
537 SkipForSpecialization);
538 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
539 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
540 ForConstraintInstantiation);
541 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
542 R = HandleRecordDecl(*this, Rec, Result, Context,
543 ForConstraintInstantiation);
544 } else if (const auto *CSD =
545 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
546 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
547 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
548 R = HandleFunctionTemplateDecl(FTD, Result);
549 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
550 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
551 } else if (!isa<DeclContext>(CurDecl)) {
552 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
553 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
554 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
555 }
556 } else {
557 R = HandleGenericDeclContext(CurDecl);
558 }
559
560 if (R.IsDone)
561 return Result;
562 if (R.ClearRelativeToPrimary)
563 RelativeToPrimary = false;
564 assert(R.NextDecl);
565 CurDecl = R.NextDecl;
566 }
567
568 return Result;
569}
570
572 switch (Kind) {
580 case ConstraintsCheck:
582 return true;
583
601 return false;
602
603 // This function should never be called when Kind's value is Memoization.
604 case Memoization:
605 break;
606 }
607
608 llvm_unreachable("Invalid SynthesisKind!");
609}
610
613 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
614 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
615 sema::TemplateDeductionInfo *DeductionInfo)
616 : SemaRef(SemaRef) {
617 // Don't allow further instantiation if a fatal error and an uncompilable
618 // error have occurred. Any diagnostics we might have raised will not be
619 // visible, and we do not need to construct a correct AST.
622 Invalid = true;
623 return;
624 }
625 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
626 if (!Invalid) {
628 Inst.Kind = Kind;
629 Inst.PointOfInstantiation = PointOfInstantiation;
630 Inst.Entity = Entity;
631 Inst.Template = Template;
632 Inst.TemplateArgs = TemplateArgs.data();
633 Inst.NumTemplateArgs = TemplateArgs.size();
634 Inst.DeductionInfo = DeductionInfo;
635 Inst.InstantiationRange = InstantiationRange;
637
638 AlreadyInstantiating = !Inst.Entity ? false :
640 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
641 .second;
643 }
644}
645
647 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
648 SourceRange InstantiationRange)
650 CodeSynthesisContext::TemplateInstantiation,
651 PointOfInstantiation, InstantiationRange, Entity) {}
652
654 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
655 ExceptionSpecification, SourceRange InstantiationRange)
657 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
658 PointOfInstantiation, InstantiationRange, Entity) {}
659
661 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
662 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
663 SourceRange InstantiationRange)
665 SemaRef,
666 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
667 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
668 Template, TemplateArgs) {}
669
671 Sema &SemaRef, SourceLocation PointOfInstantiation,
673 ArrayRef<TemplateArgument> TemplateArgs,
675 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
676 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
677 InstantiationRange, FunctionTemplate, nullptr,
678 TemplateArgs, &DeductionInfo) {
682}
683
685 Sema &SemaRef, SourceLocation PointOfInstantiation,
686 TemplateDecl *Template,
687 ArrayRef<TemplateArgument> TemplateArgs,
688 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
690 SemaRef,
691 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
692 PointOfInstantiation, InstantiationRange, Template, nullptr,
693 TemplateArgs, &DeductionInfo) {}
694
696 Sema &SemaRef, SourceLocation PointOfInstantiation,
698 ArrayRef<TemplateArgument> TemplateArgs,
699 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
701 SemaRef,
702 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
703 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
704 TemplateArgs, &DeductionInfo) {}
705
707 Sema &SemaRef, SourceLocation PointOfInstantiation,
709 ArrayRef<TemplateArgument> TemplateArgs,
710 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
712 SemaRef,
713 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
714 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
715 TemplateArgs, &DeductionInfo) {}
716
718 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
719 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
721 SemaRef,
722 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
723 PointOfInstantiation, InstantiationRange, Param, nullptr,
724 TemplateArgs) {}
725
727 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
729 SourceRange InstantiationRange)
731 SemaRef,
732 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
733 PointOfInstantiation, InstantiationRange, Param, Template,
734 TemplateArgs) {}
735
737 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
739 SourceRange InstantiationRange)
741 SemaRef,
742 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
743 PointOfInstantiation, InstantiationRange, Param, Template,
744 TemplateArgs) {}
745
747 Sema &SemaRef, SourceLocation PointOfInstantiation,
749 SourceRange InstantiationRange)
751 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
752 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
753 /*Template=*/nullptr, TemplateArgs) {}
754
756 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
757 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
758 SourceRange InstantiationRange)
760 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
761 PointOfInstantiation, InstantiationRange, Param, Template,
762 TemplateArgs) {}
763
765 Sema &SemaRef, SourceLocation PointOfInstantiation,
767 SourceRange InstantiationRange)
769 SemaRef, CodeSynthesisContext::RequirementInstantiation,
770 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
771 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
772}
773
775 Sema &SemaRef, SourceLocation PointOfInstantiation,
777 SourceRange InstantiationRange)
779 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
780 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
781 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
782
784 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
785 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
787 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
788 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
789 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
790}
791
793 Sema &SemaRef, SourceLocation PointOfInstantiation,
794 ConstraintsCheck, NamedDecl *Template,
795 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
798 PointOfInstantiation, InstantiationRange, Template, nullptr,
799 TemplateArgs) {}
800
802 Sema &SemaRef, SourceLocation PointOfInstantiation,
804 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
807 PointOfInstantiation, InstantiationRange, Template, nullptr,
808 {}, &DeductionInfo) {}
809
811 Sema &SemaRef, SourceLocation PointOfInstantiation,
813 SourceRange InstantiationRange)
816 PointOfInstantiation, InstantiationRange, Template) {}
817
819 Sema &SemaRef, SourceLocation PointOfInstantiation,
821 SourceRange InstantiationRange)
824 PointOfInstantiation, InstantiationRange, Template) {}
825
827 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
828 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
830 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
831 PointOfInstantiation, InstantiationRange, Entity) {}
832
833
837
838 CodeSynthesisContexts.push_back(Ctx);
839
840 if (!Ctx.isInstantiationRecord())
842
843 // Check to see if we're low on stack space. We can't do anything about this
844 // from here, but we can at least warn the user.
847}
848
850 auto &Active = CodeSynthesisContexts.back();
851 if (!Active.isInstantiationRecord()) {
852 assert(NonInstantiationEntries > 0);
854 }
855
856 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
857
858 // Name lookup no longer looks in this template's defining module.
859 assert(CodeSynthesisContexts.size() >=
861 "forgot to remove a lookup module for a template instantiation");
862 if (CodeSynthesisContexts.size() ==
865 LookupModulesCache.erase(M);
867 }
868
869 // If we've left the code synthesis context for the current context stack,
870 // stop remembering that we've emitted that stack.
871 if (CodeSynthesisContexts.size() ==
874
875 CodeSynthesisContexts.pop_back();
876}
877
879 if (!Invalid) {
880 if (!AlreadyInstantiating) {
881 auto &Active = SemaRef.CodeSynthesisContexts.back();
882 if (Active.Entity)
884 {Active.Entity->getCanonicalDecl(), Active.Kind});
885 }
886
889
891 Invalid = true;
892 }
893}
894
895static std::string convertCallArgsToString(Sema &S,
897 std::string Result;
898 llvm::raw_string_ostream OS(Result);
899 llvm::ListSeparator Comma;
900 for (const Expr *Arg : Args) {
901 OS << Comma;
902 Arg->IgnoreParens()->printPretty(OS, nullptr,
904 }
905 return Result;
906}
907
908bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
909 SourceLocation PointOfInstantiation,
910 SourceRange InstantiationRange) {
913 if ((SemaRef.CodeSynthesisContexts.size() -
915 <= SemaRef.getLangOpts().InstantiationDepth)
916 return false;
917
918 SemaRef.Diag(PointOfInstantiation,
919 diag::err_template_recursion_depth_exceeded)
920 << SemaRef.getLangOpts().InstantiationDepth
921 << InstantiationRange;
922 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
923 << SemaRef.getLangOpts().InstantiationDepth;
924 return true;
925}
926
927/// Prints the current instantiation stack through a series of
928/// notes.
930 // Determine which template instantiations to skip, if any.
931 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
932 unsigned Limit = Diags.getTemplateBacktraceLimit();
933 if (Limit && Limit < CodeSynthesisContexts.size()) {
934 SkipStart = Limit / 2 + Limit % 2;
935 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
936 }
937
938 // FIXME: In all of these cases, we need to show the template arguments
939 unsigned InstantiationIdx = 0;
941 Active = CodeSynthesisContexts.rbegin(),
942 ActiveEnd = CodeSynthesisContexts.rend();
943 Active != ActiveEnd;
944 ++Active, ++InstantiationIdx) {
945 // Skip this instantiation?
946 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
947 if (InstantiationIdx == SkipStart) {
948 // Note that we're skipping instantiations.
949 Diags.Report(Active->PointOfInstantiation,
950 diag::note_instantiation_contexts_suppressed)
951 << unsigned(CodeSynthesisContexts.size() - Limit);
952 }
953 continue;
954 }
955
956 switch (Active->Kind) {
958 Decl *D = Active->Entity;
959 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
960 unsigned DiagID = diag::note_template_member_class_here;
961 if (isa<ClassTemplateSpecializationDecl>(Record))
962 DiagID = diag::note_template_class_instantiation_here;
963 Diags.Report(Active->PointOfInstantiation, DiagID)
964 << Record << Active->InstantiationRange;
965 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
966 unsigned DiagID;
967 if (Function->getPrimaryTemplate())
968 DiagID = diag::note_function_template_spec_here;
969 else
970 DiagID = diag::note_template_member_function_here;
971 Diags.Report(Active->PointOfInstantiation, DiagID)
972 << Function
973 << Active->InstantiationRange;
974 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
975 Diags.Report(Active->PointOfInstantiation,
976 VD->isStaticDataMember()?
977 diag::note_template_static_data_member_def_here
978 : diag::note_template_variable_def_here)
979 << VD
980 << Active->InstantiationRange;
981 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
982 Diags.Report(Active->PointOfInstantiation,
983 diag::note_template_enum_def_here)
984 << ED
985 << Active->InstantiationRange;
986 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
987 Diags.Report(Active->PointOfInstantiation,
988 diag::note_template_nsdmi_here)
989 << FD << Active->InstantiationRange;
990 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
991 Diags.Report(Active->PointOfInstantiation,
992 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 Diags.Report(Active->PointOfInstantiation,
1006 diag::note_default_arg_instantiation_here)
1007 << OS.str()
1008 << Active->InstantiationRange;
1009 break;
1010 }
1011
1013 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
1014 Diags.Report(Active->PointOfInstantiation,
1015 diag::note_explicit_template_arg_substitution_here)
1016 << FnTmpl
1018 Active->TemplateArgs,
1019 Active->NumTemplateArgs)
1020 << Active->InstantiationRange;
1021 break;
1022 }
1023
1025 if (FunctionTemplateDecl *FnTmpl =
1026 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1027 Diags.Report(Active->PointOfInstantiation,
1028 diag::note_function_template_deduction_instantiation_here)
1029 << FnTmpl
1030 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1031 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 Diags.Report(Active->PointOfInstantiation,
1053 diag::note_deduced_template_arg_substitution_here)
1054 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1055 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1056 Active->NumTemplateArgs)
1057 << Active->InstantiationRange;
1058 }
1059 break;
1060 }
1061
1063 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1064 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1065
1066 SmallString<128> TemplateArgsStr;
1067 llvm::raw_svector_ostream OS(TemplateArgsStr);
1069 printTemplateArgumentList(OS, Active->template_arguments(),
1071 Diags.Report(Active->PointOfInstantiation,
1072 diag::note_default_function_arg_instantiation_here)
1073 << OS.str()
1074 << 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 =
1089 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1090 ->getTemplateParameters();
1091 Diags.Report(Active->PointOfInstantiation,
1092 diag::note_prior_template_arg_substitution)
1093 << isa<TemplateTemplateParmDecl>(Parm)
1094 << Name
1095 << getTemplateArgumentBindingsText(TemplateParams,
1096 Active->TemplateArgs,
1097 Active->NumTemplateArgs)
1098 << Active->InstantiationRange;
1099 break;
1100 }
1101
1103 TemplateParameterList *TemplateParams = nullptr;
1104 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1105 TemplateParams = Template->getTemplateParameters();
1106 else
1107 TemplateParams =
1108 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1109 ->getTemplateParameters();
1110
1111 Diags.Report(Active->PointOfInstantiation,
1112 diag::note_template_default_arg_checking)
1113 << getTemplateArgumentBindingsText(TemplateParams,
1114 Active->TemplateArgs,
1115 Active->NumTemplateArgs)
1116 << Active->InstantiationRange;
1117 break;
1118 }
1119
1121 Diags.Report(Active->PointOfInstantiation,
1122 diag::note_evaluating_exception_spec_here)
1123 << cast<FunctionDecl>(Active->Entity);
1124 break;
1125
1127 Diags.Report(Active->PointOfInstantiation,
1128 diag::note_template_exception_spec_instantiation_here)
1129 << cast<FunctionDecl>(Active->Entity)
1130 << Active->InstantiationRange;
1131 break;
1132
1134 Diags.Report(Active->PointOfInstantiation,
1135 diag::note_template_requirement_instantiation_here)
1136 << Active->InstantiationRange;
1137 break;
1139 Diags.Report(Active->PointOfInstantiation,
1140 diag::note_template_requirement_params_instantiation_here)
1141 << Active->InstantiationRange;
1142 break;
1143
1145 Diags.Report(Active->PointOfInstantiation,
1146 diag::note_nested_requirement_here)
1147 << Active->InstantiationRange;
1148 break;
1149
1151 Diags.Report(Active->PointOfInstantiation,
1152 diag::note_in_declaration_of_implicit_special_member)
1153 << cast<CXXRecordDecl>(Active->Entity)
1154 << llvm::to_underlying(Active->SpecialMember);
1155 break;
1156
1158 Diags.Report(Active->Entity->getLocation(),
1159 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);
1168 if (DFK.isSpecialMember()) {
1169 auto *MD = cast<CXXMethodDecl>(FD);
1170 Diags.Report(Active->PointOfInstantiation,
1171 diag::note_member_synthesized_at)
1172 << MD->isExplicitlyDefaulted()
1173 << llvm::to_underlying(DFK.asSpecialMember())
1174 << Context.getTagDeclType(MD->getParent());
1175 } else if (DFK.isComparison()) {
1176 QualType RecordType = FD->getParamDecl(0)
1177 ->getType()
1178 .getNonReferenceType()
1179 .getUnqualifiedType();
1180 Diags.Report(Active->PointOfInstantiation,
1181 diag::note_comparison_synthesized_at)
1182 << (int)DFK.asComparison() << RecordType;
1183 }
1184 break;
1185 }
1186
1188 Diags.Report(Active->Entity->getLocation(),
1189 diag::note_rewriting_operator_as_spaceship);
1190 break;
1191
1193 Diags.Report(Active->PointOfInstantiation,
1194 diag::note_in_binding_decl_init)
1195 << cast<BindingDecl>(Active->Entity);
1196 break;
1197
1199 Diags.Report(Active->PointOfInstantiation,
1200 diag::note_due_to_dllexported_class)
1201 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1202 break;
1203
1205 Diags.Report(Active->PointOfInstantiation,
1206 diag::note_building_builtin_dump_struct_call)
1208 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1209 break;
1210
1212 break;
1213
1215 Diags.Report(Active->PointOfInstantiation,
1216 diag::note_lambda_substitution_here);
1217 break;
1219 unsigned DiagID = 0;
1220 if (!Active->Entity) {
1221 Diags.Report(Active->PointOfInstantiation,
1222 diag::note_nested_requirement_here)
1223 << Active->InstantiationRange;
1224 break;
1225 }
1226 if (isa<ConceptDecl>(Active->Entity))
1227 DiagID = diag::note_concept_specialization_here;
1228 else if (isa<TemplateDecl>(Active->Entity))
1229 DiagID = diag::note_checking_constraints_for_template_id_here;
1230 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1231 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1232 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1233 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1234 else {
1235 assert(isa<FunctionDecl>(Active->Entity));
1236 DiagID = diag::note_checking_constraints_for_function_here;
1237 }
1238 SmallString<128> TemplateArgsStr;
1239 llvm::raw_svector_ostream OS(TemplateArgsStr);
1240 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1241 if (!isa<FunctionDecl>(Active->Entity)) {
1242 printTemplateArgumentList(OS, Active->template_arguments(),
1244 }
1245 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1246 << Active->InstantiationRange;
1247 break;
1248 }
1250 Diags.Report(Active->PointOfInstantiation,
1251 diag::note_constraint_substitution_here)
1252 << Active->InstantiationRange;
1253 break;
1255 Diags.Report(Active->PointOfInstantiation,
1256 diag::note_constraint_normalization_here)
1257 << cast<NamedDecl>(Active->Entity)->getName()
1258 << Active->InstantiationRange;
1259 break;
1261 Diags.Report(Active->PointOfInstantiation,
1262 diag::note_parameter_mapping_substitution_here)
1263 << Active->InstantiationRange;
1264 break;
1266 Diags.Report(Active->PointOfInstantiation,
1267 diag::note_building_deduction_guide_here);
1268 break;
1270 Diags.Report(Active->PointOfInstantiation,
1271 diag::note_template_type_alias_instantiation_here)
1272 << cast<TypeAliasTemplateDecl>(Active->Entity)
1273 << Active->InstantiationRange;
1274 break;
1275 }
1276 }
1277}
1278
1279std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1281 return std::optional<TemplateDeductionInfo *>(nullptr);
1282
1284 Active = CodeSynthesisContexts.rbegin(),
1285 ActiveEnd = CodeSynthesisContexts.rend();
1286 Active != ActiveEnd;
1287 ++Active)
1288 {
1289 switch (Active->Kind) {
1291 // An instantiation of an alias template may or may not be a SFINAE
1292 // context, depending on what else is on the stack.
1293 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1294 break;
1295 [[fallthrough]];
1303 // This is a template instantiation, so there is no SFINAE.
1304 return std::nullopt;
1306 // [temp.deduct]p9
1307 // A lambda-expression appearing in a function type or a template
1308 // parameter is not considered part of the immediate context for the
1309 // purposes of template argument deduction.
1310 // CWG2672: A lambda-expression body is never in the immediate context.
1311 return std::nullopt;
1312
1317 // A default template argument instantiation and substitution into
1318 // template parameters with arguments for prior parameters may or may
1319 // not be a SFINAE context; look further up the stack.
1320 break;
1321
1324 // We're either substituting explicitly-specified template arguments,
1325 // deduced template arguments. SFINAE applies unless we are in a lambda
1326 // body, see [temp.deduct]p9.
1330 // SFINAE always applies in a constraint expression or a requirement
1331 // in a requires expression.
1332 assert(Active->DeductionInfo && "Missing deduction info pointer");
1333 return Active->DeductionInfo;
1334
1342 // This happens in a context unrelated to template instantiation, so
1343 // there is no SFINAE.
1344 return std::nullopt;
1345
1347 // FIXME: This should not be treated as a SFINAE context, because
1348 // we will cache an incorrect exception specification. However, clang
1349 // bootstrap relies this! See PR31692.
1350 break;
1351
1353 break;
1354 }
1355
1356 // The inner context was transparent for SFINAE. If it occurred within a
1357 // non-instantiation SFINAE context, then SFINAE applies.
1358 if (Active->SavedInNonInstantiationSFINAEContext)
1359 return std::optional<TemplateDeductionInfo *>(nullptr);
1360 }
1361
1362 return std::nullopt;
1363}
1364
1365//===----------------------------------------------------------------------===/
1366// Template Instantiation for Types
1367//===----------------------------------------------------------------------===/
1368namespace {
1369 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1370 const MultiLevelTemplateArgumentList &TemplateArgs;
1372 DeclarationName Entity;
1373 // Whether to evaluate the C++20 constraints or simply substitute into them.
1374 bool EvaluateConstraints = true;
1375
1376 public:
1377 typedef TreeTransform<TemplateInstantiator> inherited;
1378
1379 TemplateInstantiator(Sema &SemaRef,
1380 const MultiLevelTemplateArgumentList &TemplateArgs,
1382 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1383 Entity(Entity) {}
1384
1385 void setEvaluateConstraints(bool B) {
1386 EvaluateConstraints = B;
1387 }
1388 bool getEvaluateConstraints() {
1389 return EvaluateConstraints;
1390 }
1391
1392 /// Determine whether the given type \p T has already been
1393 /// transformed.
1394 ///
1395 /// For the purposes of template instantiation, a type has already been
1396 /// transformed if it is NULL or if it is not dependent.
1397 bool AlreadyTransformed(QualType T);
1398
1399 /// Returns the location of the entity being instantiated, if known.
1400 SourceLocation getBaseLocation() { return Loc; }
1401
1402 /// Returns the name of the entity being instantiated, if any.
1403 DeclarationName getBaseEntity() { return Entity; }
1404
1405 /// Sets the "base" location and entity when that
1406 /// information is known based on another transformation.
1407 void setBase(SourceLocation Loc, DeclarationName Entity) {
1408 this->Loc = Loc;
1409 this->Entity = Entity;
1410 }
1411
1412 unsigned TransformTemplateDepth(unsigned Depth) {
1413 return TemplateArgs.getNewDepth(Depth);
1414 }
1415
1416 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1417 int Index = getSema().ArgumentPackSubstitutionIndex;
1418 if (Index == -1)
1419 return std::nullopt;
1420 return Pack.pack_size() - 1 - Index;
1421 }
1422
1423 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1424 SourceRange PatternRange,
1426 bool &ShouldExpand, bool &RetainExpansion,
1427 std::optional<unsigned> &NumExpansions) {
1428 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1429 PatternRange, Unexpanded,
1430 TemplateArgs,
1431 ShouldExpand,
1432 RetainExpansion,
1433 NumExpansions);
1434 }
1435
1436 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1438 }
1439
1440 TemplateArgument ForgetPartiallySubstitutedPack() {
1441 TemplateArgument Result;
1442 if (NamedDecl *PartialPack
1444 MultiLevelTemplateArgumentList &TemplateArgs
1445 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1446 unsigned Depth, Index;
1447 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1448 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1449 Result = TemplateArgs(Depth, Index);
1450 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1451 }
1452 }
1453
1454 return Result;
1455 }
1456
1457 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1458 if (Arg.isNull())
1459 return;
1460
1461 if (NamedDecl *PartialPack
1463 MultiLevelTemplateArgumentList &TemplateArgs
1464 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1465 unsigned Depth, Index;
1466 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1467 TemplateArgs.setArgument(Depth, Index, Arg);
1468 }
1469 }
1470
1471 /// Transform the given declaration by instantiating a reference to
1472 /// this declaration.
1473 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1474
1475 void transformAttrs(Decl *Old, Decl *New) {
1476 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1477 }
1478
1479 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1480 if (Old->isParameterPack()) {
1482 for (auto *New : NewDecls)
1484 Old, cast<VarDecl>(New));
1485 return;
1486 }
1487
1488 assert(NewDecls.size() == 1 &&
1489 "should only have multiple expansions for a pack");
1490 Decl *New = NewDecls.front();
1491
1492 // If we've instantiated the call operator of a lambda or the call
1493 // operator template of a generic lambda, update the "instantiation of"
1494 // information.
1495 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1496 if (NewMD && isLambdaCallOperator(NewMD)) {
1497 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1498 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1499 NewTD->setInstantiatedFromMemberTemplate(
1500 OldMD->getDescribedFunctionTemplate());
1501 else
1502 NewMD->setInstantiationOfMemberFunction(OldMD,
1504 }
1505
1507
1508 // We recreated a local declaration, but not by instantiating it. There
1509 // may be pending dependent diagnostics to produce.
1510 if (auto *DC = dyn_cast<DeclContext>(Old);
1511 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1512 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1513 }
1514
1515 /// Transform the definition of the given declaration by
1516 /// instantiating it.
1517 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1518
1519 /// Transform the first qualifier within a scope by instantiating the
1520 /// declaration.
1521 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1522
1523 bool TransformExceptionSpec(SourceLocation Loc,
1525 SmallVectorImpl<QualType> &Exceptions,
1526 bool &Changed);
1527
1528 /// Rebuild the exception declaration and register the declaration
1529 /// as an instantiated local.
1530 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1532 SourceLocation StartLoc,
1533 SourceLocation NameLoc,
1534 IdentifierInfo *Name);
1535
1536 /// Rebuild the Objective-C exception declaration and register the
1537 /// declaration as an instantiated local.
1538 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1539 TypeSourceInfo *TSInfo, QualType T);
1540
1541 /// Check for tag mismatches when instantiating an
1542 /// elaborated type.
1543 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1544 ElaboratedTypeKeyword Keyword,
1545 NestedNameSpecifierLoc QualifierLoc,
1546 QualType T);
1547
1549 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1550 SourceLocation NameLoc,
1551 QualType ObjectType = QualType(),
1552 NamedDecl *FirstQualifierInScope = nullptr,
1553 bool AllowInjectedClassName = false);
1554
1555 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1556 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1557 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1558 const Stmt *InstS,
1559 const NoInlineAttr *A);
1560 const AlwaysInlineAttr *
1561 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1562 const AlwaysInlineAttr *A);
1563 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1564 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1565 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1566 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1567
1568 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1570 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1572 ExprResult TransformSubstNonTypeTemplateParmExpr(
1574
1575 /// Rebuild a DeclRefExpr for a VarDecl reference.
1576 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1577
1578 /// Transform a reference to a function or init-capture parameter pack.
1579 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1580
1581 /// Transform a FunctionParmPackExpr which was built when we couldn't
1582 /// expand a function parameter pack reference which refers to an expanded
1583 /// pack.
1584 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1585
1586 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1588 // Call the base version; it will forward to our overridden version below.
1589 return inherited::TransformFunctionProtoType(TLB, TL);
1590 }
1591
1592 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1594 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1595 // Special case for transforming a deduction guide, we return a
1596 // transformed TemplateSpecializationType.
1597 if (Type.isNull() &&
1598 SemaRef.CodeSynthesisContexts.back().Kind ==
1600 // Return a TemplateSpecializationType for transforming a deduction
1601 // guide.
1602 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1603 auto Type =
1604 inherited::TransformType(ICT->getInjectedSpecializationType());
1605 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1606 return Type;
1607 }
1608 }
1609 return Type;
1610 }
1611 // Override the default version to handle a rewrite-template-arg-pack case
1612 // for building a deduction guide.
1613 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1614 TemplateArgumentLoc &Output,
1615 bool Uneval = false) {
1616 const TemplateArgument &Arg = Input.getArgument();
1617 std::vector<TemplateArgument> TArgs;
1618 switch (Arg.getKind()) {
1620 // Literally rewrite the template argument pack, instead of unpacking
1621 // it.
1622 for (auto &pack : Arg.getPackAsArray()) {
1624 pack, QualType(), SourceLocation{});
1625 TemplateArgumentLoc Output;
1626 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1627 return true; // fails
1628 TArgs.push_back(Output.getArgument());
1629 }
1630 Output = SemaRef.getTrivialTemplateArgumentLoc(
1631 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1633 return false;
1634 default:
1635 break;
1636 }
1637 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1638 }
1639
1640 template<typename Fn>
1641 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1643 CXXRecordDecl *ThisContext,
1644 Qualifiers ThisTypeQuals,
1645 Fn TransformExceptionSpec);
1646
1647 ParmVarDecl *
1648 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1649 std::optional<unsigned> NumExpansions,
1650 bool ExpectParameterPack);
1651
1652 using inherited::TransformTemplateTypeParmType;
1653 /// Transforms a template type parameter type by performing
1654 /// substitution of the corresponding template type argument.
1655 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1657 bool SuppressObjCLifetime);
1658
1659 QualType BuildSubstTemplateTypeParmType(
1660 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1661 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1662 TemplateArgument Arg, SourceLocation NameLoc);
1663
1664 /// Transforms an already-substituted template type parameter pack
1665 /// into either itself (if we aren't substituting into its pack expansion)
1666 /// or the appropriate substituted argument.
1667 using inherited::TransformSubstTemplateTypeParmPackType;
1668 QualType
1669 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1671 bool SuppressObjCLifetime);
1672
1674 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1675 auto &CCS = SemaRef.CodeSynthesisContexts.back();
1676 if (CCS.Kind ==
1678 unsigned TypeAliasDeclDepth = CCS.Entity->getTemplateDepth();
1679 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1680 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1681 }
1682 return inherited::ComputeLambdaDependency(LSI);
1683 }
1684
1685 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1686 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1688
1689 ExprResult Result = inherited::TransformLambdaExpr(E);
1690 if (Result.isInvalid())
1691 return Result;
1692
1693 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1694 for (ParmVarDecl *PVD : MD->parameters()) {
1695 assert(PVD && "null in a parameter list");
1696 if (!PVD->hasDefaultArg())
1697 continue;
1698 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1699 // FIXME: Obtain the source location for the '=' token.
1700 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1701 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1702 // If substitution fails, the default argument is set to a
1703 // RecoveryExpr that wraps the uninstantiated default argument so
1704 // that downstream diagnostics are omitted.
1705 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1706 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1707 { UninstExpr }, UninstExpr->getType());
1708 if (ErrorResult.isUsable())
1709 PVD->setDefaultArg(ErrorResult.get());
1710 }
1711 }
1712
1713 return Result;
1714 }
1715
1716 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1717 // Currently, we instantiate the body when instantiating the lambda
1718 // expression. However, `EvaluateConstraints` is disabled during the
1719 // instantiation of the lambda expression, causing the instantiation
1720 // failure of the return type requirement in the body. If p0588r1 is fully
1721 // implemented, the body will be lazily instantiated, and this problem
1722 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1723 // `true` to temporarily fix this issue.
1724 // FIXME: This temporary fix can be removed after fully implementing
1725 // p0588r1.
1726 bool Prev = EvaluateConstraints;
1727 EvaluateConstraints = true;
1728 StmtResult Stmt = inherited::TransformLambdaBody(E, Body);
1729 EvaluateConstraints = Prev;
1730 return Stmt;
1731 }
1732
1733 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1734 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1735 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1736 if (TransReq.isInvalid())
1737 return TransReq;
1738 assert(TransReq.get() != E &&
1739 "Do not change value of isSatisfied for the existing expression. "
1740 "Create a new expression instead.");
1741 if (E->getBody()->isDependentContext()) {
1742 Sema::SFINAETrap Trap(SemaRef);
1743 // We recreate the RequiresExpr body, but not by instantiating it.
1744 // Produce pending diagnostics for dependent access check.
1745 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1746 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1747 if (Trap.hasErrorOccurred())
1748 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1749 }
1750 return TransReq;
1751 }
1752
1753 bool TransformRequiresExprRequirements(
1756 bool SatisfactionDetermined = false;
1757 for (concepts::Requirement *Req : Reqs) {
1758 concepts::Requirement *TransReq = nullptr;
1759 if (!SatisfactionDetermined) {
1760 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1761 TransReq = TransformTypeRequirement(TypeReq);
1762 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1763 TransReq = TransformExprRequirement(ExprReq);
1764 else
1765 TransReq = TransformNestedRequirement(
1766 cast<concepts::NestedRequirement>(Req));
1767 if (!TransReq)
1768 return true;
1769 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1770 // [expr.prim.req]p6
1771 // [...] The substitution and semantic constraint checking
1772 // proceeds in lexical order and stops when a condition that
1773 // determines the result of the requires-expression is
1774 // encountered. [..]
1775 SatisfactionDetermined = true;
1776 } else
1777 TransReq = Req;
1778 Transformed.push_back(TransReq);
1779 }
1780 return false;
1781 }
1782
1783 TemplateParameterList *TransformTemplateParameterList(
1784 TemplateParameterList *OrigTPL) {
1785 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1786
1787 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1788 TemplateDeclInstantiator DeclInstantiator(getSema(),
1789 /* DeclContext *Owner */ Owner, TemplateArgs);
1790 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1791 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1792 }
1793
1795 TransformTypeRequirement(concepts::TypeRequirement *Req);
1797 TransformExprRequirement(concepts::ExprRequirement *Req);
1799 TransformNestedRequirement(concepts::NestedRequirement *Req);
1800 ExprResult TransformRequiresTypeParams(
1801 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1804 SmallVectorImpl<ParmVarDecl *> &TransParams,
1806
1807 private:
1809 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1810 const NonTypeTemplateParmDecl *parm,
1812 std::optional<unsigned> PackIndex);
1813 };
1814}
1815
1816bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1817 if (T.isNull())
1818 return true;
1819
1821 return false;
1822
1823 getSema().MarkDeclarationsReferencedInType(Loc, T);
1824 return true;
1825}
1826
1827static TemplateArgument
1829 assert(S.ArgumentPackSubstitutionIndex >= 0);
1830 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1832 if (Arg.isPackExpansion())
1833 Arg = Arg.getPackExpansionPattern();
1834 return Arg;
1835}
1836
1837Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1838 if (!D)
1839 return nullptr;
1840
1841 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1842 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1843 // If the corresponding template argument is NULL or non-existent, it's
1844 // because we are performing instantiation from explicitly-specified
1845 // template arguments in a function template, but there were some
1846 // arguments left unspecified.
1847 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1848 TTP->getPosition()))
1849 return D;
1850
1851 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1852
1853 if (TTP->isParameterPack()) {
1854 assert(Arg.getKind() == TemplateArgument::Pack &&
1855 "Missing argument pack");
1856 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1857 }
1858
1859 TemplateName Template = Arg.getAsTemplate();
1860 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1861 "Wrong kind of template template argument");
1862 return Template.getAsTemplateDecl();
1863 }
1864
1865 // Fall through to find the instantiated declaration for this template
1866 // template parameter.
1867 }
1868
1869 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1870}
1871
1872Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1873 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1874 if (!Inst)
1875 return nullptr;
1876
1877 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1878 return Inst;
1879}
1880
1881bool TemplateInstantiator::TransformExceptionSpec(
1883 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1884 if (ESI.Type == EST_Uninstantiated) {
1885 ESI.instantiate();
1886 Changed = true;
1887 }
1888 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1889}
1890
1891NamedDecl *
1892TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1894 // If the first part of the nested-name-specifier was a template type
1895 // parameter, instantiate that type parameter down to a tag type.
1896 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1897 const TemplateTypeParmType *TTP
1898 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1899
1900 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1901 // FIXME: This needs testing w/ member access expressions.
1902 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1903
1904 if (TTP->isParameterPack()) {
1905 assert(Arg.getKind() == TemplateArgument::Pack &&
1906 "Missing argument pack");
1907
1908 if (getSema().ArgumentPackSubstitutionIndex == -1)
1909 return nullptr;
1910
1911 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1912 }
1913
1914 QualType T = Arg.getAsType();
1915 if (T.isNull())
1916 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1917
1918 if (const TagType *Tag = T->getAs<TagType>())
1919 return Tag->getDecl();
1920
1921 // The resulting type is not a tag; complain.
1922 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1923 return nullptr;
1924 }
1925 }
1926
1927 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1928}
1929
1930VarDecl *
1931TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1933 SourceLocation StartLoc,
1934 SourceLocation NameLoc,
1935 IdentifierInfo *Name) {
1936 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1937 StartLoc, NameLoc, Name);
1938 if (Var)
1939 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1940 return Var;
1941}
1942
1943VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1944 TypeSourceInfo *TSInfo,
1945 QualType T) {
1946 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1947 if (Var)
1948 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1949 return Var;
1950}
1951
1953TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1954 ElaboratedTypeKeyword Keyword,
1955 NestedNameSpecifierLoc QualifierLoc,
1956 QualType T) {
1957 if (const TagType *TT = T->getAs<TagType>()) {
1958 TagDecl* TD = TT->getDecl();
1959
1960 SourceLocation TagLocation = KeywordLoc;
1961
1963
1964 // TODO: should we even warn on struct/class mismatches for this? Seems
1965 // like it's likely to produce a lot of spurious errors.
1966 if (Id && Keyword != ElaboratedTypeKeyword::None &&
1969 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1970 TagLocation, Id)) {
1971 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1972 << Id
1974 TD->getKindName());
1975 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1976 }
1977 }
1978 }
1979
1980 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1981}
1982
1983TemplateName TemplateInstantiator::TransformTemplateName(
1984 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1985 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1986 bool AllowInjectedClassName) {
1988 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1989 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1990 // If the corresponding template argument is NULL or non-existent, it's
1991 // because we are performing instantiation from explicitly-specified
1992 // template arguments in a function template, but there were some
1993 // arguments left unspecified.
1994 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1995 TTP->getPosition()))
1996 return Name;
1997
1998 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1999
2000 if (TemplateArgs.isRewrite()) {
2001 // We're rewriting the template parameter as a reference to another
2002 // template parameter.
2003 if (Arg.getKind() == TemplateArgument::Pack) {
2004 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2005 "unexpected pack arguments in template rewrite");
2006 Arg = Arg.pack_begin()->getPackExpansionPattern();
2007 }
2008 assert(Arg.getKind() == TemplateArgument::Template &&
2009 "unexpected nontype template argument kind in template rewrite");
2010 return Arg.getAsTemplate();
2011 }
2012
2013 auto [AssociatedDecl, Final] =
2014 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2015 std::optional<unsigned> PackIndex;
2016 if (TTP->isParameterPack()) {
2017 assert(Arg.getKind() == TemplateArgument::Pack &&
2018 "Missing argument pack");
2019
2020 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2021 // We have the template argument pack to substitute, but we're not
2022 // actually expanding the enclosing pack expansion yet. So, just
2023 // keep the entire argument pack.
2024 return getSema().Context.getSubstTemplateTemplateParmPack(
2025 Arg, AssociatedDecl, TTP->getIndex(), Final);
2026 }
2027
2028 PackIndex = getPackIndex(Arg);
2029 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2030 }
2031
2032 TemplateName Template = Arg.getAsTemplate();
2033 assert(!Template.isNull() && "Null template template argument");
2034
2035 if (Final)
2036 return Template;
2037 return getSema().Context.getSubstTemplateTemplateParm(
2038 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2039 }
2040 }
2041
2043 = Name.getAsSubstTemplateTemplateParmPack()) {
2044 if (getSema().ArgumentPackSubstitutionIndex == -1)
2045 return Name;
2046
2047 TemplateArgument Pack = SubstPack->getArgumentPack();
2048 TemplateName Template =
2050 if (SubstPack->getFinal())
2051 return Template;
2052 return getSema().Context.getSubstTemplateTemplateParm(
2053 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2054 getPackIndex(Pack));
2055 }
2056
2057 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2058 FirstQualifierInScope,
2059 AllowInjectedClassName);
2060}
2061
2063TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2064 if (!E->isTypeDependent())
2065 return E;
2066
2067 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2068}
2069
2071TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2073 // If the corresponding template argument is NULL or non-existent, it's
2074 // because we are performing instantiation from explicitly-specified
2075 // template arguments in a function template, but there were some
2076 // arguments left unspecified.
2077 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2078 NTTP->getPosition()))
2079 return E;
2080
2081 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2082
2083 if (TemplateArgs.isRewrite()) {
2084 // We're rewriting the template parameter as a reference to another
2085 // template parameter.
2086 if (Arg.getKind() == TemplateArgument::Pack) {
2087 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2088 "unexpected pack arguments in template rewrite");
2089 Arg = Arg.pack_begin()->getPackExpansionPattern();
2090 }
2091 assert(Arg.getKind() == TemplateArgument::Expression &&
2092 "unexpected nontype template argument kind in template rewrite");
2093 // FIXME: This can lead to the same subexpression appearing multiple times
2094 // in a complete expression.
2095 return Arg.getAsExpr();
2096 }
2097
2098 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2099 std::optional<unsigned> PackIndex;
2100 if (NTTP->isParameterPack()) {
2101 assert(Arg.getKind() == TemplateArgument::Pack &&
2102 "Missing argument pack");
2103
2104 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2105 // We have an argument pack, but we can't select a particular argument
2106 // out of it yet. Therefore, we'll build an expression to hold on to that
2107 // argument pack.
2108 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2109 E->getLocation(),
2110 NTTP->getDeclName());
2111 if (TargetType.isNull())
2112 return ExprError();
2113
2114 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2115 if (TargetType->isRecordType())
2116 ExprType.addConst();
2117 // FIXME: Pass in Final.
2119 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2120 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2121 }
2122 PackIndex = getPackIndex(Arg);
2123 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2124 }
2125 // FIXME: Don't put subst node on Final replacement.
2126 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2127 Arg, PackIndex);
2128}
2129
2130const CXXAssumeAttr *
2131TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2132 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2133 if (!Res.isUsable())
2134 return AA;
2135
2136 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2137 AA->getRange());
2138 if (!Res.isUsable())
2139 return AA;
2140
2141 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2142 AA->getRange());
2143}
2144
2145const LoopHintAttr *
2146TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2147 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2148
2149 if (TransformedExpr == LH->getValue())
2150 return LH;
2151
2152 // Generate error if there is a problem with the value.
2153 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2154 LH->getSemanticSpelling() ==
2155 LoopHintAttr::Pragma_unroll))
2156 return LH;
2157
2158 LoopHintAttr::OptionType Option = LH->getOption();
2159 LoopHintAttr::LoopHintState State = LH->getState();
2160
2161 llvm::APSInt ValueAPS =
2162 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2163 // The values of 0 and 1 block any unrolling of the loop.
2164 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2165 Option = LoopHintAttr::Unroll;
2166 State = LoopHintAttr::Disable;
2167 }
2168
2169 // Create new LoopHintValueAttr with integral expression in place of the
2170 // non-type template parameter.
2171 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2172 TransformedExpr, *LH);
2173}
2174const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2175 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2176 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2177 return nullptr;
2178
2179 return A;
2180}
2181const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2182 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2183 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2184 return nullptr;
2185
2186 return A;
2187}
2188
2189const CodeAlignAttr *
2190TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2191 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2192 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2193}
2194
2195ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2196 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2198 std::optional<unsigned> PackIndex) {
2199 ExprResult result;
2200
2201 // Determine the substituted parameter type. We can usually infer this from
2202 // the template argument, but not always.
2203 auto SubstParamType = [&] {
2204 QualType T;
2205 if (parm->isExpandedParameterPack())
2207 else
2208 T = parm->getType();
2209 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2210 T = cast<PackExpansionType>(T)->getPattern();
2211 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2212 };
2213
2214 bool refParam = false;
2215
2216 // The template argument itself might be an expression, in which case we just
2217 // return that expression. This happens when substituting into an alias
2218 // template.
2219 if (arg.getKind() == TemplateArgument::Expression) {
2220 Expr *argExpr = arg.getAsExpr();
2221 result = argExpr;
2222 if (argExpr->isLValue()) {
2223 if (argExpr->getType()->isRecordType()) {
2224 // Check whether the parameter was actually a reference.
2225 QualType paramType = SubstParamType();
2226 if (paramType.isNull())
2227 return ExprError();
2228 refParam = paramType->isReferenceType();
2229 } else {
2230 refParam = true;
2231 }
2232 }
2233 } else if (arg.getKind() == TemplateArgument::Declaration ||
2234 arg.getKind() == TemplateArgument::NullPtr) {
2235 if (arg.getKind() == TemplateArgument::Declaration) {
2236 ValueDecl *VD = arg.getAsDecl();
2237
2238 // Find the instantiation of the template argument. This is
2239 // required for nested templates.
2240 VD = cast_or_null<ValueDecl>(
2241 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2242 if (!VD)
2243 return ExprError();
2244 }
2245
2246 QualType paramType = arg.getNonTypeTemplateArgumentType();
2247 assert(!paramType.isNull() && "type substitution failed for param type");
2248 assert(!paramType->isDependentType() && "param type still dependent");
2249 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2250 refParam = paramType->isReferenceType();
2251 } else {
2252 QualType paramType = arg.getNonTypeTemplateArgumentType();
2254 refParam = paramType->isReferenceType();
2255 assert(result.isInvalid() ||
2257 paramType.getNonReferenceType()));
2258 }
2259
2260 if (result.isInvalid())
2261 return ExprError();
2262
2263 Expr *resultExpr = result.get();
2264 // FIXME: Don't put subst node on final replacement.
2266 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2267 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2268}
2269
2271TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2273 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2274 // We aren't expanding the parameter pack, so just return ourselves.
2275 return E;
2276 }
2277
2280 // FIXME: Don't put subst node on final replacement.
2281 return transformNonTypeTemplateParmRef(
2283 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2284}
2285
2287TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2289 ExprResult SubstReplacement = E->getReplacement();
2290 if (!isa<ConstantExpr>(SubstReplacement.get()))
2291 SubstReplacement = TransformExpr(E->getReplacement());
2292 if (SubstReplacement.isInvalid())
2293 return true;
2294 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2295 if (SubstType.isNull())
2296 return true;
2297 // The type may have been previously dependent and not now, which means we
2298 // might have to implicit cast the argument to the new type, for example:
2299 // template<auto T, decltype(T) U>
2300 // concept C = sizeof(U) == 4;
2301 // void foo() requires C<2, 'a'> { }
2302 // When normalizing foo(), we first form the normalized constraints of C:
2303 // AtomicExpr(sizeof(U) == 4,
2304 // U=SubstNonTypeTemplateParmExpr(Param=U,
2305 // Expr=DeclRef(U),
2306 // Type=decltype(T)))
2307 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2308 // produce:
2309 // AtomicExpr(sizeof(U) == 4,
2310 // U=SubstNonTypeTemplateParmExpr(Param=U,
2311 // Expr=ImpCast(
2312 // decltype(2),
2313 // SubstNTTPE(Param=U, Expr='a',
2314 // Type=char)),
2315 // Type=decltype(2)))
2316 // The call to CheckTemplateArgument here produces the ImpCast.
2317 TemplateArgument SugaredConverted, CanonicalConverted;
2318 if (SemaRef
2320 SubstReplacement.get(), SugaredConverted,
2321 CanonicalConverted, Sema::CTAK_Specified)
2322 .isInvalid())
2323 return true;
2324 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2325 E->getParameter(), E->getExprLoc(),
2326 SugaredConverted, E->getPackIndex());
2327}
2328
2329ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2331 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2332 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2333}
2334
2336TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2337 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2338 // We can expand this parameter pack now.
2340 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2341 if (!VD)
2342 return ExprError();
2343 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2344 }
2345
2346 QualType T = TransformType(E->getType());
2347 if (T.isNull())
2348 return ExprError();
2349
2350 // Transform each of the parameter expansions into the corresponding
2351 // parameters in the instantiation of the function decl.
2353 Vars.reserve(E->getNumExpansions());
2354 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2355 I != End; ++I) {
2356 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2357 if (!D)
2358 return ExprError();
2359 Vars.push_back(D);
2360 }
2361
2362 auto *PackExpr =
2364 E->getParameterPackLocation(), Vars);
2365 getSema().MarkFunctionParmPackReferenced(PackExpr);
2366 return PackExpr;
2367}
2368
2370TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2371 VarDecl *PD) {
2372 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2373 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2374 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2375 assert(Found && "no instantiation for parameter pack");
2376
2377 Decl *TransformedDecl;
2378 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2379 // If this is a reference to a function parameter pack which we can
2380 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2381 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2382 QualType T = TransformType(E->getType());
2383 if (T.isNull())
2384 return ExprError();
2385 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2386 E->getExprLoc(), *Pack);
2387 getSema().MarkFunctionParmPackReferenced(PackExpr);
2388 return PackExpr;
2389 }
2390
2391 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2392 } else {
2393 TransformedDecl = Found->get<Decl*>();
2394 }
2395
2396 // We have either an unexpanded pack or a specific expansion.
2397 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2398}
2399
2401TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2402 NamedDecl *D = E->getDecl();
2403
2404 // Handle references to non-type template parameters and non-type template
2405 // parameter packs.
2406 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2407 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2408 return TransformTemplateParmRefExpr(E, NTTP);
2409
2410 // We have a non-type template parameter that isn't fully substituted;
2411 // FindInstantiatedDecl will find it in the local instantiation scope.
2412 }
2413
2414 // Handle references to function parameter packs.
2415 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2416 if (PD->isParameterPack())
2417 return TransformFunctionParmPackRefExpr(E, PD);
2418
2419 return inherited::TransformDeclRefExpr(E);
2420}
2421
2422ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2423 CXXDefaultArgExpr *E) {
2424 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2425 getDescribedFunctionTemplate() &&
2426 "Default arg expressions are never formed in dependent cases.");
2428 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2429 E->getParam());
2430}
2431
2432template<typename Fn>
2433QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2435 CXXRecordDecl *ThisContext,
2436 Qualifiers ThisTypeQuals,
2437 Fn TransformExceptionSpec) {
2438 // We need a local instantiation scope for this function prototype.
2439 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2440 return inherited::TransformFunctionProtoType(
2441 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2442}
2443
2444ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2445 ParmVarDecl *OldParm, int indexAdjustment,
2446 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2447 auto NewParm = SemaRef.SubstParmVarDecl(
2448 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2449 ExpectParameterPack, EvaluateConstraints);
2450 if (NewParm && SemaRef.getLangOpts().OpenCL)
2452 return NewParm;
2453}
2454
2455QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2456 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2457 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2458 TemplateArgument Arg, SourceLocation NameLoc) {
2459 QualType Replacement = Arg.getAsType();
2460
2461 // If the template parameter had ObjC lifetime qualifiers,
2462 // then any such qualifiers on the replacement type are ignored.
2463 if (SuppressObjCLifetime) {
2464 Qualifiers RQs;
2465 RQs = Replacement.getQualifiers();
2466 RQs.removeObjCLifetime();
2467 Replacement =
2468 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2469 }
2470
2471 if (Final) {
2472 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2473 return Replacement;
2474 }
2475 // TODO: only do this uniquing once, at the start of instantiation.
2476 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2477 Replacement, AssociatedDecl, Index, PackIndex);
2480 NewTL.setNameLoc(NameLoc);
2481 return Result;
2482}
2483
2485TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2487 bool SuppressObjCLifetime) {
2488 const TemplateTypeParmType *T = TL.getTypePtr();
2489 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2490 // Replace the template type parameter with its corresponding
2491 // template argument.
2492
2493 // If the corresponding template argument is NULL or doesn't exist, it's
2494 // because we are performing instantiation from explicitly-specified
2495 // template arguments in a function template class, but there were some
2496 // arguments left unspecified.
2497 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2500 NewTL.setNameLoc(TL.getNameLoc());
2501 return TL.getType();
2502 }
2503
2504 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2505
2506 if (TemplateArgs.isRewrite()) {
2507 // We're rewriting the template parameter as a reference to another
2508 // template parameter.
2509 if (Arg.getKind() == TemplateArgument::Pack) {
2510 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2511 "unexpected pack arguments in template rewrite");
2512 Arg = Arg.pack_begin()->getPackExpansionPattern();
2513 }
2514 assert(Arg.getKind() == TemplateArgument::Type &&
2515 "unexpected nontype template argument kind in template rewrite");
2516 QualType NewT = Arg.getAsType();
2517 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2518 return NewT;
2519 }
2520
2521 auto [AssociatedDecl, Final] =
2522 TemplateArgs.getAssociatedDecl(T->getDepth());
2523 std::optional<unsigned> PackIndex;
2524 if (T->isParameterPack()) {
2525 assert(Arg.getKind() == TemplateArgument::Pack &&
2526 "Missing argument pack");
2527
2528 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2529 // We have the template argument pack, but we're not expanding the
2530 // enclosing pack expansion yet. Just save the template argument
2531 // pack for later substitution.
2532 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2533 AssociatedDecl, T->getIndex(), Final, Arg);
2536 NewTL.setNameLoc(TL.getNameLoc());
2537 return Result;
2538 }
2539
2540 // PackIndex starts from last element.
2541 PackIndex = getPackIndex(Arg);
2542 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2543 }
2544
2545 assert(Arg.getKind() == TemplateArgument::Type &&
2546 "Template argument kind mismatch");
2547
2548 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2549 AssociatedDecl, T->getIndex(),
2550 PackIndex, Arg, TL.getNameLoc());
2551 }
2552
2553 // The template type parameter comes from an inner template (e.g.,
2554 // the template parameter list of a member template inside the
2555 // template we are instantiating). Create a new template type
2556 // parameter with the template "level" reduced by one.
2557 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2558 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2559 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2560 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2561 QualType Result = getSema().Context.getTemplateTypeParmType(
2562 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2563 T->isParameterPack(), NewTTPDecl);
2565 NewTL.setNameLoc(TL.getNameLoc());
2566 return Result;
2567}
2568
2569QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2571 bool SuppressObjCLifetime) {
2573
2574 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2575
2576 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2577 // We aren't expanding the parameter pack, so just return ourselves.
2578 QualType Result = TL.getType();
2579 if (NewReplaced != T->getAssociatedDecl())
2580 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2581 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2584 NewTL.setNameLoc(TL.getNameLoc());
2585 return Result;
2586 }
2587
2588 TemplateArgument Pack = T->getArgumentPack();
2590 return BuildSubstTemplateTypeParmType(
2591 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2592 getPackIndex(Pack), Arg, TL.getNameLoc());
2593}
2594
2597 concepts::EntityPrinter Printer) {
2598 SmallString<128> Message;
2599 SourceLocation ErrorLoc;
2600 if (Info.hasSFINAEDiagnostic()) {
2603 Info.takeSFINAEDiagnostic(PDA);
2604 PDA.second.EmitToString(S.getDiagnostics(), Message);
2605 ErrorLoc = PDA.first;
2606 } else {
2607 ErrorLoc = Info.getLocation();
2608 }
2609 char *MessageBuf = new (S.Context) char[Message.size()];
2610 std::copy(Message.begin(), Message.end(), MessageBuf);
2611 SmallString<128> Entity;
2612 llvm::raw_svector_ostream OS(Entity);
2613 Printer(OS);
2614 char *EntityBuf = new (S.Context) char[Entity.size()];
2615 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2617 StringRef(EntityBuf, Entity.size()), ErrorLoc,
2618 StringRef(MessageBuf, Message.size())};
2619}
2620
2623 EntityPrinter Printer) {
2624 SmallString<128> Entity;
2625 llvm::raw_svector_ostream OS(Entity);
2626 Printer(OS);
2627 char *EntityBuf = new (S.Context) char[Entity.size()];
2628 llvm::copy(Entity, EntityBuf);
2630 /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()),
2631 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2632}
2633
2634ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2635 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2638 SmallVectorImpl<ParmVarDecl *> &TransParams,
2640
2641 TemplateDeductionInfo Info(KWLoc);
2642 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2643 RE, Info,
2644 SourceRange{KWLoc, RBraceLoc});
2646
2647 unsigned ErrorIdx;
2648 if (getDerived().TransformFunctionTypeParams(
2649 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2650 &TransParams, PInfos, &ErrorIdx) ||
2651 Trap.hasErrorOccurred()) {
2653 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2654 // Add a 'failed' Requirement to contain the error that caused the failure
2655 // here.
2656 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2657 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2658 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2659 TransParams, RE->getRParenLoc(),
2660 TransReqs, RBraceLoc);
2661 }
2662
2663 return ExprResult{};
2664}
2665
2667TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2668 if (!Req->isDependent() && !AlwaysRebuild())
2669 return Req;
2670 if (Req->isSubstitutionFailure()) {
2671 if (AlwaysRebuild())
2672 return RebuildTypeRequirement(
2674 return Req;
2675 }
2676
2680 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2681 Req->getType()->getTypeLoc().getSourceRange());
2682 if (TypeInst.isInvalid())
2683 return nullptr;
2684 TypeSourceInfo *TransType = TransformType(Req->getType());
2685 if (!TransType || Trap.hasErrorOccurred())
2686 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2687 [&] (llvm::raw_ostream& OS) {
2688 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2689 }));
2690 return RebuildTypeRequirement(TransType);
2691}
2692
2694TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2695 if (!Req->isDependent() && !AlwaysRebuild())
2696 return Req;
2697
2699
2700 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2701 TransExpr;
2702 if (Req->isExprSubstitutionFailure())
2703 TransExpr = Req->getExprSubstitutionDiagnostic();
2704 else {
2705 Expr *E = Req->getExpr();
2707 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2708 E->getSourceRange());
2709 if (ExprInst.isInvalid())
2710 return nullptr;
2711 ExprResult TransExprRes = TransformExpr(E);
2712 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2713 TransExprRes.get()->hasPlaceholderType())
2714 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2715 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2716 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2717 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2718 });
2719 else
2720 TransExpr = TransExprRes.get();
2721 }
2722
2723 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2724 const auto &RetReq = Req->getReturnTypeRequirement();
2725 if (RetReq.isEmpty())
2726 TransRetReq.emplace();
2727 else if (RetReq.isSubstitutionFailure())
2728 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2729 else if (RetReq.isTypeConstraint()) {
2730 TemplateParameterList *OrigTPL =
2731 RetReq.getTypeConstraintTemplateParameterList();
2732 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2734 Req, Info, OrigTPL->getSourceRange());
2735 if (TPLInst.isInvalid())
2736 return nullptr;
2737 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2738 if (!TPL)
2739 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2740 [&] (llvm::raw_ostream& OS) {
2741 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2742 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2743 }));
2744 else {
2745 TPLInst.Clear();
2746 TransRetReq.emplace(TPL);
2747 }
2748 }
2749 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2750 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2751 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2752 std::move(*TransRetReq));
2753 return RebuildExprRequirement(
2755 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2756}
2757
2759TemplateInstantiator::TransformNestedRequirement(
2761 if (!Req->isDependent() && !AlwaysRebuild())
2762 return Req;
2763 if (Req->hasInvalidConstraint()) {
2764 if (AlwaysRebuild())
2765 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2767 return Req;
2768 }
2770 Req->getConstraintExpr()->getBeginLoc(), Req,
2773 if (!getEvaluateConstraints()) {
2774 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2775 if (TransConstraint.isInvalid() || !TransConstraint.get())
2776 return nullptr;
2777 if (TransConstraint.get()->isInstantiationDependent())
2778 return new (SemaRef.Context)
2779 concepts::NestedRequirement(TransConstraint.get());
2780 ConstraintSatisfaction Satisfaction;
2782 SemaRef.Context, TransConstraint.get(), Satisfaction);
2783 }
2784
2785 ExprResult TransConstraint;
2786 ConstraintSatisfaction Satisfaction;
2788 {
2793 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2795 if (ConstrInst.isInvalid())
2796 return nullptr;
2799 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2800 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2801 !Result.empty())
2802 TransConstraint = Result[0];
2803 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2804 "by CheckConstraintSatisfaction.");
2805 }
2806 if (TransConstraint.isUsable() &&
2807 TransConstraint.get()->isInstantiationDependent())
2808 return new (SemaRef.Context)
2809 concepts::NestedRequirement(TransConstraint.get());
2810 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2811 Satisfaction.HasSubstitutionFailure()) {
2812 SmallString<128> Entity;
2813 llvm::raw_svector_ostream OS(Entity);
2814 Req->getConstraintExpr()->printPretty(OS, nullptr,
2816 char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
2817 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2819 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
2820 }
2822 SemaRef.Context, TransConstraint.get(), Satisfaction);
2823}
2824
2825
2826/// Perform substitution on the type T with a given set of template
2827/// arguments.
2828///
2829/// This routine substitutes the given template arguments into the
2830/// type T and produces the instantiated type.
2831///
2832/// \param T the type into which the template arguments will be
2833/// substituted. If this type is not dependent, it will be returned
2834/// immediately.
2835///
2836/// \param Args the template arguments that will be
2837/// substituted for the top-level template parameters within T.
2838///
2839/// \param Loc the location in the source code where this substitution
2840/// is being performed. It will typically be the location of the
2841/// declarator (if we're instantiating the type of some declaration)
2842/// or the location of the type in the source code (if, e.g., we're
2843/// instantiating the type of a cast expression).
2844///
2845/// \param Entity the name of the entity associated with a declaration
2846/// being instantiated (if any). May be empty to indicate that there
2847/// is no such entity (if, e.g., this is a type that occurs as part of
2848/// a cast expression) or that the entity has no name (e.g., an
2849/// unnamed function parameter).
2850///
2851/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2852/// acceptable as the top level type of the result.
2853///
2854/// \returns If the instantiation succeeds, the instantiated
2855/// type. Otherwise, produces diagnostics and returns a NULL type.
2859 DeclarationName Entity,
2860 bool AllowDeducedTST) {
2861 assert(!CodeSynthesisContexts.empty() &&
2862 "Cannot perform an instantiation without some context on the "
2863 "instantiation stack");
2864
2865 if (!T->getType()->isInstantiationDependentType() &&
2866 !T->getType()->isVariablyModifiedType())
2867 return T;
2868
2869 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2870 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2871 : Instantiator.TransformType(T);
2872}
2873
2877 DeclarationName Entity) {
2878 assert(!CodeSynthesisContexts.empty() &&
2879 "Cannot perform an instantiation without some context on the "
2880 "instantiation stack");
2881
2882 if (TL.getType().isNull())
2883 return nullptr;
2884
2887 // FIXME: Make a copy of the TypeLoc data here, so that we can
2888 // return a new TypeSourceInfo. Inefficient!
2889 TypeLocBuilder TLB;
2890 TLB.pushFullCopy(TL);
2891 return TLB.getTypeSourceInfo(Context, TL.getType());
2892 }
2893
2894 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2895 TypeLocBuilder TLB;
2896 TLB.reserve(TL.getFullDataSize());
2897 QualType Result = Instantiator.TransformType(TLB, TL);
2898 if (Result.isNull())
2899 return nullptr;
2900
2901 return TLB.getTypeSourceInfo(Context, Result);
2902}
2903
2904/// Deprecated form of the above.
2906 const MultiLevelTemplateArgumentList &TemplateArgs,
2908 assert(!CodeSynthesisContexts.empty() &&
2909 "Cannot perform an instantiation without some context on the "
2910 "instantiation stack");
2911
2912 // If T is not a dependent type or a variably-modified type, there
2913 // is nothing to do.
2915 return T;
2916
2917 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2918 return Instantiator.TransformType(T);
2919}
2920
2922 if (T->getType()->isInstantiationDependentType() ||
2923 T->getType()->isVariablyModifiedType())
2924 return true;
2925
2926 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2927 if (!TL.getAs<FunctionProtoTypeLoc>())
2928 return false;
2929
2931 for (ParmVarDecl *P : FP.getParams()) {
2932 // This must be synthesized from a typedef.
2933 if (!P) continue;
2934
2935 // If there are any parameters, a new TypeSourceInfo that refers to the
2936 // instantiated parameters must be built.
2937 return true;
2938 }
2939
2940 return false;
2941}
2942
2943/// A form of SubstType intended specifically for instantiating the
2944/// type of a FunctionDecl. Its purpose is solely to force the
2945/// instantiation of default-argument expressions and to avoid
2946/// instantiating an exception-specification.
2950 DeclarationName Entity,
2951 CXXRecordDecl *ThisContext,
2952 Qualifiers ThisTypeQuals,
2953 bool EvaluateConstraints) {
2954 assert(!CodeSynthesisContexts.empty() &&
2955 "Cannot perform an instantiation without some context on the "
2956 "instantiation stack");
2957
2959 return T;
2960
2961 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2962 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2963
2964 TypeLocBuilder TLB;
2965
2966 TypeLoc TL = T->getTypeLoc();
2967 TLB.reserve(TL.getFullDataSize());
2968
2970
2971 if (FunctionProtoTypeLoc Proto =
2973 // Instantiate the type, other than its exception specification. The
2974 // exception specification is instantiated in InitFunctionInstantiation
2975 // once we've built the FunctionDecl.
2976 // FIXME: Set the exception specification to EST_Uninstantiated here,
2977 // instead of rebuilding the function type again later.
2978 Result = Instantiator.TransformFunctionProtoType(
2979 TLB, Proto, ThisContext, ThisTypeQuals,
2981 bool &Changed) { return false; });
2982 } else {
2983 Result = Instantiator.TransformType(TLB, TL);
2984 }
2985 // When there are errors resolving types, clang may use IntTy as a fallback,
2986 // breaking our assumption that function declarations have function types.
2987 if (Result.isNull() || !Result->isFunctionType())
2988 return nullptr;
2989
2990 return TLB.getTypeSourceInfo(Context, Result);
2991}
2992
2995 SmallVectorImpl<QualType> &ExceptionStorage,
2996 const MultiLevelTemplateArgumentList &Args) {
2997 bool Changed = false;
2998 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2999 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3000 Changed);
3001}
3002
3004 const MultiLevelTemplateArgumentList &Args) {
3007
3008 SmallVector<QualType, 4> ExceptionStorage;
3010 ESI, ExceptionStorage, Args))
3011 // On error, recover by dropping the exception specification.
3012 ESI.Type = EST_None;
3013
3014 UpdateExceptionSpec(New, ESI);
3015}
3016
3017namespace {
3018
3019 struct GetContainedInventedTypeParmVisitor :
3020 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3021 TemplateTypeParmDecl *> {
3022 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3023 TemplateTypeParmDecl *>::Visit;
3024
3026 if (T.isNull())
3027 return nullptr;
3028 return Visit(T.getTypePtr());
3029 }
3030 // The deduced type itself.
3031 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3032 const TemplateTypeParmType *T) {
3033 if (!T->getDecl() || !T->getDecl()->isImplicit())
3034 return nullptr;
3035 return T->getDecl();
3036 }
3037
3038 // Only these types can contain 'auto' types, and subsequently be replaced
3039 // by references to invented parameters.
3040
3041 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
3042 return Visit(T->getNamedType());
3043 }
3044
3045 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3046 return Visit(T->getPointeeType());
3047 }
3048
3049 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3050 return Visit(T->getPointeeType());
3051 }
3052
3053 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3054 return Visit(T->getPointeeTypeAsWritten());
3055 }
3056
3057 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3058 return Visit(T->getPointeeType());
3059 }
3060
3061 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3062 return Visit(T->getElementType());
3063 }
3064
3065 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3067 return Visit(T->getElementType());
3068 }
3069
3070 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3071 return Visit(T->getElementType());
3072 }
3073
3074 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3075 return VisitFunctionType(T);
3076 }
3077
3078 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3079 return Visit(T->getReturnType());
3080 }
3081
3082 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3083 return Visit(T->getInnerType());
3084 }
3085
3086 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3087 return Visit(T->getModifiedType());
3088 }
3089
3090 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3091 return Visit(T->getUnderlyingType());
3092 }
3093
3094 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3095 return Visit(T->getOriginalType());
3096 }
3097
3098 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3099 return Visit(T->getPattern());
3100 }
3101 };
3102
3103} // namespace
3104
3106 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3107 const MultiLevelTemplateArgumentList &TemplateArgs,
3108 bool EvaluateConstraints) {
3109 const ASTTemplateArgumentListInfo *TemplArgInfo =
3111
3112 if (!EvaluateConstraints) {
3115 return false;
3116 }
3117
3118 TemplateArgumentListInfo InstArgs;
3119
3120 if (TemplArgInfo) {
3121 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3122 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3123 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3124 InstArgs))
3125 return true;
3126 }
3127 return AttachTypeConstraint(
3129 TC->getNamedConcept(),
3130 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3131 Inst->isParameterPack()
3132 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3133 ->getEllipsisLoc()
3134 : SourceLocation());
3135}
3136
3138 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3139 int indexAdjustment, std::optional<unsigned> NumExpansions,
3140 bool ExpectParameterPack, bool EvaluateConstraint) {
3141 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3142 TypeSourceInfo *NewDI = nullptr;
3143
3144 TypeLoc OldTL = OldDI->getTypeLoc();
3145 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3146
3147 // We have a function parameter pack. Substitute into the pattern of the
3148 // expansion.
3149 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3150 OldParm->getLocation(), OldParm->getDeclName());
3151 if (!NewDI)
3152 return nullptr;
3153
3154 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3155 // We still have unexpanded parameter packs, which means that
3156 // our function parameter is still a function parameter pack.
3157 // Therefore, make its type a pack expansion type.
3158 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3159 NumExpansions);
3160 } else if (ExpectParameterPack) {
3161 // We expected to get a parameter pack but didn't (because the type
3162 // itself is not a pack expansion type), so complain. This can occur when
3163 // the substitution goes through an alias template that "loses" the
3164 // pack expansion.
3165 Diag(OldParm->getLocation(),
3166 diag::err_function_parameter_pack_without_parameter_packs)
3167 << NewDI->getType();
3168 return nullptr;
3169 }
3170 } else {
3171 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3172 OldParm->getDeclName());
3173 }
3174
3175 if (!NewDI)
3176 return nullptr;
3177
3178 if (NewDI->getType()->isVoidType()) {
3179 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3180 return nullptr;
3181 }
3182
3183 // In abbreviated templates, TemplateTypeParmDecls with possible
3184 // TypeConstraints are created when the parameter list is originally parsed.
3185 // The TypeConstraints can therefore reference other functions parameters in
3186 // the abbreviated function template, which is why we must instantiate them
3187 // here, when the instantiated versions of those referenced parameters are in
3188 // scope.
3189 if (TemplateTypeParmDecl *TTP =
3190 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3191 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3192 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3193 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3194 // We will first get here when instantiating the abbreviated function
3195 // template's described function, but we might also get here later.
3196 // Make sure we do not instantiate the TypeConstraint more than once.
3197 if (Inst && !Inst->getTypeConstraint()) {
3198 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3199 return nullptr;
3200 }
3201 }
3202 }
3203
3205 OldParm->getInnerLocStart(),
3206 OldParm->getLocation(),
3207 OldParm->getIdentifier(),
3208 NewDI->getType(), NewDI,
3209 OldParm->getStorageClass());
3210 if (!NewParm)
3211 return nullptr;
3212
3213 // Mark the (new) default argument as uninstantiated (if any).
3214 if (OldParm->hasUninstantiatedDefaultArg()) {
3215 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3216 NewParm->setUninstantiatedDefaultArg(Arg);
3217 } else if (OldParm->hasUnparsedDefaultArg()) {
3218 NewParm->setUnparsedDefaultArg();
3219 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3220 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3221 // Default arguments cannot be substituted until the declaration context
3222 // for the associated function or lambda capture class is available.
3223 // This is necessary for cases like the following where construction of
3224 // the lambda capture class for the outer lambda is dependent on the
3225 // parameter types but where the default argument is dependent on the
3226 // outer lambda's declaration context.
3227 // template <typename T>
3228 // auto f() {
3229 // return [](T = []{ return T{}; }()) { return 0; };
3230 // }
3231 NewParm->setUninstantiatedDefaultArg(Arg);
3232 }
3233
3237
3238 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3239 // Add the new parameter to the instantiated parameter pack.
3241 } else {
3242 // Introduce an Old -> New mapping
3244 }
3245
3246 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3247 // can be anything, is this right ?
3248 NewParm->setDeclContext(CurContext);
3249
3250 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3251 OldParm->getFunctionScopeIndex() + indexAdjustment);
3252
3253 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3254
3255 return NewParm;
3256}
3257
3258/// Substitute the given template arguments into the given set of
3259/// parameters, producing the set of parameter types that would be generated
3260/// from such a substitution.
3263 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3264 const MultiLevelTemplateArgumentList &TemplateArgs,
3265 SmallVectorImpl<QualType> &ParamTypes,
3267 ExtParameterInfoBuilder &ParamInfos) {
3268 assert(!CodeSynthesisContexts.empty() &&
3269 "Cannot perform an instantiation without some context on the "
3270 "instantiation stack");
3271
3272 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3273 DeclarationName());
3274 return Instantiator.TransformFunctionTypeParams(
3275 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3276}
3277
3278/// Substitute the given template arguments into the default argument.
3281 ParmVarDecl *Param,
3282 const MultiLevelTemplateArgumentList &TemplateArgs,
3283 bool ForCallExpr) {
3284 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3285 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3286
3289
3290 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3291 if (Inst.isInvalid())
3292 return true;
3293 if (Inst.isAlreadyInstantiating()) {
3294 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3295 Param->setInvalidDecl();
3296 return true;
3297 }
3298
3300 {
3301 // C++ [dcl.fct.default]p5:
3302 // The names in the [default argument] expression are bound, and
3303 // the semantic constraints are checked, at the point where the
3304 // default argument expression appears.
3305 ContextRAII SavedContext(*this, FD);
3306 std::unique_ptr<LocalInstantiationScope> LIS;
3307 MultiLevelTemplateArgumentList NewTemplateArgs = TemplateArgs;
3308
3309 if (ForCallExpr) {
3310 // When instantiating a default argument due to use in a call expression,
3311 // an instantiation scope that includes the parameters of the callee is
3312 // required to satisfy references from the default argument. For example:
3313 // template<typename T> void f(T a, int = decltype(a)());
3314 // void g() { f(0); }
3315 LIS = std::make_unique<LocalInstantiationScope>(*this);
3317 /*ForDefinition*/ false);
3318 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3319 return true;
3320 const FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
3321 if (PrimaryTemplate && PrimaryTemplate->isOutOfLine()) {
3322 TemplateArgumentList *CurrentTemplateArgumentList =
3324 TemplateArgs.getInnermost());
3325 NewTemplateArgs = getTemplateInstantiationArgs(
3326 FD, FD->getDeclContext(), /*Final=*/false,
3327 CurrentTemplateArgumentList->asArray(), /*RelativeToPrimary=*/true);
3328 }
3329 }
3330
3332 Result = SubstInitializer(PatternExpr, NewTemplateArgs,
3333 /*DirectInit*/ false);
3334 });
3335 }
3336 if (Result.isInvalid())
3337 return true;
3338
3339 if (ForCallExpr) {
3340 // Check the expression as an initializer for the parameter.
3341 InitializedEntity Entity
3344 Param->getLocation(),
3345 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3346 Expr *ResultE = Result.getAs<Expr>();
3347
3348 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3349 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3350 if (Result.isInvalid())
3351 return true;
3352
3353 Result =
3355 /*DiscardedValue*/ false);
3356 } else {
3357 // FIXME: Obtain the source location for the '=' token.
3358 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3359 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3360 }
3361 if (Result.isInvalid())
3362 return true;
3363
3364 // Remember the instantiated default argument.
3365 Param->setDefaultArg(Result.getAs<Expr>());
3366
3367 return false;
3368}
3369
3370/// Perform substitution on the base class specifiers of the
3371/// given class template specialization.
3372///
3373/// Produces a diagnostic and returns true on error, returns false and
3374/// attaches the instantiated base classes to the class template
3375/// specialization if successful.
3376bool
3378 CXXRecordDecl *Pattern,
3379 const MultiLevelTemplateArgumentList &TemplateArgs) {
3380 bool Invalid = false;
3381 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3382 for (const auto &Base : Pattern->bases()) {
3383 if (!Base.getType()->isDependentType()) {
3384 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3385 if (RD->isInvalidDecl())
3386 Instantiation->setInvalidDecl();
3387 }
3388 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3389 continue;
3390 }
3391
3392 SourceLocation EllipsisLoc;
3393 TypeSourceInfo *BaseTypeLoc;
3394 if (Base.isPackExpansion()) {
3395 // This is a pack expansion. See whether we should expand it now, or
3396 // wait until later.
3398 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3399 Unexpanded);
3400 bool ShouldExpand = false;
3401 bool RetainExpansion = false;
3402 std::optional<unsigned> NumExpansions;
3403 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3404 Base.getSourceRange(),
3405 Unexpanded,
3406 TemplateArgs, ShouldExpand,
3407 RetainExpansion,
3408 NumExpansions)) {
3409 Invalid = true;
3410 continue;
3411 }
3412
3413 // If we should expand this pack expansion now, do so.
3414 if (ShouldExpand) {
3415 for (unsigned I = 0; I != *NumExpansions; ++I) {
3416 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3417
3418 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3419 TemplateArgs,
3420 Base.getSourceRange().getBegin(),
3421 DeclarationName());
3422 if (!BaseTypeLoc) {
3423 Invalid = true;
3424 continue;
3425 }
3426
3427 if (CXXBaseSpecifier *InstantiatedBase
3428 = CheckBaseSpecifier(Instantiation,
3429 Base.getSourceRange(),
3430 Base.isVirtual(),
3431 Base.getAccessSpecifierAsWritten(),
3432 BaseTypeLoc,
3433 SourceLocation()))
3434 InstantiatedBases.push_back(InstantiatedBase);
3435 else
3436 Invalid = true;
3437 }
3438
3439 continue;
3440 }
3441
3442 // The resulting base specifier will (still) be a pack expansion.
3443 EllipsisLoc = Base.getEllipsisLoc();
3444 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3445 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3446 TemplateArgs,
3447 Base.getSourceRange().getBegin(),
3448 DeclarationName());
3449 } else {
3450 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3451 TemplateArgs,
3452 Base.getSourceRange().getBegin(),
3453 DeclarationName());
3454 }
3455
3456 if (!BaseTypeLoc) {
3457 Invalid = true;
3458 continue;
3459 }
3460
3461 if (CXXBaseSpecifier *InstantiatedBase
3462 = CheckBaseSpecifier(Instantiation,
3463 Base.getSourceRange(),
3464 Base.isVirtual(),
3465 Base.getAccessSpecifierAsWritten(),
3466 BaseTypeLoc,
3467 EllipsisLoc))
3468 InstantiatedBases.push_back(InstantiatedBase);
3469 else
3470 Invalid = true;
3471 }
3472
3473 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3474 Invalid = true;
3475
3476 return Invalid;
3477}
3478
3479// Defined via #include from SemaTemplateInstantiateDecl.cpp
3480namespace clang {
3481 namespace sema {
3483 const MultiLevelTemplateArgumentList &TemplateArgs);
3485 const Attr *At, ASTContext &C, Sema &S,
3486 const MultiLevelTemplateArgumentList &TemplateArgs);
3487 }
3488}
3489
3490/// Instantiate the definition of a class from a given pattern.
3491///
3492/// \param PointOfInstantiation The point of instantiation within the
3493/// source code.
3494///
3495/// \param Instantiation is the declaration whose definition is being
3496/// instantiated. This will be either a class template specialization
3497/// or a member class of a class template specialization.
3498///
3499/// \param Pattern is the pattern from which the instantiation
3500/// occurs. This will be either the declaration of a class template or
3501/// the declaration of a member class of a class template.
3502///
3503/// \param TemplateArgs The template arguments to be substituted into
3504/// the pattern.
3505///
3506/// \param TSK the kind of implicit or explicit instantiation to perform.
3507///
3508/// \param Complain whether to complain if the class cannot be instantiated due
3509/// to the lack of a definition.
3510///
3511/// \returns true if an error occurred, false otherwise.
3512bool
3514 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3515 const MultiLevelTemplateArgumentList &TemplateArgs,
3517 bool Complain) {
3518 CXXRecordDecl *PatternDef
3519 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3520 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3521 Instantiation->getInstantiatedFromMemberClass(),
3522 Pattern, PatternDef, TSK, Complain))
3523 return true;
3524
3525 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3526 std::string Name;
3527 llvm::raw_string_ostream OS(Name);
3528 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3529 /*Qualified=*/true);
3530 return Name;
3531 });
3532
3533 Pattern = PatternDef;
3534
3535 // Record the point of instantiation.
3536 if (MemberSpecializationInfo *MSInfo
3537 = Instantiation->getMemberSpecializationInfo()) {
3538 MSInfo->setTemplateSpecializationKind(TSK);
3539 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3540 } else if (ClassTemplateSpecializationDecl *Spec
3541 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3542 Spec->setTemplateSpecializationKind(TSK);
3543 Spec->setPointOfInstantiation(PointOfInstantiation);
3544 }
3545
3546 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3547 if (Inst.isInvalid())
3548 return true;
3549 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3550 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3551 "instantiating class definition");
3552
3553 // Enter the scope of this instantiation. We don't use
3554 // PushDeclContext because we don't have a scope.
3555 ContextRAII SavedContext(*this, Instantiation);
3558
3559 // If this is an instantiation of a local class, merge this local
3560 // instantiation scope with the enclosing scope. Otherwise, every
3561 // instantiation of a class has its own local instantiation scope.
3562 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3563 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3564
3565 // Some class state isn't processed immediately but delayed till class
3566 // instantiation completes. We may not be ready to handle any delayed state
3567 // already on the stack as it might correspond to a different class, so save
3568 // it now and put it back later.
3569 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3570
3571 // Pull attributes from the pattern onto the instantiation.
3572 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3573
3574 // Start the definition of this instantiation.
3575 Instantiation->startDefinition();
3576
3577 // The instantiation is visible here, even if it was first declared in an
3578 // unimported module.
3579 Instantiation->setVisibleDespiteOwningModule();
3580
3581 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3582 Instantiation->setTagKind(Pattern->getTagKind());
3583
3584 // Do substitution on the base class specifiers.
3585 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3586 Instantiation->setInvalidDecl();
3587
3588 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3589 Instantiator.setEvaluateConstraints(false);
3590 SmallVector<Decl*, 4> Fields;
3591 // Delay instantiation of late parsed attributes.
3592 LateInstantiatedAttrVec LateAttrs;
3593 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3594
3595 bool MightHaveConstexprVirtualFunctions = false;
3596 for (auto *Member : Pattern->decls()) {
3597 // Don't instantiate members not belonging in this semantic context.
3598 // e.g. for:
3599 // @code
3600 // template <int i> class A {
3601 // class B *g;
3602 // };
3603 // @endcode
3604 // 'class B' has the template as lexical context but semantically it is
3605 // introduced in namespace scope.
3606 if (Member->getDeclContext() != Pattern)
3607 continue;
3608
3609 // BlockDecls can appear in a default-member-initializer. They must be the
3610 // child of a BlockExpr, so we only know how to instantiate them from there.
3611 // Similarly, lambda closure types are recreated when instantiating the
3612 // corresponding LambdaExpr.
3613 if (isa<BlockDecl>(Member) ||
3614 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3615 continue;
3616
3617 if (Member->isInvalidDecl()) {
3618 Instantiation->setInvalidDecl();
3619 continue;
3620 }
3621
3622 Decl *NewMember = Instantiator.Visit(Member);
3623 if (NewMember) {
3624 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3625 Fields.push_back(Field);
3626 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3627 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3628 // specialization causes the implicit instantiation of the definitions
3629 // of unscoped member enumerations.
3630 // Record a point of instantiation for this implicit instantiation.
3631 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3632 Enum->isCompleteDefinition()) {
3633 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3634 assert(MSInfo && "no spec info for member enum specialization");
3636 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3637 }
3638 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3639 if (SA->isFailed()) {
3640 // A static_assert failed. Bail out; instantiating this
3641 // class is probably not meaningful.
3642 Instantiation->setInvalidDecl();
3643 break;
3644 }
3645 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3646 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3647 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3648 MightHaveConstexprVirtualFunctions = true;
3649 }
3650
3651 if (NewMember->isInvalidDecl())
3652 Instantiation->setInvalidDecl();
3653 } else {
3654 // FIXME: Eventually, a NULL return will mean that one of the
3655 // instantiations was a semantic disaster, and we'll want to mark the
3656 // declaration invalid.
3657 // For now, we expect to skip some members that we can't yet handle.
3658 }
3659 }
3660
3661 // Finish checking fields.
3662 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3664 CheckCompletedCXXClass(nullptr, Instantiation);
3665
3666 // Default arguments are parsed, if not instantiated. We can go instantiate
3667 // default arg exprs for default constructors if necessary now. Unless we're
3668 // parsing a class, in which case wait until that's finished.
3669 if (ParsingClassDepth == 0)
3671
3672 // Instantiate late parsed attributes, and attach them to their decls.
3673 // See Sema::InstantiateAttrs
3674 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3675 E = LateAttrs.end(); I != E; ++I) {
3676 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3677 CurrentInstantiationScope = I->Scope;
3678
3679 // Allow 'this' within late-parsed attributes.
3680 auto *ND = cast<NamedDecl>(I->NewDecl);
3681 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3682 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3683 ND->isCXXInstanceMember());
3684
3685 Attr *NewAttr =
3686 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3687 if (NewAttr)
3688 I->NewDecl->addAttr(NewAttr);
3690 Instantiator.getStartingScope());
3691 }
3692 Instantiator.disableLateAttributeInstantiation();
3693 LateAttrs.clear();
3694
3696
3697 // FIXME: We should do something similar for explicit instantiations so they
3698 // end up in the right module.
3699 if (TSK == TSK_ImplicitInstantiation) {
3700 Instantiation->setLocation(Pattern->getLocation());
3701 Instantiation->setLocStart(Pattern->getInnerLocStart());
3702 Instantiation->setBraceRange(Pattern->getBraceRange());
3703 }
3704
3705 if (!Instantiation->isInvalidDecl()) {
3706 // Perform any dependent diagnostics from the pattern.
3707 if (Pattern->isDependentContext())
3708 PerformDependentDiagnostics(Pattern, TemplateArgs);
3709
3710 // Instantiate any out-of-line class template partial
3711 // specializations now.
3713 P = Instantiator.delayed_partial_spec_begin(),
3714 PEnd = Instantiator.delayed_partial_spec_end();
3715 P != PEnd; ++P) {
3717 P->first, P->second)) {
3718 Instantiation->setInvalidDecl();
3719 break;
3720 }
3721 }
3722
3723 // Instantiate any out-of-line variable template partial
3724 // specializations now.
3726 P = Instantiator.delayed_var_partial_spec_begin(),
3727 PEnd = Instantiator.delayed_var_partial_spec_end();
3728 P != PEnd; ++P) {
3730 P->first, P->second)) {
3731 Instantiation->setInvalidDecl();
3732 break;
3733 }
3734 }
3735 }
3736
3737 // Exit the scope of this instantiation.
3738 SavedContext.pop();
3739
3740 if (!Instantiation->isInvalidDecl()) {
3741 // Always emit the vtable for an explicit instantiation definition
3742 // of a polymorphic class template specialization. Otherwise, eagerly
3743 // instantiate only constexpr virtual functions in preparation for their use
3744 // in constant evaluation.
3746 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3747 else if (MightHaveConstexprVirtualFunctions)
3748 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3749 /*ConstexprOnly*/ true);
3750 }
3751
3752 Consumer.HandleTagDeclDefinition(Instantiation);
3753
3754 return Instantiation->isInvalidDecl();
3755}
3756
3757/// Instantiate the definition of an enum from a given pattern.
3758///
3759/// \param PointOfInstantiation The point of instantiation within the
3760/// source code.
3761/// \param Instantiation is the declaration whose definition is being
3762/// instantiated. This will be a member enumeration of a class
3763/// temploid specialization, or a local enumeration within a
3764/// function temploid specialization.
3765/// \param Pattern The templated declaration from which the instantiation
3766/// occurs.
3767/// \param TemplateArgs The template arguments to be substituted into
3768/// the pattern.
3769/// \param TSK The kind of implicit or explicit instantiation to perform.
3770///
3771/// \return \c true if an error occurred, \c false otherwise.
3772bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3773 EnumDecl *Instantiation, EnumDecl *Pattern,
3774 const MultiLevelTemplateArgumentList &TemplateArgs,
3776 EnumDecl *PatternDef = Pattern->getDefinition();
3777 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3778 Instantiation->getInstantiatedFromMemberEnum(),
3779 Pattern, PatternDef, TSK,/*Complain*/true))
3780 return true;
3781 Pattern = PatternDef;
3782
3783 // Record the point of instantiation.
3784 if (MemberSpecializationInfo *MSInfo
3785 = Instantiation->getMemberSpecializationInfo()) {
3786 MSInfo->setTemplateSpecializationKind(TSK);
3787 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3788 }
3789
3790 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3791 if (Inst.isInvalid())
3792 return true;
3793 if (Inst.isAlreadyInstantiating())
3794 return false;
3795 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3796 "instantiating enum definition");
3797
3798 // The instantiation is visible here, even if it was first declared in an
3799 // unimported module.
3800 Instantiation->setVisibleDespiteOwningModule();
3801
3802 // Enter the scope of this instantiation. We don't use
3803 // PushDeclContext because we don't have a scope.
3804 ContextRAII SavedContext(*this, Instantiation);
3807
3808 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3809
3810 // Pull attributes from the pattern onto the instantiation.
3811 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3812
3813 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3814 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3815
3816 // Exit the scope of this instantiation.
3817 SavedContext.pop();
3818
3819 return Instantiation->isInvalidDecl();
3820}
3821
3822
3823/// Instantiate the definition of a field from the given pattern.
3824///
3825/// \param PointOfInstantiation The point of instantiation within the
3826/// source code.
3827/// \param Instantiation is the declaration whose definition is being
3828/// instantiated. This will be a class of a class temploid
3829/// specialization, or a local enumeration within a function temploid
3830/// specialization.
3831/// \param Pattern The templated declaration from which the instantiation
3832/// occurs.
3833/// \param TemplateArgs The template arguments to be substituted into
3834/// the pattern.
3835///
3836/// \return \c true if an error occurred, \c false otherwise.
3838 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3839 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3840 // If there is no initializer, we don't need to do anything.
3841 if (!Pattern->hasInClassInitializer())
3842 return false;
3843
3844 assert(Instantiation->getInClassInitStyle() ==
3845 Pattern->getInClassInitStyle() &&
3846 "pattern and instantiation disagree about init style");
3847
3848 // Error out if we haven't parsed the initializer of the pattern yet because
3849 // we are waiting for the closing brace of the outer class.
3850 Expr *OldInit = Pattern->getInClassInitializer();
3851 if (!OldInit) {
3852 RecordDecl *PatternRD = Pattern->getParent();
3853 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3854 Diag(PointOfInstantiation,
3855 diag::err_default_member_initializer_not_yet_parsed)
3856 << OutermostClass << Pattern;
3857 Diag(Pattern->getEndLoc(),
3858 diag::note_default_member_initializer_not_yet_parsed);
3859 Instantiation->setInvalidDecl();
3860 return true;
3861 }
3862
3863 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3864 if (Inst.isInvalid())
3865 return true;
3866 if (Inst.isAlreadyInstantiating()) {
3867 // Error out if we hit an instantiation cycle for this initializer.
3868 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3869 << Instantiation;
3870 return true;
3871 }
3872 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3873 "instantiating default member init");
3874
3875 // Enter the scope of this instantiation. We don't use PushDeclContext because
3876 // we don't have a scope.
3877 ContextRAII SavedContext(*this, Instantiation->getParent());
3880 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3881 PointOfInstantiation, Instantiation, CurContext};
3882
3883 LocalInstantiationScope Scope(*this, true);
3884
3885 // Instantiate the initializer.
3887 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3888
3889 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3890 /*CXXDirectInit=*/false);
3891 Expr *Init = NewInit.get();
3892 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3894 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3895
3896 if (auto *L = getASTMutationListener())
3897 L->DefaultMemberInitializerInstantiated(Instantiation);
3898
3899 // Return true if the in-class initializer is still missing.
3900 return !Instantiation->getInClassInitializer();
3901}
3902
3903namespace {
3904 /// A partial specialization whose template arguments have matched
3905 /// a given template-id.
3906 struct PartialSpecMatchResult {
3909 };
3910}
3911
3914 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3916 return true;
3917
3919 ClassTemplateSpec->getSpecializedTemplate()
3920 ->getPartialSpecializations(PartialSpecs);
3921 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3923 if (DeduceTemplateArguments(PartialSpecs[I],
3924 ClassTemplateSpec->getTemplateArgs().asArray(),
3926 return true;
3927 }
3928
3929 return false;
3930}
3931
3932/// Get the instantiation pattern to use to instantiate the definition of a
3933/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3934/// template or of a partial specialization).
3937 Sema &S, SourceLocation PointOfInstantiation,
3938 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3940 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3941 if (Inst.isInvalid())
3942 return {/*Invalid=*/true};
3943 if (Inst.isAlreadyInstantiating())
3944 return {/*Invalid=*/false};
3945
3946 llvm::PointerUnion<ClassTemplateDecl *,
3948 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3949 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3950 // Find best matching specialization.
3951 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3952
3953 // C++ [temp.class.spec.match]p1:
3954 // When a class template is used in a context that requires an
3955 // instantiation of the class, it is necessary to determine
3956 // whether the instantiation is to be generated using the primary
3957 // template or one of the partial specializations. This is done by
3958 // matching the template arguments of the class template
3959 // specialization with the template argument lists of the partial
3960 // specializations.
3961 typedef PartialSpecMatchResult MatchResult;
3964 Template->getPartialSpecializations(PartialSpecs);
3965 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3966 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3967 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3968 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3970 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3972 // Store the failed-deduction information for use in diagnostics, later.
3973 // TODO: Actually use the failed-deduction info?
3974 FailedCandidates.addCandidate().set(
3975 DeclAccessPair::make(Template, AS_public), Partial,
3977 (void)Result;
3978 } else {
3979 Matched.push_back(PartialSpecMatchResult());
3980 Matched.back().Partial = Partial;
3981 Matched.back().Args = Info.takeCanonical();
3982 }
3983 }
3984
3985 // If we're dealing with a member template where the template parameters
3986 // have been instantiated, this provides the original template parameters
3987 // from which the member template's parameters were instantiated.
3988
3989 if (Matched.size() >= 1) {
3990 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3991 if (Matched.size() == 1) {
3992 // -- If exactly one matching specialization is found, the
3993 // instantiation is generated from that specialization.
3994 // We don't need to do anything for this.
3995 } else {
3996 // -- If more than one matching specialization is found, the
3997 // partial order rules (14.5.4.2) are used to determine
3998 // whether one of the specializations is more specialized
3999 // than the others. If none of the specializations is more
4000 // specialized than all of the other matching
4001 // specializations, then the use of the class template is
4002 // ambiguous and the program is ill-formed.
4004 PEnd = Matched.end();
4005 P != PEnd; ++P) {
4007 P->Partial, Best->Partial, PointOfInstantiation) ==
4008 P->Partial)
4009 Best = P;
4010 }
4011
4012 // Determine if the best partial specialization is more specialized than
4013 // the others.
4014 bool Ambiguous = false;
4015 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4016 PEnd = Matched.end();
4017 P != PEnd; ++P) {
4019 P->Partial, Best->Partial,
4020 PointOfInstantiation) != Best->Partial) {
4021 Ambiguous = true;
4022 break;
4023 }
4024 }
4025
4026 if (Ambiguous) {
4027 // Partial ordering did not produce a clear winner. Complain.
4028 Inst.Clear();
4029 ClassTemplateSpec->setInvalidDecl();
4030 S.Diag(PointOfInstantiation,
4031 diag::err_partial_spec_ordering_ambiguous)
4032 << ClassTemplateSpec;
4033
4034 // Print the matching partial specializations.
4035 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4036 PEnd = Matched.end();
4037 P != PEnd; ++P)
4038 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4040 P->Partial->getTemplateParameters(), *P->Args);
4041
4042 return {/*Invalid=*/true};
4043 }
4044 }
4045
4046 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4047 } else {
4048 // -- If no matches are found, the instantiation is generated
4049 // from the primary template.
4050 }
4051 }
4052
4053 CXXRecordDecl *Pattern = nullptr;
4054 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4055 if (auto *PartialSpec =
4056 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4057 // Instantiate using the best class template partial specialization.
4058 while (PartialSpec->getInstantiatedFromMember()) {
4059 // If we've found an explicit specialization of this class template,
4060 // stop here and use that as the pattern.
4061 if (PartialSpec->isMemberSpecialization())
4062 break;
4063
4064 PartialSpec = PartialSpec->getInstantiatedFromMember();
4065 }
4066 Pattern = PartialSpec;
4067 } else {
4068 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4069 while (Template->getInstantiatedFromMemberTemplate()) {
4070 // If we've found an explicit specialization of this class template,
4071 // stop here and use that as the pattern.
4072 if (Template->isMemberSpecialization())
4073 break;
4074
4075 Template = Template->getInstantiatedFromMemberTemplate();
4076 }
4077 Pattern = Template->getTemplatedDecl();
4078 }
4079
4080 return Pattern;
4081}
4082
4084 SourceLocation PointOfInstantiation,
4085 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4086 TemplateSpecializationKind TSK, bool Complain) {
4087 // Perform the actual instantiation on the canonical declaration.
4088 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4089 ClassTemplateSpec->getCanonicalDecl());
4090 if (ClassTemplateSpec->isInvalidDecl())
4091 return true;
4092
4094 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4095 ClassTemplateSpec, TSK);
4096 if (!Pattern.isUsable())
4097 return Pattern.isInvalid();
4098
4099 return InstantiateClass(
4100 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4101 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4102}
4103
4104/// Instantiates the definitions of all of the member
4105/// of the given class, which is an instantiation of a class template
4106/// or a member class of a template.
4107void
4109 CXXRecordDecl *Instantiation,
4110 const MultiLevelTemplateArgumentList &TemplateArgs,
4112 // FIXME: We need to notify the ASTMutationListener that we did all of these
4113 // things, in case we have an explicit instantiation definition in a PCM, a
4114 // module, or preamble, and the declaration is in an imported AST.
4115 assert(
4118 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4119 "Unexpected template specialization kind!");
4120 for (auto *D : Instantiation->decls()) {
4121 bool SuppressNew = false;
4122 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4123 if (FunctionDecl *Pattern =
4124 Function->getInstantiatedFromMemberFunction()) {
4125
4126 if (Function->isIneligibleOrNotSelected())
4127 continue;
4128
4129 if (Function->getTrailingRequiresClause()) {
4130 ConstraintSatisfaction Satisfaction;
4131 if (CheckFunctionConstraints(Function, Satisfaction) ||
4132 !Satisfaction.IsSatisfied) {
4133 continue;
4134 }
4135 }
4136
4137 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4138 continue;
4139
4140 MemberSpecializationInfo *MSInfo =
4141 Function->getMemberSpecializationInfo();
4142 assert(MSInfo && "No member specialization information?");
4143 if (MSInfo->getTemplateSpecializationKind()
4145 continue;
4146
4147 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4148 Function,
4150 MSInfo->getPointOfInstantiation(),
4151 SuppressNew) ||
4152 SuppressNew)
4153 continue;
4154
4155 // C++11 [temp.explicit]p8:
4156 // An explicit instantiation definition that names a class template
4157 // specialization explicitly instantiates the class template
4158 // specialization and is only an explicit instantiation definition
4159 // of members whose definition is visible at the point of
4160 // instantiation.
4161 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4162 continue;
4163
4164 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4165
4166 if (Function->isDefined()) {
4167 // Let the ASTConsumer know that this function has been explicitly
4168 // instantiated now, and its linkage might have changed.
4170 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4171 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4172 } else if (TSK == TSK_ImplicitInstantiation) {
4174 std::make_pair(Function, PointOfInstantiation));
4175 }
4176 }
4177 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4178 if (isa<VarTemplateSpecializationDecl>(Var))
4179 continue;
4180
4181 if (Var->isStaticDataMember()) {
4182 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4183 continue;
4184
4186 assert(MSInfo && "No member specialization information?");
4187 if (MSInfo->getTemplateSpecializationKind()
4189 continue;
4190
4191 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4192 Var,
4194 MSInfo->getPointOfInstantiation(),
4195 SuppressNew) ||
4196 SuppressNew)
4197 continue;
4198
4200 // C++0x [temp.explicit]p8:
4201 // An explicit instantiation definition that names a class template
4202 // specialization explicitly instantiates the class template
4203 // specialization and is only an explicit instantiation definition
4204 // of members whose definition is visible at the point of
4205 // instantiation.
4207 continue;
4208
4209 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4210 InstantiateVariableDefinition(PointOfInstantiation, Var);
4211 } else {
4212 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4213 }
4214 }
4215 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4216 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4217 continue;
4218
4219 // Always skip the injected-class-name, along with any
4220 // redeclarations of nested classes, since both would cause us
4221 // to try to instantiate the members of a class twice.
4222 // Skip closure types; they'll get instantiated when we instantiate
4223 // the corresponding lambda-expression.
4224 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4225 Record->isLambda())
4226 continue;
4227
4228 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4229 assert(MSInfo && "No member specialization information?");
4230
4231 if (MSInfo->getTemplateSpecializationKind()
4233 continue;
4234
4235 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4237 // On Windows, explicit instantiation decl of the outer class doesn't
4238 // affect the inner class. Typically extern template declarations are
4239 // used in combination with dll import/export annotations, but those
4240 // are not propagated from the outer class templates to inner classes.
4241 // Therefore, do not instantiate inner classes on this platform, so
4242 // that users don't end up with undefined symbols during linking.
4243 continue;
4244 }
4245
4246 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4247 Record,
4249 MSInfo->getPointOfInstantiation(),
4250 SuppressNew) ||
4251 SuppressNew)
4252 continue;
4253
4255 assert(Pattern && "Missing instantiated-from-template information");
4256
4257 if (!Record->getDefinition()) {
4258 if (!Pattern->getDefinition()) {
4259 // C++0x [temp.explicit]p8:
4260 // An explicit instantiation definition that names a class template
4261 // specialization explicitly instantiates the class template
4262 // specialization and is only an explicit instantiation definition
4263 // of members whose definition is visible at the point of
4264 // instantiation.
4266 MSInfo->setTemplateSpecializationKind(TSK);
4267 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4268 }
4269
4270 continue;
4271 }
4272
4273 InstantiateClass(PointOfInstantiation, Record, Pattern,
4274 TemplateArgs,
4275 TSK);
4276 } else {
4278 Record->getTemplateSpecializationKind() ==
4280 Record->setTemplateSpecializationKind(TSK);
4281 MarkVTableUsed(PointOfInstantiation, Record, true);
4282 }
4283 }
4284
4285 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4286 if (Pattern)
4287 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4288 TSK);
4289 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4290 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4291 assert(MSInfo && "No member specialization information?");
4292
4293 if (MSInfo->getTemplateSpecializationKind()
4295 continue;
4296
4298 PointOfInstantiation, TSK, Enum,
4300 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4301 SuppressNew)
4302 continue;
4303
4304 if (Enum->getDefinition())
4305 continue;
4306
4307 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4308 assert(Pattern && "Missing instantiated-from-template information");
4309
4311 if (!Pattern->getDefinition())
4312 continue;
4313
4314 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4315 } else {
4316 MSInfo->setTemplateSpecializationKind(TSK);
4317 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4318 }
4319 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4320 // No need to instantiate in-class initializers during explicit
4321 // instantiation.
4322 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4323 CXXRecordDecl *ClassPattern =
4324 Instantiation->getTemplateInstantiationPattern();
4326 ClassPattern->lookup(Field->getDeclName());
4327 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4328 assert(Pattern);
4329 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4330 TemplateArgs);
4331 }
4332 }
4333 }
4334}
4335
4336/// Instantiate the definitions of all of the members of the
4337/// given class template specialization, which was named as part of an
4338/// explicit instantiation.
4339void
4341 SourceLocation PointOfInstantiation,
4342 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4344 // C++0x [temp.explicit]p7:
4345 // An explicit instantiation that names a class template
4346 // specialization is an explicit instantion of the same kind
4347 // (declaration or definition) of each of its members (not
4348 // including members inherited from base classes) that has not
4349 // been previously explicitly specialized in the translation unit
4350 // containing the explicit instantiation, except as described
4351 // below.
4352 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4353 getTemplateInstantiationArgs(ClassTemplateSpec),
4354 TSK);
4355}
4356
4359 if (!S)
4360 return S;
4361
4362 TemplateInstantiator Instantiator(*this, TemplateArgs,
4364 DeclarationName());
4365 return Instantiator.TransformStmt(S);
4366}
4367
4369 const TemplateArgumentLoc &Input,
4370 const MultiLevelTemplateArgumentList &TemplateArgs,
4372 const DeclarationName &Entity) {
4373 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4374 return Instantiator.TransformTemplateArgument(Input, Output);
4375}
4376
4379 const MultiLevelTemplateArgumentList &TemplateArgs,
4381 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4382 DeclarationName());
4383 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4384}
4385
4388 if (!E)
4389 return E;
4390
4391 TemplateInstantiator Instantiator(*this, TemplateArgs,
4393 DeclarationName());
4394 return Instantiator.TransformExpr(E);
4395}
4396
4399 const MultiLevelTemplateArgumentList &TemplateArgs) {
4400 // FIXME: should call SubstExpr directly if this function is equivalent or
4401 // should it be different?
4402 return SubstExpr(E, TemplateArgs);
4403}
4404
4406 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4407 if (!E)
4408 return E;
4409
4410 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4411 DeclarationName());
4412 Instantiator.setEvaluateConstraints(false);
4413 return Instantiator.TransformExpr(E);
4414}
4415
4417 const MultiLevelTemplateArgumentList &TemplateArgs,
4418 bool CXXDirectInit) {
4419 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4420 DeclarationName());
4421 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4422}
4423
4424bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4425 const MultiLevelTemplateArgumentList &TemplateArgs,
4426 SmallVectorImpl<Expr *> &Outputs) {
4427 if (Exprs.empty())
4428 return false;
4429
4430 TemplateInstantiator Instantiator(*this, TemplateArgs,
4432 DeclarationName());
4433 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4434 IsCall, Outputs);
4435}
4436
4439 const MultiLevelTemplateArgumentList &TemplateArgs) {
4440 if (!NNS)
4441 return NestedNameSpecifierLoc();
4442
4443 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4444 DeclarationName());
4445 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4446}
4447
4448/// Do template substitution on declaration name info.
4451 const MultiLevelTemplateArgumentList &TemplateArgs) {
4452 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4453 NameInfo.getName());
4454 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4455}
4456
4460 const MultiLevelTemplateArgumentList &TemplateArgs) {
4461 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4462 DeclarationName());
4463 CXXScopeSpec SS;
4464 SS.Adopt(QualifierLoc);
4465 return Instantiator.TransformTemplateName(SS, Name, Loc);
4466}
4467
4468static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4469 // When storing ParmVarDecls in the local instantiation scope, we always
4470 // want to use the ParmVarDecl from the canonical function declaration,
4471 // since the map is then valid for any redeclaration or definition of that
4472 // function.
4473 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4474 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4475 unsigned i = PV->getFunctionScopeIndex();
4476 // This parameter might be from a freestanding function type within the
4477 // function and isn't necessarily referring to one of FD's parameters.
4478 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4479 return FD->getCanonicalDecl()->getParamDecl(i);
4480 }
4481 }
4482 return D;
4483}
4484
4485
4486llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4489 for (LocalInstantiationScope *Current = this; Current;
4490 Current = Current->Outer) {
4491
4492 // Check if we found something within this scope.
4493 const Decl *CheckD = D;
4494 do {
4495 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4496 if (Found != Current->LocalDecls.end())
4497 return &Found->second;
4498
4499 // If this is a tag declaration, it's possible that we need to look for
4500 // a previous declaration.
4501 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4502 CheckD = Tag->getPreviousDecl();
4503 else
4504 CheckD = nullptr;
4505 } while (CheckD);
4506
4507 // If we aren't combined with our outer scope, we're done.
4508 if (!Current->CombineWithOuterScope)
4509 break;
4510 }
4511
4512 // If we're performing a partial substitution during template argument
4513 // deduction, we may not have values for template parameters yet.
4514 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4515 isa<TemplateTemplateParmDecl>(D))
4516 return nullptr;
4517
4518 // Local types referenced prior to definition may require instantiation.
4519 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4520 if (RD->isLocalClass())
4521 return nullptr;
4522
4523 // Enumeration types referenced prior to definition may appear as a result of
4524 // error recovery.
4525 if (isa<EnumDecl>(D))
4526 return nullptr;
4527
4528 // Materialized typedefs/type alias for implicit deduction guides may require
4529 // instantiation.
4530 if (isa<TypedefNameDecl>(D) &&
4531 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4532 return nullptr;
4533
4534 // If we didn't find the decl, then we either have a sema bug, or we have a
4535 // forward reference to a label declaration. Return null to indicate that
4536 // we have an uninstantiated label.
4537 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4538 return nullptr;
4539}
4540
4543 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4544 if (Stored.isNull()) {
4545#ifndef NDEBUG
4546 // It should not be present in any surrounding scope either.
4547 LocalInstantiationScope *Current = this;
4548 while (Current->CombineWithOuterScope && Current->Outer) {
4549 Current = Current->Outer;
4550 assert(!Current->LocalDecls.contains(D) &&
4551 "Instantiated local in inner and outer scopes");
4552 }
4553#endif
4554 Stored = Inst;
4555 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4556 Pack->push_back(cast<VarDecl>(Inst));
4557 } else {
4558 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
4559 }
4560}
4561
4563 VarDecl *Inst) {
4565 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4566 Pack->push_back(Inst);
4567}
4568
4570#ifndef NDEBUG
4571 // This should be the first time we've been told about this decl.
4572 for (LocalInstantiationScope *Current = this;
4573 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4574 assert(!Current->LocalDecls.contains(D) &&
4575 "Creating local pack after instantiation of local");
4576#endif
4577
4579 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4581 Stored = Pack;
4582 ArgumentPacks.push_back(Pack);
4583}
4584
4586 for (DeclArgumentPack *Pack : ArgumentPacks)
4587 if (llvm::is_contained(*Pack, D))
4588 return true;
4589 return false;
4590}
4591
4593 const TemplateArgument *ExplicitArgs,
4594 unsigned NumExplicitArgs) {
4595 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4596 "Already have a partially-substituted pack");
4597 assert((!PartiallySubstitutedPack
4598 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4599 "Wrong number of arguments in partially-substituted pack");
4600 PartiallySubstitutedPack = Pack;
4601 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4602 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4603}
4604
4606 const TemplateArgument **ExplicitArgs,
4607 unsigned *NumExplicitArgs) const {
4608 if (ExplicitArgs)
4609 *ExplicitArgs = nullptr;
4610 if (NumExplicitArgs)
4611 *NumExplicitArgs = 0;
4612
4613 for (const LocalInstantiationScope *Current = this; Current;
4614 Current = Current->Outer) {
4615 if (Current->PartiallySubstitutedPack) {
4616 if (ExplicitArgs)
4617 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4618 if (NumExplicitArgs)
4619 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4620
4621 return Current->PartiallySubstitutedPack;
4622 }
4623
4624 if (!Current->CombineWithOuterScope)
4625 break;
4626 }
4627
4628 return nullptr;
4629}
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.
StringRef P
Defines the C++ template declaration subclasses.
Defines Expressions and AST nodes for C++2a concepts.
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &, QualType)
Definition: InterpFrame.cpp:97
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition: MachO.h:31
MatchFinder::MatchResult MatchResult
uint32_t Id
Definition: SemaARM.cpp:1140
SourceLocation Loc
Definition: SemaObjC.cpp:758
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, concepts::EntityPrinter Printer)
static ActionResult< CXXRecordDecl * > getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...
static std::string convertCallArgsToString(Sema &S, llvm::ArrayRef< const Expr * > Args)
static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg)
Defines utilities for dealing with stack allocation and stack space.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ int
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:72
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1076
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2607
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1600
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2173
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:700
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3314
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3534
Attr - This represents one attribute.
Definition: Attr.h:42
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:5620
Pointer to a block type.
Definition: Type.h:3365
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1264
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition: ExprCXX.h:1338
const ParmVarDecl * getParam() const
Definition: ExprCXX.h:1306
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
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:1685
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1548
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:1876
base_class_range bases()
Definition: DeclCXX.h:619
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1022
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1930
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1905
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1897
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1883
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1916
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
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:199
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1368
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
bool isFileContext() const
Definition: DeclBase.h:2136
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1313
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1833
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1995
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2325
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
SourceLocation getLocation() const
Definition: Expr.h:1336
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:1050
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:261
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
bool isFileContextDecl() const
Definition: DeclBase.cpp:430
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1042
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:296
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1196
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setLocation(SourceLocation L)
Definition: DeclBase.h:446
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:938
DeclContext * getDeclContext()
Definition: DeclBase.h:454
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:358
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:859
The name of a declaration.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:828
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:813
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2040
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3915
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:850
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:631
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6384
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3869
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4128
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For an enumeration member that was instantiated from a member enumeration of a templated class,...
Definition: Decl.cpp:4908
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4934
EnumDecl * getDefinition() const
Definition: Decl.h:3972
This represents one expression.
Definition: Expr.h:110
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
Represents a member of a struct/union/class.
Definition: Decl.h:3059
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4566
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3220
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3214
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3272
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
Represents a function declaration or definition.
Definition: Decl.h:1971
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2685
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:4109
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4158
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2434
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2315
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4642