clang 24.0.0git
SemaTemplateDeductionGuide.cpp
Go to the documentation of this file.
1//===- SemaTemplateDeductionGude.cpp - Template Argument Deduction---------===//
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//
9// This file implements deduction guides for C++ class template argument
10// deduction.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/TypeLoc.h"
32#include "clang/Basic/LLVM.h"
35#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/Lookup.h"
38#include "clang/Sema/Overload.h"
40#include "clang/Sema/Scope.h"
42#include "clang/Sema/Template.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/ErrorHandling.h"
49#include <cassert>
50#include <optional>
51#include <utility>
52
53using namespace clang;
54using namespace sema;
55
56namespace {
57
58/// Return true if two associated-constraint sets are semantically equal.
59static bool HaveSameAssociatedConstraints(
60 Sema &SemaRef, const NamedDecl *Old, ArrayRef<AssociatedConstraint> OldACs,
62 if (OldACs.size() != NewACs.size())
63 return false;
64 if (OldACs.empty())
65 return true;
66
67 // General case: pairwise compare each associated constraint expression.
69 for (size_t I = 0, E = OldACs.size(); I != E; ++I)
71 Old, OldACs[I].ConstraintExpr, NewInfo, NewACs[I].ConstraintExpr))
72 return false;
73
74 return true;
75}
76
77/// Tree transform to "extract" a transformed type from a class template's
78/// constructor to a deduction guide.
79class ExtractTypeForDeductionGuide
80 : public TreeTransform<ExtractTypeForDeductionGuide> {
81 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
82 ClassTemplateDecl *NestedPattern;
83 const MultiLevelTemplateArgumentList *OuterInstantiationArgs;
84 std::optional<TemplateDeclInstantiator> TypedefNameInstantiator;
85
86public:
87 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
88 ExtractTypeForDeductionGuide(
89 Sema &SemaRef,
90 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs,
91 ClassTemplateDecl *NestedPattern = nullptr,
92 const MultiLevelTemplateArgumentList *OuterInstantiationArgs = nullptr)
93 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs),
94 NestedPattern(NestedPattern),
95 OuterInstantiationArgs(OuterInstantiationArgs) {
96 if (OuterInstantiationArgs)
97 TypedefNameInstantiator.emplace(
98 SemaRef, SemaRef.getASTContext().getTranslationUnitDecl(),
99 *OuterInstantiationArgs);
100 }
101
102 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
103
104 /// Returns true if it's safe to substitute \p Typedef with
105 /// \p OuterInstantiationArgs.
106 bool mightReferToOuterTemplateParameters(TypedefNameDecl *Typedef) {
107 if (!NestedPattern)
108 return false;
109
110 static auto WalkUp = [](DeclContext *DC, DeclContext *TargetDC) {
111 if (DC->Equals(TargetDC))
112 return true;
113 while (DC->isRecord()) {
114 if (DC->Equals(TargetDC))
115 return true;
116 DC = DC->getParent();
117 }
118 return false;
119 };
120
121 if (WalkUp(Typedef->getDeclContext(), NestedPattern->getTemplatedDecl()))
122 return true;
123 if (WalkUp(NestedPattern->getTemplatedDecl(), Typedef->getDeclContext()))
124 return true;
125 return false;
126 }
127
128 QualType RebuildTemplateSpecializationType(
130 SourceLocation TemplateNameLoc, TemplateArgumentListInfo &TemplateArgs) {
131 if (!OuterInstantiationArgs ||
132 !isa_and_present<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()))
134 Keyword, Template, TemplateNameLoc, TemplateArgs);
135
136 auto *TATD = cast<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
137 auto *Pattern = TATD;
138 while (Pattern->getInstantiatedFromMemberTemplate())
139 Pattern = Pattern->getInstantiatedFromMemberTemplate();
140 if (!mightReferToOuterTemplateParameters(Pattern->getTemplatedDecl()))
142 Keyword, Template, TemplateNameLoc, TemplateArgs);
143
144 Decl *NewD =
145 TypedefNameInstantiator->InstantiateTypeAliasTemplateDecl(TATD);
146 if (!NewD)
147 return QualType();
148
149 auto *NewTATD = cast<TypeAliasTemplateDecl>(NewD);
150 MaterializedTypedefs.push_back(NewTATD->getTemplatedDecl());
151
153 Keyword, TemplateName(NewTATD), TemplateNameLoc, TemplateArgs);
154 }
155
156 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
157 ASTContext &Context = SemaRef.getASTContext();
158 TypedefNameDecl *OrigDecl = TL.getDecl();
159 TypedefNameDecl *Decl = OrigDecl;
160 const TypedefType *T = TL.getTypePtr();
161 // Transform the underlying type of the typedef and clone the Decl only if
162 // the typedef has a dependent context.
163 bool InDependentContext = OrigDecl->getDeclContext()->isDependentContext();
164
165 // A typedef/alias Decl within the NestedPattern may reference the outer
166 // template parameters. They're substituted with corresponding instantiation
167 // arguments here and in RebuildTemplateSpecializationType() above.
168 // Otherwise, we would have a CTAD guide with "dangling" template
169 // parameters.
170 // For example,
171 // template <class T> struct Outer {
172 // using Alias = S<T>;
173 // template <class U> struct Inner {
174 // Inner(Alias);
175 // };
176 // };
177 if (OuterInstantiationArgs && InDependentContext &&
179 Decl = cast_if_present<TypedefNameDecl>(
180 TypedefNameInstantiator->InstantiateTypedefNameDecl(
181 OrigDecl, /*IsTypeAlias=*/isa<TypeAliasDecl>(OrigDecl)));
182 if (!Decl)
183 return QualType();
184 MaterializedTypedefs.push_back(Decl);
185 } else if (InDependentContext) {
186 TypeLocBuilder InnerTLB;
187 QualType Transformed =
188 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
189 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
190 if (isa<TypeAliasDecl>(OrigDecl))
192 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
193 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
194 else {
195 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
197 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
198 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
199 }
200 MaterializedTypedefs.push_back(Decl);
201 }
202
203 NestedNameSpecifierLoc QualifierLoc = TL.getQualifierLoc();
204 if (QualifierLoc) {
205 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
206 if (!QualifierLoc)
207 return QualType();
208 }
209
210 QualType TDTy = Context.getTypedefType(
211 T->getKeyword(), QualifierLoc.getNestedNameSpecifier(), Decl);
212 TLB.push<TypedefTypeLoc>(TDTy).set(TL.getElaboratedKeywordLoc(),
213 QualifierLoc, TL.getNameLoc());
214 return TDTy;
215 }
216};
217
218// Build a deduction guide using the provided information.
219//
220// A deduction guide can be either a template or a non-template function
221// declaration. If \p TemplateParams is null, a non-template function
222// declaration will be created.
224buildDeductionGuide(Sema &SemaRef, TemplateDecl *OriginalTemplate,
225 TemplateParameterList *TemplateParams,
227 TypeSourceInfo *TInfo, SourceLocation LocStart,
228 SourceLocation Loc, SourceLocation LocEnd, bool IsImplicit,
229 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {},
230 const AssociatedConstraint &FunctionTrailingRC = {}) {
231 DeclContext *DC = OriginalTemplate->getDeclContext();
232 auto DeductionGuideName =
234 OriginalTemplate);
235
236 DeclarationNameInfo Name(DeductionGuideName, Loc);
238 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
239
240 // Build the implicit deduction guide template.
241 QualType GuideType = TInfo->getType();
242
243 // In CUDA/HIP mode, avoid duplicate implicit guides that differ only in CUDA
244 // target attributes (same constructor signature and constraints).
245 if (IsImplicit && Ctor && SemaRef.getLangOpts().CUDA) {
247 Ctor->getAssociatedConstraints(NewACs);
248
249 for (NamedDecl *Existing : DC->lookup(DeductionGuideName)) {
250 auto *ExistingFT = dyn_cast<FunctionTemplateDecl>(Existing);
251 auto *ExistingGuide =
252 ExistingFT
253 ? dyn_cast<CXXDeductionGuideDecl>(ExistingFT->getTemplatedDecl())
254 : dyn_cast<CXXDeductionGuideDecl>(Existing);
255 if (!ExistingGuide)
256 continue;
257
258 // Only consider guides that were also synthesized from a constructor.
259 auto *ExistingCtor = ExistingGuide->getCorrespondingConstructor();
260 if (!ExistingCtor)
261 continue;
262
263 // If the underlying constructors are overloads (different signatures once
264 // CUDA attributes are ignored), they should each get their own guides.
265 if (SemaRef.IsOverload(Ctor, ExistingCtor,
266 /*UseMemberUsingDeclRules=*/false,
267 /*ConsiderCudaAttrs=*/false))
268 continue;
269
270 // At this point, the constructors have the same signature ignoring CUDA
271 // attributes. Decide whether their associated constraints are also the
272 // same; only in that case do we treat one guide as a duplicate of the
273 // other.
275 ExistingCtor->getAssociatedConstraints(ExistingACs);
276
277 if (HaveSameAssociatedConstraints(SemaRef, ExistingCtor, ExistingACs,
278 Ctor, NewACs))
279 return ExistingGuide;
280 }
281 }
282
283 auto *Guide = CXXDeductionGuideDecl::Create(
284 SemaRef.Context, DC, LocStart, ES, Name, GuideType, TInfo, LocEnd, Ctor,
285 DeductionCandidate::Normal, FunctionTrailingRC);
286 Guide->setImplicit(IsImplicit);
287 Guide->setParams(Params);
288
289 for (auto *Param : Params)
290 Param->setDeclContext(Guide);
291 for (auto *TD : MaterializedTypedefs)
292 TD->setDeclContext(Guide);
293 if (isa<CXXRecordDecl>(DC))
294 Guide->setAccess(AS_public);
295
296 if (!TemplateParams) {
297 DC->addDecl(Guide);
298 return Guide;
299 }
300
301 auto *GuideTemplate = FunctionTemplateDecl::Create(
302 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
303 GuideTemplate->setImplicit(IsImplicit);
304 Guide->setDescribedFunctionTemplate(GuideTemplate);
305
306 if (isa<CXXRecordDecl>(DC))
307 GuideTemplate->setAccess(AS_public);
308
309 DC->addDecl(GuideTemplate);
310 return Guide;
311}
312
313// Transform a given template type parameter `TTP`.
315transformTemplateParam(Sema &SemaRef, DeclContext *DC,
317 MultiLevelTemplateArgumentList &Args, unsigned NewDepth,
318 unsigned NewIndex, bool EvaluateConstraint) {
319 // TemplateTypeParmDecl's index cannot be changed after creation, so
320 // substitute it directly.
321 auto *NewTTP = TemplateTypeParmDecl::Create(
322 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), NewDepth,
323 NewIndex, TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
324 TTP->isParameterPack(), TTP->hasTypeConstraint(),
326 if (const auto *TC = TTP->getTypeConstraint())
327 SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
328 /*EvaluateConstraint=*/EvaluateConstraint);
329 if (TTP->hasDefaultArgument()) {
330 TemplateArgumentLoc InstantiatedDefaultArg;
331 if (!SemaRef.SubstTemplateArgument(
332 TTP->getDefaultArgument(), Args, InstantiatedDefaultArg,
333 TTP->getDefaultArgumentLoc(), TTP->getDeclName()))
334 NewTTP->setDefaultArgument(SemaRef.Context, InstantiatedDefaultArg);
335 }
336 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TTP, NewTTP);
337 return NewTTP;
338}
339
341transformTemplateParam(Sema &SemaRef, DeclContext *DC,
342 NonTypeTemplateParmDecl *TTP, unsigned NewDepth,
343 unsigned NewIndex,
346 if (TTP->isExpandedParameterPack()) {
347 SmallVector<TypeSourceInfo *, 4> ExpandedTypeSourceInfos(
348 TTP->getNumExpansionTypes());
350 for (unsigned I = 0, N = TTP->getNumExpansionTypes(); I != N; ++I) {
351 TypeSourceInfo *NewTSI =
352 SemaRef.SubstType(TTP->getExpansionTypeSourceInfo(I), Args,
353 TTP->getLocation(), TTP->getDeclName());
354 assert(NewTSI);
355
356 QualType NewT =
357 SemaRef.CheckNonTypeTemplateParameterType(NewTSI, TTP->getLocation());
358 assert(!NewT.isNull());
359
360 ExpandedTypeSourceInfos[I] = NewTSI;
361 ExpandedTypes[I] = NewT;
362 }
364 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), NewDepth,
365 NewIndex, TTP->getIdentifier(), TTP->getType(),
366 TTP->getTypeSourceInfo(), ExpandedTypes, ExpandedTypeSourceInfos);
367 } else {
368 TypeSourceInfo *NewTSI = SemaRef.SubstType(
369 TTP->getTypeSourceInfo(), Args, TTP->getLocation(), TTP->getDeclName());
370 assert(NewTSI);
371
372 QualType NewT =
373 SemaRef.CheckNonTypeTemplateParameterType(NewTSI, TTP->getLocation());
374 assert(!NewT.isNull());
375
377 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), NewDepth,
378 NewIndex, TTP->getIdentifier(), NewT, TTP->isParameterPack(), NewTSI);
379 }
380
381 if (TypeSourceInfo *TSI = TTP->getTypeSourceInfo();
383 if (AutoLoc.isConstrained()) {
384 SourceLocation EllipsisLoc;
385 if (TTP->isExpandedParameterPack())
386 EllipsisLoc =
387 TSI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc();
388 else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>(
390 EllipsisLoc = Constraint->getEllipsisLoc();
391 // Note: We attach the non-instantiated constraint here, so that it can be
392 // instantiated relative to the top level, like all our other
393 // constraints.
394 if (SemaRef.AttachTypeConstraint(AutoLoc, /*NewConstrainedParm=*/NewTTP,
395 /*OrigConstrainedParm=*/TTP,
396 EllipsisLoc))
397 llvm_unreachable("unexpected failure attaching type constraint");
398 }
399 }
400
401 NewTTP->setAccess(AS_public);
402 NewTTP->setImplicit(TTP->isImplicit());
403
404 if (TTP->hasDefaultArgument()) {
405 TemplateArgumentLoc InstantiatedDefaultArg;
406 if (!SemaRef.SubstTemplateArgument(
407 TTP->getDefaultArgument(), Args, InstantiatedDefaultArg,
408 TTP->getDefaultArgumentLoc(), TTP->getDeclName()))
409 NewTTP->setDefaultArgument(SemaRef.Context, InstantiatedDefaultArg);
410 }
411
412 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TTP, NewTTP);
413 return NewTTP;
414}
415
417transformTemplateParameters(Sema &SemaRef, DeclContext *DC,
420 unsigned NewDepth, bool EvaluateConstraint);
421
423transformTemplateParam(Sema &SemaRef, DeclContext *DC,
424 TemplateTemplateParmDecl *TTP, unsigned NewDepth,
425 unsigned NewIndex, MultiLevelTemplateArgumentList &Args,
426 bool EvaluateConstraint) {
428 if (TTP->isExpandedParameterPack()) {
431 for (unsigned I = 0, N = TTP->getNumExpansionTemplateParameters(); I != N;
432 ++I)
433 ExpandedTPLs[I] = transformTemplateParameters(
434 SemaRef, DC, TTP->getExpansionTemplateParameters(I), Args,
435 NewDepth + 1, EvaluateConstraint);
437 SemaRef.Context, DC, TTP->getLocation(), NewDepth, NewIndex,
440 ExpandedTPLs);
441 } else {
442 TemplateParameterList *NewTPL =
443 transformTemplateParameters(SemaRef, DC, TTP->getTemplateParameters(),
444 Args, NewDepth + 1, EvaluateConstraint);
446 SemaRef.Context, DC, TTP->getLocation(), NewDepth, NewIndex,
447 TTP->isParameterPack(), TTP->getIdentifier(),
448 TTP->templateParameterKind(), TTP->wasDeclaredWithTypename(), NewTPL);
449 }
450
451 NewTTP->setAccess(AS_public);
452 NewTTP->setImplicit(TTP->isImplicit());
453
454 if (TTP->hasDefaultArgument()) {
455 TemplateArgumentLoc InstantiatedDefaultArg;
456 if (!SemaRef.SubstTemplateArgument(
457 TTP->getDefaultArgument(), Args, InstantiatedDefaultArg,
458 TTP->getDefaultArgumentLoc(), TTP->getDeclName()))
459 NewTTP->setDefaultArgument(SemaRef.Context, InstantiatedDefaultArg);
460 }
461
462 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TTP, NewTTP);
463 return NewTTP;
464}
465
466NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
469 unsigned NewIndex, unsigned NewDepth,
470 bool EvaluateConstraint = true) {
471 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
472 return transformTemplateParam(SemaRef, DC, TTP, Args, NewDepth, NewIndex,
473 EvaluateConstraint);
474 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(TemplateParam))
475 return transformTemplateParam(SemaRef, DC, NTTP, NewDepth, NewIndex, Args);
476 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
477 return transformTemplateParam(SemaRef, DC, TTP, NewDepth, NewIndex, Args,
478 EvaluateConstraint);
479 llvm_unreachable("Unhandled template parameter types");
480}
481
483transformTemplateParameters(Sema &SemaRef, DeclContext *DC,
486 unsigned NewDepth, bool EvaluateConstraint) {
487 SmallVector<NamedDecl *, 4> Params(TPL->size());
488 for (unsigned I = 0, E = TPL->size(); I < E; ++I) {
489 Params[I] = transformTemplateParameter(SemaRef, DC, TPL->getParam(I), Args,
490 /*NewIndex=*/I, NewDepth,
491 EvaluateConstraint);
492 }
494 SemaRef.Context, TPL->getTemplateLoc(), TPL->getLAngleLoc(), Params,
495 TPL->getRAngleLoc(), TPL->getRequiresClause());
496}
497
498/// Transform to convert portions of a constructor declaration into the
499/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
500struct ConvertConstructorToDeductionGuideTransform {
501 ConvertConstructorToDeductionGuideTransform(Sema &S,
502 ClassTemplateDecl *Template)
503 : SemaRef(S), Template(Template) {
504 // If the template is nested, then we need to use the original
505 // pattern to iterate over the constructors.
506 ClassTemplateDecl *Pattern = Template;
507 while (Pattern->getInstantiatedFromMemberTemplate()) {
508 if (Pattern->isMemberSpecialization())
509 break;
510 Pattern = Pattern->getInstantiatedFromMemberTemplate();
511 NestedPattern = Pattern;
512 }
513
514 if (NestedPattern)
515 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
516 }
517
518 Sema &SemaRef;
519 ClassTemplateDecl *Template;
520 ClassTemplateDecl *NestedPattern = nullptr;
521
522 DeclContext *DC = Template->getDeclContext();
523 CXXRecordDecl *Primary = Template->getTemplatedDecl();
524 DeclarationName DeductionGuideName =
525 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
526
527 QualType DeducedType = SemaRef.Context.getCanonicalTagType(Primary);
528
529 // Index adjustment to apply to convert depth-1 template parameters into
530 // depth-0 template parameters.
531 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
532
533 // Instantiation arguments for the outermost depth-1 templates
534 // when the template is nested
535 MultiLevelTemplateArgumentList OuterInstantiationArgs;
536
537 /// Transform a constructor declaration into a deduction guide.
538 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
539 CXXConstructorDecl *CD) {
540 SmallVector<TemplateArgument, 16> SubstArgs;
541
542 LocalInstantiationScope Scope(SemaRef);
543
544 // C++ [over.match.class.deduct]p1:
545 // -- For each constructor of the class template designated by the
546 // template-name, a function template with the following properties:
547
548 // -- The template parameters are the template parameters of the class
549 // template followed by the template parameters (including default
550 // template arguments) of the constructor, if any.
551 TemplateParameterList *TemplateParams =
552 SemaRef.GetTemplateParameterList(Template);
553 SmallVector<TemplateArgument, 16> Depth1Args;
554 AssociatedConstraint OuterRC(TemplateParams->getRequiresClause());
555 if (FTD) {
556 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
557 SmallVector<NamedDecl *, 16> AllParams;
558 AllParams.reserve(TemplateParams->size() + InnerParams->size());
559 AllParams.insert(AllParams.begin(), TemplateParams->begin(),
560 TemplateParams->end());
561 SubstArgs.reserve(InnerParams->size());
562 Depth1Args.reserve(InnerParams->size());
563
564 // Later template parameters could refer to earlier ones, so build up
565 // a list of substituted template arguments as we go.
566 for (NamedDecl *Param : *InnerParams) {
567 MultiLevelTemplateArgumentList Args;
568 Args.setKind(TemplateSubstitutionKind::Rewrite);
569 Args.addOuterTemplateArguments(Depth1Args);
571 if (NestedPattern)
572 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
573 auto [Depth, Index] = getDepthAndIndex(Param);
574 // Depth can be 0 if FTD belongs to a non-template class/a class
575 // template specialization with an empty template parameter list. In
576 // that case, we don't want the NewDepth to overflow, and it should
577 // remain 0.
578 NamedDecl *NewParam = transformTemplateParameter(
579 SemaRef, DC, Param, Args, Index + Depth1IndexAdjustment,
580 Depth ? Depth - 1 : 0);
581 if (!NewParam)
582 return nullptr;
583 // Constraints require that we substitute depth-1 arguments
584 // to match depths when substituted for evaluation later
585 Depth1Args.push_back(SemaRef.Context.getInjectedTemplateArg(NewParam));
586
587 if (NestedPattern) {
588 auto [Depth, Index] = getDepthAndIndex(NewParam);
589 NewParam = transformTemplateParameter(
590 SemaRef, DC, NewParam, OuterInstantiationArgs, Index,
591 Depth - OuterInstantiationArgs.getNumSubstitutedLevels(),
592 /*EvaluateConstraint=*/false);
593 }
594
595 assert(getDepthAndIndex(NewParam).first == 0 &&
596 "Unexpected template parameter depth");
597
598 AllParams.push_back(NewParam);
599 SubstArgs.push_back(SemaRef.Context.getInjectedTemplateArg(NewParam));
600 }
601
602 // Substitute new template parameters into requires-clause if present.
603 Expr *RequiresClause = nullptr;
604 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
605 MultiLevelTemplateArgumentList Args;
606 Args.setKind(TemplateSubstitutionKind::Rewrite);
607 Args.addOuterTemplateArguments(Depth1Args);
609 if (NestedPattern)
610 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
611 ExprResult E =
612 SemaRef.SubstConstraintExprWithoutSatisfaction(InnerRC, Args);
613 if (!E.isUsable())
614 return nullptr;
615 RequiresClause = E.get();
616 }
617
618 TemplateParams = TemplateParameterList::Create(
619 SemaRef.Context, InnerParams->getTemplateLoc(),
620 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
621 RequiresClause);
622 }
623
624 // If we built a new template-parameter-list, track that we need to
625 // substitute references to the old parameters into references to the
626 // new ones.
627 MultiLevelTemplateArgumentList Args;
628 Args.setKind(TemplateSubstitutionKind::Rewrite);
629 if (FTD) {
630 Args.addOuterTemplateArguments(SubstArgs);
632 }
633
634 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()
635 ->getTypeLoc()
636 .getAsAdjusted<FunctionProtoTypeLoc>();
637 assert(FPTL && "no prototype for constructor declaration");
638
639 // Transform the type of the function, adjusting the return type and
640 // replacing references to the old parameters with references to the
641 // new ones.
642 TypeLocBuilder TLB;
643 SmallVector<ParmVarDecl *, 8> Params;
644 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
645 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
646 MaterializedTypedefs);
647 if (NewType.isNull())
648 return nullptr;
649 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
650
651 // At this point, the function parameters are already 'instantiated' in the
652 // current scope. Substitute into the constructor's trailing
653 // requires-clause, if any.
654 AssociatedConstraint FunctionTrailingRC;
655 if (const AssociatedConstraint &RC = CD->getTrailingRequiresClause()) {
656 MultiLevelTemplateArgumentList Args;
657 Args.setKind(TemplateSubstitutionKind::Rewrite);
658 Args.addOuterTemplateArguments(Depth1Args);
660 if (NestedPattern)
661 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
662 ExprResult E = SemaRef.SubstConstraintExprWithoutSatisfaction(
663 const_cast<Expr *>(RC.ConstraintExpr), Args);
664 if (!E.isUsable())
665 return nullptr;
666 FunctionTrailingRC = AssociatedConstraint(E.get(), RC.ArgPackSubstIndex);
667 }
668
669 // C++ [over.match.class.deduct]p1:
670 // If C is defined, for each constructor of C, a function template with
671 // the following properties:
672 // [...]
673 // - The associated constraints are the conjunction of the associated
674 // constraints of C and the associated constraints of the constructor, if
675 // any.
676 if (OuterRC) {
677 // The outer template parameters are not transformed, so their
678 // associated constraints don't need substitution.
679 // FIXME: Should simply add another field for the OuterRC, instead of
680 // combining them like this.
681 if (!FunctionTrailingRC)
682 FunctionTrailingRC = OuterRC;
683 else
684 FunctionTrailingRC = AssociatedConstraint(
686 SemaRef.Context,
687 /*lhs=*/const_cast<Expr *>(OuterRC.ConstraintExpr),
688 /*rhs=*/const_cast<Expr *>(FunctionTrailingRC.ConstraintExpr),
689 BO_LAnd, SemaRef.Context.BoolTy, VK_PRValue, OK_Ordinary,
690 TemplateParams->getTemplateLoc(), FPOptionsOverride()),
691 FunctionTrailingRC.ArgPackSubstIndex);
692 }
693
694 return buildDeductionGuide(
695 SemaRef, Template, TemplateParams, CD, CD->getExplicitSpecifier(),
696 NewTInfo, CD->getBeginLoc(), CD->getLocation(), CD->getEndLoc(),
697 /*IsImplicit=*/true, MaterializedTypedefs, FunctionTrailingRC);
698 }
699
700 /// Build a deduction guide with the specified parameter types.
701 CXXDeductionGuideDecl *
702 buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
703 SourceLocation Loc = Template->getLocation();
704
705 // Build the requested type.
706 FunctionProtoType::ExtProtoInfo EPI;
707 EPI.HasTrailingReturn = true;
708 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
709 DeductionGuideName, EPI);
710 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
711 if (NestedPattern)
712 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
713 DeductionGuideName);
714
715 if (!TSI)
716 return nullptr;
717
718 FunctionProtoTypeLoc FPTL =
719 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
720
721 // Build the parameters, needed during deduction / substitution.
722 SmallVector<ParmVarDecl *, 4> Params;
723 for (auto T : ParamTypes) {
724 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
725 if (NestedPattern)
726 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
727 DeclarationName());
728 if (!TSI)
729 return nullptr;
730
731 ParmVarDecl *NewParam =
732 ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
733 TSI->getType(), TSI, SC_None, nullptr);
734 NewParam->setScopeInfo(0, Params.size());
735 FPTL.setParam(Params.size(), NewParam);
736 Params.push_back(NewParam);
737 }
738
739 return buildDeductionGuide(
740 SemaRef, Template, SemaRef.GetTemplateParameterList(Template), nullptr,
741 ExplicitSpecifier(), TSI, Loc, Loc, Loc, /*IsImplicit=*/true);
742 }
743
744private:
745 QualType transformFunctionProtoType(
746 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
747 SmallVectorImpl<ParmVarDecl *> &Params,
748 MultiLevelTemplateArgumentList &Args,
749 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
750 SmallVector<QualType, 4> ParamTypes;
751 const FunctionProtoType *T = TL.getTypePtr();
752
753 // -- The types of the function parameters are those of the constructor.
754 for (auto *OldParam : TL.getParams()) {
755 ParmVarDecl *NewParam = OldParam;
756 // Given
757 // template <class T> struct C {
758 // template <class U> struct D {
759 // template <class V> D(U, V);
760 // };
761 // };
762 // First, transform all the references to template parameters that are
763 // defined outside of the surrounding class template. That is T in the
764 // above example.
765 if (NestedPattern) {
766 NewParam = transformFunctionTypeParam(
767 NewParam, OuterInstantiationArgs, MaterializedTypedefs,
768 /*TransformingOuterPatterns=*/true);
769 if (!NewParam)
770 return QualType();
771 }
772 // Then, transform all the references to template parameters that are
773 // defined at the class template and the constructor. In this example,
774 // they're U and V, respectively.
775 NewParam =
776 transformFunctionTypeParam(NewParam, Args, MaterializedTypedefs,
777 /*TransformingOuterPatterns=*/false);
778 if (!NewParam)
779 return QualType();
780 ParamTypes.push_back(NewParam->getType());
781 Params.push_back(NewParam);
782 }
783
784 // -- The return type is the class template specialization designated by
785 // the template-name and template arguments corresponding to the
786 // template parameters obtained from the class template.
787 //
788 // We use the injected-class-name type of the primary template instead.
789 // This has the convenient property that it is different from any type that
790 // the user can write in a deduction-guide (because they cannot enter the
791 // context of the template), so implicit deduction guides can never collide
792 // with explicit ones.
793 QualType ReturnType = DeducedType;
794 auto TTL = TLB.push<TagTypeLoc>(ReturnType);
795 TTL.setElaboratedKeywordLoc(SourceLocation());
796 TTL.setQualifierLoc(NestedNameSpecifierLoc());
797 TTL.setNameLoc(Primary->getLocation());
798
799 // Resolving a wording defect, we also inherit the variadicness of the
800 // constructor.
801 FunctionProtoType::ExtProtoInfo EPI;
802 EPI.Variadic = T->isVariadic();
803 EPI.HasTrailingReturn = true;
804
805 QualType Result = SemaRef.BuildFunctionType(
806 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
807 if (Result.isNull())
808 return QualType();
809
810 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
812 NewTL.setLParenLoc(TL.getLParenLoc());
813 NewTL.setRParenLoc(TL.getRParenLoc());
814 NewTL.setExceptionSpecRange(SourceRange());
816 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
817 NewTL.setParam(I, Params[I]);
818
819 return Result;
820 }
821
822 ParmVarDecl *transformFunctionTypeParam(
823 ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
824 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs,
825 bool TransformingOuterPatterns) {
826 TypeSourceInfo *OldTSI = OldParam->getTypeSourceInfo();
827 TypeSourceInfo *NewTSI;
828 if (auto PackTL = OldTSI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
829 // Expand out the one and only element in each inner pack.
830 Sema::ArgPackSubstIndexRAII SubstIndex(SemaRef, 0u);
831 NewTSI =
832 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
833 OldParam->getLocation(), OldParam->getDeclName());
834 if (!NewTSI)
835 return nullptr;
836 NewTSI =
837 SemaRef.CheckPackExpansion(NewTSI, PackTL.getEllipsisLoc(),
838 PackTL.getTypePtr()->getNumExpansions());
839 } else
840 NewTSI = SemaRef.SubstType(OldTSI, Args, OldParam->getLocation(),
841 OldParam->getDeclName());
842 if (!NewTSI)
843 return nullptr;
844
845 // Extract the type. This (for instance) replaces references to typedef
846 // members of the current instantiations with the definitions of those
847 // typedefs, avoiding triggering instantiation of the deduced type during
848 // deduction.
849 NewTSI = ExtractTypeForDeductionGuide(
850 SemaRef, MaterializedTypedefs, NestedPattern,
851 TransformingOuterPatterns ? &Args : nullptr)
852 .transform(NewTSI);
853 if (!NewTSI)
854 return nullptr;
855 // Resolving a wording defect, we also inherit default arguments from the
856 // constructor.
857 ExprResult NewDefArg;
858 if (OldParam->hasDefaultArg()) {
859 // We don't care what the value is (we won't use it); just create a
860 // placeholder to indicate there is a default argument.
861 QualType ParamTy = NewTSI->getType();
862 NewDefArg = new (SemaRef.Context)
863 OpaqueValueExpr(OldParam->getDefaultArgRange().getBegin(),
864 ParamTy.getNonLValueExprType(SemaRef.Context),
866 : ParamTy->isRValueReferenceType() ? VK_XValue
867 : VK_PRValue);
868 }
869 // Handle arrays and functions decay.
870 auto NewType = NewTSI->getType();
871 if (NewType->isArrayType() || NewType->isFunctionType())
872 NewType = SemaRef.Context.getDecayedType(NewType);
873
874 ParmVarDecl *NewParam = ParmVarDecl::Create(
875 SemaRef.Context, DC, OldParam->getInnerLocStart(),
876 OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewTSI,
877 OldParam->getStorageClass(), NewDefArg.get());
878 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
879 OldParam->getFunctionScopeIndex());
880 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
881 return NewParam;
882 }
883};
884
885// Find all template parameters that appear in the given DeducedArgs.
886// Return the indices of the template parameters in the TemplateParams.
887SmallVector<unsigned> TemplateParamsReferencedInTemplateArgumentList(
888 Sema &SemaRef, const TemplateParameterList *TemplateParamsList,
889 ArrayRef<TemplateArgument> DeducedArgs) {
890
891 llvm::SmallBitVector ReferencedTemplateParams(TemplateParamsList->size());
892 SemaRef.MarkUsedTemplateParameters(DeducedArgs, /*OnlyDeduced=*/false,
893 TemplateParamsList->getDepth(),
894 ReferencedTemplateParams);
895
896 auto MarkDefaultArgs = [&](auto *Param) {
897 if (!Param->hasDefaultArgument())
898 return;
900 Param->getDefaultArgument().getArgument(), /*OnlyDeduced=*/false,
901 TemplateParamsList->getDepth(), ReferencedTemplateParams);
902 };
903
904 for (unsigned Index = 0; Index < TemplateParamsList->size(); ++Index) {
905 if (!ReferencedTemplateParams[Index])
906 continue;
907 auto *Param = TemplateParamsList->getParam(Index);
908 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Param))
909 MarkDefaultArgs(TTPD);
910 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Param))
911 MarkDefaultArgs(NTTPD);
912 else
913 MarkDefaultArgs(cast<TemplateTemplateParmDecl>(Param));
914 }
915
916 SmallVector<unsigned> Results;
917 for (unsigned Index = 0; Index < TemplateParamsList->size(); ++Index) {
918 if (ReferencedTemplateParams[Index])
919 Results.push_back(Index);
920 }
921 return Results;
922}
923
924bool hasDeclaredDeductionGuides(DeclarationName Name, DeclContext *DC) {
925 // Check whether we've already declared deduction guides for this template.
926 // FIXME: Consider storing a flag on the template to indicate this.
927 assert(Name.getNameKind() ==
929 "name must be a deduction guide name");
930 auto Existing = DC->lookup(Name);
931 for (auto *D : Existing)
932 if (D->isImplicit())
933 return true;
934 return false;
935}
936
937// Returns all source deduction guides associated with the declared
938// deduction guides that have the specified deduction guide name.
939llvm::DenseSet<const NamedDecl *> getSourceDeductionGuides(DeclarationName Name,
940 DeclContext *DC) {
941 assert(Name.getNameKind() ==
943 "name must be a deduction guide name");
944 llvm::DenseSet<const NamedDecl *> Result;
945 for (auto *D : DC->lookup(Name)) {
946 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
947 D = FTD->getTemplatedDecl();
948
949 if (const auto *GD = dyn_cast<CXXDeductionGuideDecl>(D)) {
950 assert(GD->getSourceDeductionGuide() &&
951 "deduction guide for alias template must have a source deduction "
952 "guide");
953 Result.insert(GD->getSourceDeductionGuide());
954 }
955 }
956 return Result;
957}
958
959bool IsNonDeducedArgument(const TemplateArgument &TA) {
960 // The following cases indicate the template argument is non-deducible:
961 // 1. The result is null. E.g. When it comes from a default template
962 // argument that doesn't appear in the alias declaration.
963 // 2. The template parameter is a pack and that cannot be deduced from
964 // the arguments within the alias declaration.
965 // Non-deducible template parameters will persist in the transformed
966 // deduction guide.
967 return TA.isNull() ||
969 llvm::any_of(TA.pack_elements(), IsNonDeducedArgument));
970}
971
972// Build the associated constraints for the alias deduction guides.
973// C++ [over.match.class.deduct]p3.3:
974// The associated constraints ([temp.constr.decl]) are the conjunction of the
975// associated constraints of g and a constraint that is satisfied if and only
976// if the arguments of A are deducible (see below) from the return type.
977//
978// The return result is expected to be the require-clause for the synthesized
979// alias deduction guide.
980Expr *
981buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F,
984 ArrayRef<unsigned> DeducedAliasTemplateParams,
985 Expr *IsDeducible) {
987 if (!RC)
988 return IsDeducible;
989
990 ASTContext &Context = SemaRef.Context;
992
993 // In the clang AST, constraint nodes are deliberately not instantiated unless
994 // they are actively being evaluated. Consequently, occurrences of template
995 // parameters in the require-clause expression have a subtle "depth"
996 // difference compared to normal occurrences in places, such as function
997 // parameters. When transforming the require-clause, we must take this
998 // distinction into account:
999 //
1000 // 1) In the transformed require-clause, occurrences of template parameters
1001 // must use the "uninstantiated" depth;
1002 // 2) When substituting on the require-clause expr of the underlying
1003 // deduction guide, we must use the entire set of template argument lists;
1004 //
1005 // It's important to note that we're performing this transformation on an
1006 // *instantiated* AliasTemplate.
1007
1008 // For 1), if the alias template is nested within a class template, we
1009 // calcualte the 'uninstantiated' depth by adding the substitution level back.
1010 unsigned AdjustDepth = 0;
1011 if (auto *PrimaryTemplate =
1012 AliasTemplate->getInstantiatedFromMemberTemplate())
1013 AdjustDepth = PrimaryTemplate->getTemplateDepth();
1014
1015 // We rebuild all template parameters with the uninstantiated depth, and
1016 // build template arguments refer to them.
1017 SmallVector<TemplateArgument> AdjustedAliasTemplateArgs(
1018 AliasTemplate->getTemplateParameters()->size());
1019
1020 unsigned N = 0;
1021 for (unsigned Index : DeducedAliasTemplateParams) {
1022 auto *TP = AliasTemplate->getTemplateParameters()->getParam(Index);
1023 // Rebuild any internal references to earlier parameters and reindex
1024 // as we go.
1027 Args.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
1028 NamedDecl *NewParam = transformTemplateParameter(
1029 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
1030 /*NewIndex=*/N++, getDepthAndIndex(TP).first + AdjustDepth);
1031
1032 TemplateArgument NewTemplateArgument =
1033 Context.getInjectedTemplateArg(NewParam);
1034 AdjustedAliasTemplateArgs[Index] = NewTemplateArgument;
1035 }
1036
1037 // Template arguments used to transform the template arguments in
1038 // DeducedResults.
1039 SmallVector<TemplateArgument> TemplateArgsForBuildingRC(
1040 F->getTemplateParameters()->size());
1041 // Transform the transformed template args
1042 MultiLevelTemplateArgumentList ArgsForDeducedParams;
1043 ArgsForDeducedParams.setKind(TemplateSubstitutionKind::Rewrite);
1044 ArgsForDeducedParams.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
1045
1046 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
1047 const auto &D = DeduceResults[Index];
1048 if (IsNonDeducedArgument(D)) { // non-deduced template parameters of f
1049 NamedDecl *TP = F->getTemplateParameters()->getParam(Index);
1052 Args.addOuterTemplateArguments(TemplateArgsForBuildingRC);
1053 // Rebuild the template parameter with updated depth and index.
1054 NamedDecl *NewParam = transformTemplateParameter(
1055 SemaRef, F->getDeclContext(), TP, Args,
1056 /*NewIndex=*/N++, getDepthAndIndex(TP).first + AdjustDepth);
1057 assert(TemplateArgsForBuildingRC[Index].isNull());
1058 TemplateArgsForBuildingRC[Index] =
1059 Context.getInjectedTemplateArg(NewParam);
1060 continue;
1061 }
1062 TemplateArgumentLoc Input =
1064 TemplateArgumentLoc Output;
1065 if (!SemaRef.SubstTemplateArgument(Input, ArgsForDeducedParams, Output)) {
1066 assert(TemplateArgsForBuildingRC[Index].isNull() &&
1067 "InstantiatedArgs must be null before setting");
1068 TemplateArgsForBuildingRC[Index] = Output.getArgument();
1069 }
1070 }
1071
1072 // A list of template arguments for transforming the require-clause of F.
1073 // It must contain the entire set of template argument lists.
1074 MultiLevelTemplateArgumentList ArgsForBuildingRC;
1076 ArgsForBuildingRC.addOuterTemplateArguments(TemplateArgsForBuildingRC);
1077 // For 2), if the underlying deduction guide F is nested in a class template,
1078 // we need the entire template argument list, as the constraint AST in the
1079 // require-clause of F remains completely uninstantiated.
1080 //
1081 // For example:
1082 // template <typename T> // depth 0
1083 // struct Outer {
1084 // template <typename U>
1085 // struct Foo { Foo(U); };
1086 //
1087 // template <typename U> // depth 1
1088 // requires C<U>
1089 // Foo(U) -> Foo<int>;
1090 // };
1091 // template <typename U>
1092 // using AFoo = Outer<int>::Foo<U>;
1093 //
1094 // In this scenario, the deduction guide for `Foo` inside `Outer<int>`:
1095 // - The occurrence of U in the require-expression is [depth:1, index:0]
1096 // - The occurrence of U in the function parameter is [depth:0, index:0]
1097 // - The template parameter of U is [depth:0, index:0]
1098 //
1099 // We add the outer template arguments which is [int] to the multi-level arg
1100 // list to ensure that the occurrence U in `C<U>` will be replaced with int
1101 // during the substitution.
1102 //
1103 // NOTE: The underlying deduction guide F is instantiated -- either from an
1104 // explicitly-written deduction guide member, or from a constructor.
1105 // getInstantiatedFromMemberTemplate() can only handle the former case, so we
1106 // check the DeclContext kind.
1107 if (F->getLexicalDeclContext()->getDeclKind() ==
1108 clang::Decl::ClassTemplateSpecialization) {
1109 auto OuterLevelArgs = SemaRef.getTemplateInstantiationArgs(
1110 F, F->getLexicalDeclContext(),
1111 /*Final=*/false, /*Innermost=*/std::nullopt,
1112 /*RelativeToPrimary=*/true,
1113 /*Pattern=*/nullptr,
1114 /*ForConstraintInstantiation=*/true);
1115 for (auto It : OuterLevelArgs)
1116 ArgsForBuildingRC.addOuterTemplateArguments(It.Args);
1117 }
1118
1119 ExprResult E = SemaRef.SubstExpr(RC, ArgsForBuildingRC);
1120 if (E.isInvalid())
1121 return nullptr;
1122
1123 auto Conjunction =
1124 SemaRef.BuildBinOp(SemaRef.getCurScope(), SourceLocation{},
1125 BinaryOperatorKind::BO_LAnd, E.get(), IsDeducible);
1126 if (Conjunction.isInvalid())
1127 return nullptr;
1128 return Conjunction.getAs<Expr>();
1129}
1130// Build the is_deducible constraint for the alias deduction guides.
1131// [over.match.class.deduct]p3.3:
1132// ... and a constraint that is satisfied if and only if the arguments
1133// of A are deducible (see below) from the return type.
1134Expr *buildIsDeducibleConstraint(Sema &SemaRef,
1136 QualType ReturnType,
1137 ArrayRef<NamedDecl *> TemplateParams) {
1138 ASTContext &Context = SemaRef.Context;
1139 // Constraint AST nodes must use uninstantiated depth.
1140 if (auto *PrimaryTemplate =
1141 AliasTemplate->getInstantiatedFromMemberTemplate();
1142 PrimaryTemplate && TemplateParams.size() > 0) {
1144
1145 // Adjust the depth for TemplateParams.
1146 unsigned AdjustDepth = PrimaryTemplate->getTemplateDepth();
1147 SmallVector<TemplateArgument> TransformedTemplateArgs;
1148 for (auto *TP : TemplateParams) {
1149 // Rebuild any internal references to earlier parameters and reindex
1150 // as we go.
1153 Args.addOuterTemplateArguments(TransformedTemplateArgs);
1154 NamedDecl *NewParam = transformTemplateParameter(
1155 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
1156 /*NewIndex=*/TransformedTemplateArgs.size(),
1157 getDepthAndIndex(TP).first + AdjustDepth);
1158
1159 TemplateArgument NewTemplateArgument =
1160 Context.getInjectedTemplateArg(NewParam);
1161 TransformedTemplateArgs.push_back(NewTemplateArgument);
1162 }
1163 // Transformed the ReturnType to restore the uninstantiated depth.
1166 Args.addOuterTemplateArguments(TransformedTemplateArgs);
1167 ReturnType = SemaRef.SubstType(
1168 ReturnType, Args, AliasTemplate->getLocation(),
1169 Context.DeclarationNames.getCXXDeductionGuideName(AliasTemplate));
1170 }
1171
1172 SmallVector<TypeSourceInfo *> IsDeducibleTypeTraitArgs = {
1173 Context.getTrivialTypeSourceInfo(
1174 Context.getDeducedTemplateSpecializationType(
1176 /*DeducedAsType=*/QualType(), ElaboratedTypeKeyword::None,
1178 AliasTemplate->getLocation()), // template specialization type whose
1179 // arguments will be deduced.
1180 Context.getTrivialTypeSourceInfo(
1181 ReturnType, AliasTemplate->getLocation()), // type from which template
1182 // arguments are deduced.
1183 };
1184 return TypeTraitExpr::Create(
1185 Context, Context.getLogicalOperationType(), AliasTemplate->getLocation(),
1186 TypeTrait::BTT_IsDeducible, IsDeducibleTypeTraitArgs,
1187 AliasTemplate->getLocation(), /*Value*/ false);
1188}
1189
1190std::pair<TemplateDecl *, llvm::ArrayRef<TemplateArgument>>
1191getRHSTemplateDeclAndArgs(Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate) {
1192 auto RhsType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
1193 TemplateDecl *Template = nullptr;
1194 llvm::ArrayRef<TemplateArgument> AliasRhsTemplateArgs;
1195 if (const auto *TST = RhsType->getAs<TemplateSpecializationType>()) {
1196 // Cases where the RHS of the alias is dependent. e.g.
1197 // template<typename T>
1198 // using AliasFoo1 = Foo<T>; // a class/type alias template specialization
1199 Template = TST->getTemplateName().getAsTemplateDecl();
1200 AliasRhsTemplateArgs =
1201 TST->getAsNonAliasTemplateSpecializationType()->template_arguments();
1202 } else if (const auto *RT = RhsType->getAs<RecordType>()) {
1203 // Cases where template arguments in the RHS of the alias are not
1204 // dependent. e.g.
1205 // using AliasFoo = Foo<bool>;
1206 if (const auto *CTSD =
1207 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
1208 Template = CTSD->getSpecializedTemplate();
1209 AliasRhsTemplateArgs = CTSD->getTemplateArgs().asArray();
1210 }
1211 }
1212 return {Template, AliasRhsTemplateArgs};
1213}
1214
1215// Build deduction guides for a type alias template from the given underlying
1216// source deduction guide.
1217CXXDeductionGuideDecl *BuildDeductionGuideForTypeAlias(
1219 CXXDeductionGuideDecl *SourceDeductionGuide, SourceLocation Loc) {
1221 SourceDeductionGuide->getDescribedFunctionTemplate();
1222 assert(F && "deduction guide for alias template must be a function template");
1223
1225 Sema::NonSFINAEContext _1(SemaRef);
1226 Sema::InstantiatingTemplate BuildingDeductionGuides(
1227 SemaRef, AliasTemplate->getLocation(), F,
1229 if (BuildingDeductionGuides.isInvalid())
1230 return nullptr;
1231
1232 auto &Context = SemaRef.Context;
1233 auto [Template, AliasRhsTemplateArgs] =
1234 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
1235
1236 // We need both types desugared, before we continue to perform type deduction.
1237 // The intent is to get the template argument list 'matched', e.g. in the
1238 // following case:
1239 //
1240 //
1241 // template <class T>
1242 // struct A {};
1243 // template <class T>
1244 // using Foo = A<A<T>>;
1245 // template <class U = int>
1246 // using Bar = Foo<U>;
1247 //
1248 // In terms of Bar, we want U (which has the default argument) to appear in
1249 // the synthesized deduction guide, but U would remain undeduced if we deduced
1250 // A<A<T>> using Foo<U> directly.
1251 //
1252 // Instead, we need to canonicalize both against A, i.e. A<A<T>> and A<A<U>>,
1253 // such that T can be deduced as U.
1254 auto RType = SourceDeductionGuide->getReturnType();
1255 // The (trailing) return type of the deduction guide.
1256 const auto *FReturnType = RType->getAs<TemplateSpecializationType>();
1257 if (const auto *ICNT = RType->getAsCanonical<InjectedClassNameType>())
1258 // implicitly-generated deduction guide.
1260 ICNT->getDecl()->getCanonicalTemplateSpecializationType(
1261 SemaRef.Context));
1262
1263 ArrayRef<TemplateArgument> FReturnTemplateArgs;
1264 if (FReturnType) {
1265 FReturnTemplateArgs = FReturnType->template_arguments();
1266 } else if (const auto *RT = RType->getAs<RecordType>()) {
1267 // If the return type is a non-dependent class template specialization,
1268 // it might be resolved to a RecordType.
1269 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()))
1270 FReturnTemplateArgs = CTSD->getTemplateArgs().asArray();
1271 }
1272 assert(!FReturnTemplateArgs.empty() && "expected to see template arguments");
1273
1274 // Deduce template arguments of the deduction guide f from the RHS of
1275 // the alias.
1276 //
1277 // C++ [over.match.class.deduct]p3: ...For each function or function
1278 // template f in the guides of the template named by the
1279 // simple-template-id of the defining-type-id, the template arguments
1280 // of the return type of f are deduced from the defining-type-id of A
1281 // according to the process in [temp.deduct.type] with the exception
1282 // that deduction does not fail if not all template arguments are
1283 // deduced.
1284 //
1285 //
1286 // template<typename X, typename Y>
1287 // f(X, Y) -> f<Y, X>;
1288 //
1289 // template<typename U>
1290 // using alias = f<int, U>;
1291 //
1292 // The RHS of alias is f<int, U>, we deduced the template arguments of
1293 // the return type of the deduction guide from it: Y->int, X->U
1294 sema::TemplateDeductionInfo TDeduceInfo(Loc);
1295 // Must initialize n elements, this is required by DeduceTemplateArguments.
1297 F->getTemplateParameters()->size());
1298
1299 // FIXME: DeduceTemplateArguments stops immediately at the first
1300 // non-deducible template argument. However, this doesn't seem to cause
1301 // issues for practice cases, we probably need to extend it to continue
1302 // performing deduction for rest of arguments to align with the C++
1303 // standard.
1305 F->getTemplateParameters(), FReturnTemplateArgs,
1306 AliasRhsTemplateArgs, TDeduceInfo, DeduceResults,
1307 /*NumberOfArgumentsMustMatch=*/false);
1308
1310 SmallVector<unsigned> NonDeducedTemplateParamsInFIndex;
1311 // !!NOTE: DeduceResults respects the sequence of template parameters of
1312 // the deduction guide f.
1313 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
1314 const auto &D = DeduceResults[Index];
1315 if (!IsNonDeducedArgument(D))
1316 DeducedArgs.push_back(D);
1317 else
1318 NonDeducedTemplateParamsInFIndex.push_back(Index);
1319 }
1320 auto DeducedAliasTemplateParams =
1321 TemplateParamsReferencedInTemplateArgumentList(
1322 SemaRef, AliasTemplate->getTemplateParameters(), DeducedArgs);
1323 // All template arguments null by default.
1324 SmallVector<TemplateArgument> TemplateArgsForBuildingFPrime(
1325 F->getTemplateParameters()->size());
1326
1327 // Create a template parameter list for the synthesized deduction guide f'.
1328 //
1329 // C++ [over.match.class.deduct]p3.2:
1330 // If f is a function template, f' is a function template whose template
1331 // parameter list consists of all the template parameters of A
1332 // (including their default template arguments) that appear in the above
1333 // deductions or (recursively) in their default template arguments
1334 SmallVector<NamedDecl *> FPrimeTemplateParams;
1335 // Store template arguments that refer to the newly-created template
1336 // parameters, used for building `TemplateArgsForBuildingFPrime`.
1337 SmallVector<TemplateArgument, 16> TransformedDeducedAliasArgs(
1338 AliasTemplate->getTemplateParameters()->size());
1339 // We might be already within a pack expansion, but rewriting template
1340 // parameters is independent of that. (We may or may not expand new packs
1341 // when rewriting. So clear the state)
1342 Sema::ArgPackSubstIndexRAII PackSubstReset(SemaRef, std::nullopt);
1343
1344 for (unsigned AliasTemplateParamIdx : DeducedAliasTemplateParams) {
1345 auto *TP =
1346 AliasTemplate->getTemplateParameters()->getParam(AliasTemplateParamIdx);
1347 // Rebuild any internal references to earlier parameters and reindex as
1348 // we go.
1351 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
1352 NamedDecl *NewParam = transformTemplateParameter(
1353 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
1354 /*NewIndex=*/FPrimeTemplateParams.size(), getDepthAndIndex(TP).first);
1355 FPrimeTemplateParams.push_back(NewParam);
1356
1357 TemplateArgument NewTemplateArgument =
1358 Context.getInjectedTemplateArg(NewParam);
1359 TransformedDeducedAliasArgs[AliasTemplateParamIdx] = NewTemplateArgument;
1360 }
1361
1362 // To form a deduction guide f' from f, we leverage clang's instantiation
1363 // mechanism, we construct a template argument list where the template
1364 // arguments refer to the newly-created template parameters of f', and
1365 // then apply instantiation on this template argument list to instantiate
1366 // f, this ensures all template parameter occurrences are updated
1367 // correctly.
1368 //
1369 // The template argument list is formed, in order, from
1370 // 1) For the template parameters of the alias, the corresponding deduced
1371 // template arguments
1372 // 2) For the non-deduced template parameters of f. the
1373 // (rebuilt) template arguments corresponding.
1374 //
1375 // Note: the non-deduced template arguments of `f` might refer to arguments
1376 // deduced in 1), as in a type constraint.
1379 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
1380 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
1381 const auto &D = DeduceResults[Index];
1382 auto *TP = F->getTemplateParameters()->getParam(Index);
1383 if (IsNonDeducedArgument(D)) {
1384 // 2): Non-deduced template parameters would be substituted later.
1385 continue;
1386 }
1387 TemplateArgumentLoc Input =
1390 if (SemaRef.SubstTemplateArguments(Input, Args, Output))
1391 return nullptr;
1392 assert(TemplateArgsForBuildingFPrime[Index].isNull() &&
1393 "InstantiatedArgs must be null before setting");
1394 // CheckTemplateArgument is necessary for NTTP initializations.
1395 // FIXME: We may want to call CheckTemplateArguments instead, but we cannot
1396 // match packs as usual, since packs can appear in the middle of the
1397 // parameter list of a synthesized CTAD guide. See also the FIXME in
1398 // test/SemaCXX/cxx20-ctad-type-alias.cpp:test25.
1400 for (auto TA : Output.arguments())
1401 if (SemaRef.CheckTemplateArgument(
1402 TP, TA, F, F->getLocation(), F->getLocation(),
1403 /*ArgumentPackIndex=*/-1, CTAI,
1405 return nullptr;
1406 if (Input.getArgument().getKind() == TemplateArgument::Pack) {
1407 // We will substitute the non-deduced template arguments with these
1408 // transformed (unpacked at this point) arguments, where that substitution
1409 // requires a pack for the corresponding parameter packs.
1410 TemplateArgsForBuildingFPrime[Index] =
1412 } else {
1413 assert(Output.arguments().size() == 1);
1414 TemplateArgsForBuildingFPrime[Index] = CTAI.SugaredConverted[0];
1415 }
1416 }
1417
1418 // Case 2)
1419 // ...followed by the template parameters of f that were not deduced
1420 // (including their default template arguments)
1421 for (unsigned FTemplateParamIdx : NonDeducedTemplateParamsInFIndex) {
1422 auto *TP = F->getTemplateParameters()->getParam(FTemplateParamIdx);
1425 // We take a shortcut here, it is ok to reuse the
1426 // TemplateArgsForBuildingFPrime.
1427 Args.addOuterTemplateArguments(TemplateArgsForBuildingFPrime);
1428 NamedDecl *NewParam = transformTemplateParameter(
1429 SemaRef, F->getDeclContext(), TP, Args, FPrimeTemplateParams.size(),
1430 getDepthAndIndex(TP).first);
1431 FPrimeTemplateParams.push_back(NewParam);
1432
1433 assert(TemplateArgsForBuildingFPrime[FTemplateParamIdx].isNull() &&
1434 "The argument must be null before setting");
1435 TemplateArgsForBuildingFPrime[FTemplateParamIdx] =
1436 Context.getInjectedTemplateArg(NewParam);
1437 }
1438
1439 auto *TemplateArgListForBuildingFPrime =
1440 TemplateArgumentList::CreateCopy(Context, TemplateArgsForBuildingFPrime);
1441 // Form the f' by substituting the template arguments into f.
1442 if (auto *FPrime = SemaRef.InstantiateFunctionDeclaration(
1443 F, TemplateArgListForBuildingFPrime, AliasTemplate->getLocation(),
1445 auto *GG = cast<CXXDeductionGuideDecl>(FPrime);
1446
1447 Expr *IsDeducible = buildIsDeducibleConstraint(
1448 SemaRef, AliasTemplate, FPrime->getReturnType(), FPrimeTemplateParams);
1449 Expr *RequiresClause =
1450 buildAssociatedConstraints(SemaRef, F, AliasTemplate, DeduceResults,
1451 DeducedAliasTemplateParams, IsDeducible);
1452
1453 TemplateParameterList *FPrimeTemplateParamList = nullptr;
1454 if (!FPrimeTemplateParams.empty())
1455 FPrimeTemplateParamList = TemplateParameterList::Create(
1456 Context, AliasTemplate->getTemplateParameters()->getTemplateLoc(),
1457 AliasTemplate->getTemplateParameters()->getLAngleLoc(),
1458 FPrimeTemplateParams,
1459 AliasTemplate->getTemplateParameters()->getRAngleLoc(),
1460 /*RequiresClause=*/RequiresClause);
1461
1462 auto *DGuide = buildDeductionGuide(
1463 SemaRef, AliasTemplate, FPrimeTemplateParamList,
1464 GG->getCorrespondingConstructor(), GG->getExplicitSpecifier(),
1465 GG->getTypeSourceInfo(), AliasTemplate->getBeginLoc(),
1466 AliasTemplate->getLocation(), AliasTemplate->getEndLoc(),
1467 F->isImplicit());
1468 DGuide->setDeductionCandidateKind(GG->getDeductionCandidateKind());
1469 DGuide->setSourceDeductionGuide(SourceDeductionGuide);
1470 DGuide->setSourceDeductionGuideKind(
1472 return DGuide;
1473 }
1474 return nullptr;
1475}
1476
1477void DeclareImplicitDeductionGuidesForTypeAlias(
1479 if (AliasTemplate->isInvalidDecl())
1480 return;
1481 auto &Context = SemaRef.Context;
1482 auto [Template, AliasRhsTemplateArgs] =
1483 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
1484 if (!Template)
1485 return;
1486 auto SourceDeductionGuides = getSourceDeductionGuides(
1487 Context.DeclarationNames.getCXXDeductionGuideName(AliasTemplate),
1488 AliasTemplate->getDeclContext());
1489
1490 DeclarationNameInfo NameInfo(
1491 Context.DeclarationNames.getCXXDeductionGuideName(Template), Loc);
1492 LookupResult Guides(SemaRef, NameInfo, clang::Sema::LookupOrdinaryName);
1493 SemaRef.LookupQualifiedName(Guides, Template->getDeclContext());
1494 Guides.suppressDiagnostics();
1495
1496 for (auto *G : Guides) {
1497 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(G)) {
1498 if (SourceDeductionGuides.contains(DG))
1499 continue;
1500 // The deduction guide is a non-template function decl, we just clone it.
1501 auto *FunctionType =
1502 SemaRef.Context.getTrivialTypeSourceInfo(DG->getType());
1504 FunctionType->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1505
1506 // Clone the parameters.
1507 for (unsigned I = 0, N = DG->getNumParams(); I != N; ++I) {
1508 const auto *P = DG->getParamDecl(I);
1509 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(P->getType());
1510 ParmVarDecl *NewParam = ParmVarDecl::Create(
1511 SemaRef.Context, G->getDeclContext(),
1512 DG->getParamDecl(I)->getBeginLoc(), P->getLocation(), nullptr,
1513 TSI->getType(), TSI, SC_None, nullptr);
1514 NewParam->setScopeInfo(0, I);
1515 FPTL.setParam(I, NewParam);
1516 }
1517 auto *Transformed = buildDeductionGuide(
1518 SemaRef, AliasTemplate, /*TemplateParams=*/nullptr,
1519 /*Constructor=*/nullptr, DG->getExplicitSpecifier(), FunctionType,
1520 AliasTemplate->getBeginLoc(), AliasTemplate->getLocation(),
1521 AliasTemplate->getEndLoc(), DG->isImplicit());
1522 Transformed->setSourceDeductionGuide(DG);
1523 Transformed->setSourceDeductionGuideKind(
1525
1526 // FIXME: Here the synthesized deduction guide is not a templated
1527 // function. Per [dcl.decl]p4, the requires-clause shall be present only
1528 // if the declarator declares a templated function, a bug in standard?
1529 AssociatedConstraint Constraint(buildIsDeducibleConstraint(
1530 SemaRef, AliasTemplate, Transformed->getReturnType(), {}));
1531 if (const AssociatedConstraint &RC = DG->getTrailingRequiresClause()) {
1532 auto Conjunction = SemaRef.BuildBinOp(
1533 SemaRef.getCurScope(), SourceLocation{},
1534 BinaryOperatorKind::BO_LAnd, const_cast<Expr *>(RC.ConstraintExpr),
1535 const_cast<Expr *>(Constraint.ConstraintExpr));
1536 if (!Conjunction.isInvalid()) {
1537 Constraint.ConstraintExpr = Conjunction.getAs<Expr>();
1538 Constraint.ArgPackSubstIndex = RC.ArgPackSubstIndex;
1539 }
1540 }
1541 Transformed->setTrailingRequiresClause(Constraint);
1542 continue;
1543 }
1544 FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(G);
1545 if (!F || SourceDeductionGuides.contains(F->getTemplatedDecl()))
1546 continue;
1547 // The **aggregate** deduction guides are handled in a different code path
1548 // (DeclareAggregateDeductionGuideFromInitList), which involves the tricky
1549 // cache.
1550 auto *DGuide = cast<CXXDeductionGuideDecl>(F->getTemplatedDecl());
1551 if (DGuide->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
1552 continue;
1553
1554 BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate, DGuide, Loc);
1555 }
1556}
1557
1558// Build an aggregate deduction guide for a type alias template.
1559CXXDeductionGuideDecl *DeclareAggregateDeductionGuideForTypeAlias(
1561 MutableArrayRef<QualType> ParamTypes, SourceLocation Loc) {
1562 TemplateDecl *RHSTemplate =
1563 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate).first;
1564 if (!RHSTemplate)
1565 return nullptr;
1566
1568 llvm::SmallVector<QualType> NewParamTypes;
1569 ExtractTypeForDeductionGuide TypeAliasTransformer(SemaRef, TypedefDecls);
1570 for (QualType P : ParamTypes) {
1571 QualType Type = TypeAliasTransformer.TransformType(P);
1572 if (Type.isNull())
1573 return nullptr;
1574 NewParamTypes.push_back(Type);
1575 }
1576
1577 auto *RHSDeductionGuide = SemaRef.DeclareAggregateDeductionGuideFromInitList(
1578 RHSTemplate, NewParamTypes, Loc);
1579 if (!RHSDeductionGuide)
1580 return nullptr;
1581
1582 for (TypedefNameDecl *TD : TypedefDecls)
1583 TD->setDeclContext(RHSDeductionGuide);
1584
1585 return BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate,
1586 RHSDeductionGuide, Loc);
1587}
1588
1589} // namespace
1590
1593 SourceLocation Loc) {
1594 llvm::FoldingSetNodeID ID;
1595 ID.AddPointer(Template);
1596 for (auto &T : ParamTypes)
1597 T.getCanonicalType().Profile(ID);
1598 unsigned Hash = ID.computeHash();
1599
1600 auto Found = AggregateDeductionCandidates.find(Hash);
1602 return Found->getSecond();
1603
1604 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
1605 if (auto *GD = DeclareAggregateDeductionGuideForTypeAlias(
1606 *this, AliasTemplate, ParamTypes, Loc)) {
1607 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
1609 return GD;
1610 }
1611 return nullptr;
1612 }
1613
1614 if (CXXRecordDecl *DefRecord =
1615 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
1616 if (TemplateDecl *DescribedTemplate =
1617 DefRecord->getDescribedClassTemplate())
1618 Template = DescribedTemplate;
1619 }
1620
1621 DeclContext *DC = Template->getDeclContext();
1622 if (DC->isDependentContext())
1623 return nullptr;
1624
1625 ConvertConstructorToDeductionGuideTransform Transform(
1627 if (!isCompleteType(Loc, Transform.DeducedType))
1628 return nullptr;
1629
1630 // In case we were expanding a pack when we attempted to declare deduction
1631 // guides, turn off pack expansion for everything we're about to do.
1632 ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
1633 // Create a template instantiation record to track the "instantiation" of
1634 // constructors into deduction guides.
1635 InstantiatingTemplate BuildingDeductionGuides(
1636 *this, Loc, Template,
1638 if (BuildingDeductionGuides.isInvalid())
1639 return nullptr;
1640
1641 ClassTemplateDecl *Pattern =
1642 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
1643 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
1644
1645 CXXDeductionGuideDecl *GD = Transform.buildSimpleDeductionGuide(ParamTypes);
1646 SavedContext.pop();
1649 return GD;
1650}
1651
1653 SourceLocation Loc) {
1654 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
1655 DeclareImplicitDeductionGuidesForTypeAlias(*this, AliasTemplate, Loc);
1656 return;
1657 }
1658 CXXRecordDecl *DefRecord =
1659 dyn_cast_or_null<CXXRecordDecl>(Template->getTemplatedDecl());
1660 if (!DefRecord)
1661 return;
1662 if (const CXXRecordDecl *Definition = DefRecord->getDefinition()) {
1663 if (TemplateDecl *DescribedTemplate =
1664 Definition->getDescribedClassTemplate())
1665 Template = DescribedTemplate;
1666 }
1667
1668 DeclContext *DC = Template->getDeclContext();
1669 if (DC->isDependentContext())
1670 return;
1671
1672 ConvertConstructorToDeductionGuideTransform Transform(
1674 if (!isCompleteType(Loc, Transform.DeducedType))
1675 return;
1676
1677 if (hasDeclaredDeductionGuides(Transform.DeductionGuideName, DC))
1678 return;
1679
1680 // In case we were expanding a pack when we attempted to declare deduction
1681 // guides, turn off pack expansion for everything we're about to do.
1682 ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
1683 // Create a template instantiation record to track the "instantiation" of
1684 // constructors into deduction guides.
1685 InstantiatingTemplate BuildingDeductionGuides(
1686 *this, Loc, Template,
1688 if (BuildingDeductionGuides.isInvalid())
1689 return;
1690
1691 // Convert declared constructors into deduction guide templates.
1692 // FIXME: Skip constructors for which deduction must necessarily fail (those
1693 // for which some class template parameter without a default argument never
1694 // appears in a deduced context).
1695 ClassTemplateDecl *Pattern =
1696 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
1697 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
1698 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
1699 bool AddedAny = false;
1700 for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) {
1701 D = D->getUnderlyingDecl();
1702 if (D->isInvalidDecl() || D->isImplicit())
1703 continue;
1704
1705 D = cast<NamedDecl>(D->getCanonicalDecl());
1706
1707 // Within C++20 modules, we may have multiple same constructors in
1708 // multiple same RecordDecls. And it doesn't make sense to create
1709 // duplicated deduction guides for the duplicated constructors.
1710 if (ProcessedCtors.count(D))
1711 continue;
1712
1713 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1714 auto *CD =
1715 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1716 // Class-scope explicit specializations (MS extension) do not result in
1717 // deduction guides.
1718 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1719 continue;
1720
1721 // Cannot make a deduction guide when unparsed arguments are present.
1722 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
1723 return !P || P->hasUnparsedDefaultArg();
1724 }))
1725 continue;
1726
1727 ProcessedCtors.insert(D);
1728 Transform.transformConstructor(FTD, CD);
1729 AddedAny = true;
1730 }
1731
1732 // C++17 [over.match.class.deduct]
1733 // -- If C is not defined or does not declare any constructors, an
1734 // additional function template derived as above from a hypothetical
1735 // constructor C().
1736 if (!AddedAny)
1737 Transform.buildSimpleDeductionGuide({});
1738
1739 // -- An additional function template derived as above from a hypothetical
1740 // constructor C(C), called the copy deduction candidate.
1741 Transform.buildSimpleDeductionGuide(Transform.DeducedType)
1742 ->setDeductionCandidateKind(DeductionCandidate::Copy);
1743
1744 SavedContext.pop();
1745}
Defines the clang::ASTContext interface.
Defines enumerations for traits support.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
TranslationUnitDecl * getTranslationUnitDecl() const
DeclarationNameTable DeclarationNames
Definition ASTContext.h:850
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5138
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
ExplicitSpecifier getExplicitSpecifier() const
Definition DeclCXX.h:2714
Represents a C++ deduction guide declaration.
Definition DeclCXX.h:2001
void setDeductionCandidateKind(DeductionCandidate K)
Definition DeclCXX.h:2092
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr, DeductionCandidate Kind=DeductionCandidate::Normal, const AssociatedConstraint &TrailingRequiresClause={}, const CXXDeductionGuideDecl *SourceDG=nullptr, SourceDeductionGuideKind SK=SourceDeductionGuideKind::None)
Definition DeclCXX.cpp:2383
CXXConstructorDecl * getCorrespondingConstructor() const
Get the constructor from which this deduction guide was generated, if this is an implicit deduction g...
Definition DeclCXX.h:2071
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2279
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isRecord() const
Definition DeclBase.h:2226
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:510
SourceLocation getLocation() const
Definition DeclBase.h:447
void setImplicit(bool I=true)
Definition DeclBase.h:602
DeclContext * getDeclContext()
Definition DeclBase.h:456
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
The name of a declaration.
NameKind getNameKind() const
Determine what kind of name this is.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:823
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:832
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:856
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:752
SourceLocation getNameLoc() const
Definition TypeLoc.h:761
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:756
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
This represents one expression.
Definition Expr.h:113
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4244
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4232
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
void getAssociatedConstraints(SmallVectorImpl< AssociatedConstraint > &ACs) const
Get the associated-constraints of this function declaration.
Definition Decl.h:2883
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5802
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
unsigned getNumParams() const
Definition TypeLoc.h:1747
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1699
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1695
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1711
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1754
ArrayRef< ParmVarDecl * > getParams() const
Definition TypeLoc.h:1738
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1719
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1703
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1733
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1691
SourceLocation getLParenLoc() const
Definition TypeLoc.h:1707
SourceLocation getRParenLoc() const
Definition TypeLoc.h:1715
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4594
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
void InstantiatedLocal(const Decl *D, Decl *Inst)
Represents the results of name lookup.
Definition Lookup.h:147
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterRetainedLevel()
Add an outermost level that we are not substituting.
Definition Template.h:269
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:218
void setKind(TemplateSubstitutionKind K)
Definition Template.h:111
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
This represents a decl that may have a name.
Definition Decl.h:275
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
NestedNameSpecifier getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, int D, int P, const IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
TypeSourceInfo * getExpansionTypeSourceInfo(unsigned I) const
Retrieve a particular expansion type source info within an expanded parameter pack.
unsigned getNumExpansionTypes() const
Retrieves the number of expansion types in an expanded parameter pack.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
Expr * getPlaceholderTypeConstraint() const
Return the constraint introduced by the placeholder type of this non-type template parameter (if any)...
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Represents a parameter to a function.
Definition Decl.h:1820
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1880
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition Decl.cpp:3013
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1853
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2943
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3044
unsigned getFunctionScopeDepth() const
Definition Decl.h:1870
A (possibly-)qualified type.
Definition TypeBase.h:938
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3810
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13784
A RAII object to temporarily push a declaration context.
Definition Sema.h:3534
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraint)
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13182
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1137
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9394
FunctionDecl * InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC=CodeSynthesisContext::ExplicitTemplateArgumentSubstitution)
Instantiate (or find existing instantiation of) a function template with a given set of template argu...
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12087
ASTContext & Context
Definition Sema.h:1304
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateName NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
ASTContext & getASTContext() const
Definition Sema.h:935
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
const LangOptions & getLangOpts() const
Definition Sema.h:928
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition Sema.h:9082
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15623
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CXXDeductionGuideDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
Encodes a location in the source.
SourceLocation getBegin() const
A convenient class for passing around template argument information.
ArrayRef< TemplateArgumentLoc > arguments() const
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
Represents a template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
bool isNull() const
Determine whether this template argument has no value.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
SourceLocation getTemplateLoc() const
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
bool wasDeclaredWithTypename() const
Whether this template template parameter was declared with the 'typename' keyword.
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
unsigned getNumExpansionTemplateParameters() const
Retrieves the number of expansion template parameters in an expanded parameter pack.
TemplateNameKind templateParameterKind() const
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, int D, int P, bool ParameterPack, IdentifierInfo *Id, TemplateNameKind ParameterKind, bool Typename, TemplateParameterList *Params)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
bool wasDeclaredWithTypename() const
Whether this template type parameter was declared with the 'typename' keyword.
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
bool hasTypeConstraint() const
Determine whether this template parameter has a type-constraint.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
const TypeConstraint * getTypeConstraint() const
Returns the type constraint associated with this template parameter (if any).
UnsignedOrNone getNumExpansionParameters() const
Whether this parameter is a template type parameter pack that has a known list of different type-cons...
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isParameterPack() const
Returns whether this is a parameter pack.
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
QualType RebuildTemplateSpecializationType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &Args)
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5882
Declaration of an alias template.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3682
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:890
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8399
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8410
static TypeTraitExpr * Create(const ASTContext &C, QualType T, SourceLocation Loc, TypeTrait Kind, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc, bool Value)
Create a new type trait expression.
Definition ExprCXX.cpp:1939
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isRValueReferenceType() const
Definition TypeBase.h:8697
bool isArrayType() const
Definition TypeBase.h:8764
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9331
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2867
bool isLValueReferenceType() const
Definition TypeBase.h:8693
bool isFunctionType() const
Definition TypeBase.h:8661
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9264
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition Decl.cpp:5831
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3747
QualType getType() const
Definition Decl.h:724
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1175
Provides information about an attempted template argument deduction, whose success or failure was des...
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
Definition Template.h:54
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
@ AS_public
Definition Specifiers.h:125
@ SC_None
Definition Specifiers.h:251
@ Result
The result type of a method or function.
Definition TypeBase.h:906
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:556
@ DeducedAsDependent
This is a special case where the initializer is dependent, so we can't deduce a type yet.
Definition TypeBase.h:1828
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
U cast(CodeGen::Address addr)
Definition Address.h:327
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5996
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6017
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
const Expr * ConstraintExpr
Definition Decl.h:89
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:90
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12108
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13337
A stack object to be created when performing template instantiation.
Definition Sema.h:13427