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