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