clang 20.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"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/Basic/LLVM.h"
36#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/Overload.h"
41#include "clang/Sema/Scope.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/SmallVector.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/ErrorHandling.h"
50#include <cassert>
51#include <optional>
52#include <utility>
53
54using namespace clang;
55using namespace sema;
56
57namespace {
58/// Tree transform to "extract" a transformed type from a class template's
59/// constructor to a deduction guide.
60class ExtractTypeForDeductionGuide
61 : public TreeTransform<ExtractTypeForDeductionGuide> {
62 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
63 ClassTemplateDecl *NestedPattern;
64 const MultiLevelTemplateArgumentList *OuterInstantiationArgs;
65 std::optional<TemplateDeclInstantiator> TypedefNameInstantiator;
66
67public:
69 ExtractTypeForDeductionGuide(
70 Sema &SemaRef,
71 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs,
72 ClassTemplateDecl *NestedPattern = nullptr,
73 const MultiLevelTemplateArgumentList *OuterInstantiationArgs = nullptr)
74 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs),
75 NestedPattern(NestedPattern),
76 OuterInstantiationArgs(OuterInstantiationArgs) {
77 if (OuterInstantiationArgs)
78 TypedefNameInstantiator.emplace(
79 SemaRef, SemaRef.getASTContext().getTranslationUnitDecl(),
80 *OuterInstantiationArgs);
81 }
82
83 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
84
85 /// Returns true if it's safe to substitute \p Typedef with
86 /// \p OuterInstantiationArgs.
87 bool mightReferToOuterTemplateParameters(TypedefNameDecl *Typedef) {
88 if (!NestedPattern)
89 return false;
90
91 static auto WalkUp = [](DeclContext *DC, DeclContext *TargetDC) {
92 if (DC->Equals(TargetDC))
93 return true;
94 while (DC->isRecord()) {
95 if (DC->Equals(TargetDC))
96 return true;
97 DC = DC->getParent();
98 }
99 return false;
100 };
101
102 if (WalkUp(Typedef->getDeclContext(), NestedPattern->getTemplatedDecl()))
103 return true;
104 if (WalkUp(NestedPattern->getTemplatedDecl(), Typedef->getDeclContext()))
105 return true;
106 return false;
107 }
108
111 SourceLocation TemplateNameLoc,
112 TemplateArgumentListInfo &TemplateArgs) {
113 if (!OuterInstantiationArgs ||
114 !isa_and_present<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()))
115 return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc,
116 TemplateArgs);
117
118 auto *TATD = cast<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
119 auto *Pattern = TATD;
120 while (Pattern->getInstantiatedFromMemberTemplate())
121 Pattern = Pattern->getInstantiatedFromMemberTemplate();
122 if (!mightReferToOuterTemplateParameters(Pattern->getTemplatedDecl()))
123 return Base::RebuildTemplateSpecializationType(Template, TemplateNameLoc,
124 TemplateArgs);
125
126 Decl *NewD =
127 TypedefNameInstantiator->InstantiateTypeAliasTemplateDecl(TATD);
128 if (!NewD)
129 return QualType();
130
131 auto *NewTATD = cast<TypeAliasTemplateDecl>(NewD);
132 MaterializedTypedefs.push_back(NewTATD->getTemplatedDecl());
133
135 TemplateName(NewTATD), TemplateNameLoc, TemplateArgs);
136 }
137
138 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
139 ASTContext &Context = SemaRef.getASTContext();
140 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
141 TypedefNameDecl *Decl = OrigDecl;
142 // Transform the underlying type of the typedef and clone the Decl only if
143 // the typedef has a dependent context.
144 bool InDependentContext = OrigDecl->getDeclContext()->isDependentContext();
145
146 // A typedef/alias Decl within the NestedPattern may reference the outer
147 // template parameters. They're substituted with corresponding instantiation
148 // arguments here and in RebuildTemplateSpecializationType() above.
149 // Otherwise, we would have a CTAD guide with "dangling" template
150 // parameters.
151 // For example,
152 // template <class T> struct Outer {
153 // using Alias = S<T>;
154 // template <class U> struct Inner {
155 // Inner(Alias);
156 // };
157 // };
158 if (OuterInstantiationArgs && InDependentContext &&
160 Decl = cast_if_present<TypedefNameDecl>(
161 TypedefNameInstantiator->InstantiateTypedefNameDecl(
162 OrigDecl, /*IsTypeAlias=*/isa<TypeAliasDecl>(OrigDecl)));
163 if (!Decl)
164 return QualType();
165 MaterializedTypedefs.push_back(Decl);
166 } else if (InDependentContext) {
167 TypeLocBuilder InnerTLB;
168 QualType Transformed =
169 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
170 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
171 if (isa<TypeAliasDecl>(OrigDecl))
173 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
174 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
175 else {
176 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
178 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
179 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
180 }
181 MaterializedTypedefs.push_back(Decl);
182 }
183
184 QualType TDTy = Context.getTypedefType(Decl);
185 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
186 TypedefTL.setNameLoc(TL.getNameLoc());
187
188 return TDTy;
189 }
190};
191
192// Build a deduction guide using the provided information.
193//
194// A deduction guide can be either a template or a non-template function
195// declaration. If \p TemplateParams is null, a non-template function
196// declaration will be created.
197NamedDecl *buildDeductionGuide(
198 Sema &SemaRef, TemplateDecl *OriginalTemplate,
199 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
201 SourceLocation Loc, SourceLocation LocEnd, bool IsImplicit,
202 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
203 DeclContext *DC = OriginalTemplate->getDeclContext();
204 auto DeductionGuideName =
206 OriginalTemplate);
207
208 DeclarationNameInfo Name(DeductionGuideName, Loc);
210 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
211
212 // Build the implicit deduction guide template.
213 auto *Guide =
214 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
215 TInfo->getType(), TInfo, LocEnd, Ctor);
216 Guide->setImplicit(IsImplicit);
217 Guide->setParams(Params);
218
219 for (auto *Param : Params)
220 Param->setDeclContext(Guide);
221 for (auto *TD : MaterializedTypedefs)
222 TD->setDeclContext(Guide);
223 if (isa<CXXRecordDecl>(DC))
224 Guide->setAccess(AS_public);
225
226 if (!TemplateParams) {
227 DC->addDecl(Guide);
228 return Guide;
229 }
230
231 auto *GuideTemplate = FunctionTemplateDecl::Create(
232 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
233 GuideTemplate->setImplicit(IsImplicit);
234 Guide->setDescribedFunctionTemplate(GuideTemplate);
235
236 if (isa<CXXRecordDecl>(DC))
237 GuideTemplate->setAccess(AS_public);
238
239 DC->addDecl(GuideTemplate);
240 return GuideTemplate;
241}
242
243// Transform a given template type parameter `TTP`.
244TemplateTypeParmDecl *transformTemplateTypeParam(
245 Sema &SemaRef, DeclContext *DC, TemplateTypeParmDecl *TTP,
246 MultiLevelTemplateArgumentList &Args, unsigned NewDepth, unsigned NewIndex,
247 bool EvaluateConstraint) {
248 // TemplateTypeParmDecl's index cannot be changed after creation, so
249 // substitute it directly.
250 auto *NewTTP = TemplateTypeParmDecl::Create(
251 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), NewDepth,
252 NewIndex, TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
253 TTP->isParameterPack(), TTP->hasTypeConstraint(),
255 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
256 : std::nullopt);
257 if (const auto *TC = TTP->getTypeConstraint())
258 SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
259 /*EvaluateConstraint=*/EvaluateConstraint);
260 if (TTP->hasDefaultArgument()) {
261 TemplateArgumentLoc InstantiatedDefaultArg;
262 if (!SemaRef.SubstTemplateArgument(
263 TTP->getDefaultArgument(), Args, InstantiatedDefaultArg,
264 TTP->getDefaultArgumentLoc(), TTP->getDeclName()))
265 NewTTP->setDefaultArgument(SemaRef.Context, InstantiatedDefaultArg);
266 }
267 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TTP, NewTTP);
268 return NewTTP;
269}
270// Similar to above, but for non-type template or template template parameters.
271template <typename NonTypeTemplateOrTemplateTemplateParmDecl>
272NonTypeTemplateOrTemplateTemplateParmDecl *
273transformTemplateParam(Sema &SemaRef, DeclContext *DC,
274 NonTypeTemplateOrTemplateTemplateParmDecl *OldParam,
275 MultiLevelTemplateArgumentList &Args, unsigned NewIndex,
276 unsigned NewDepth) {
277 // Ask the template instantiator to do the heavy lifting for us, then adjust
278 // the index of the parameter once it's done.
279 auto *NewParam = cast<NonTypeTemplateOrTemplateTemplateParmDecl>(
280 SemaRef.SubstDecl(OldParam, DC, Args));
281 NewParam->setPosition(NewIndex);
282 NewParam->setDepth(NewDepth);
283 return NewParam;
284}
285
286NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
289 unsigned NewIndex, unsigned NewDepth,
290 bool EvaluateConstraint = true) {
291 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam))
292 return transformTemplateTypeParam(
293 SemaRef, DC, TTP, Args, NewDepth, NewIndex,
294 /*EvaluateConstraint=*/EvaluateConstraint);
295 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
296 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex, NewDepth);
297 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(TemplateParam))
298 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex, NewDepth);
299 llvm_unreachable("Unhandled template parameter types");
300}
301
302/// Transform to convert portions of a constructor declaration into the
303/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
304struct ConvertConstructorToDeductionGuideTransform {
305 ConvertConstructorToDeductionGuideTransform(Sema &S,
306 ClassTemplateDecl *Template)
307 : SemaRef(S), Template(Template) {
308 // If the template is nested, then we need to use the original
309 // pattern to iterate over the constructors.
310 ClassTemplateDecl *Pattern = Template;
311 while (Pattern->getInstantiatedFromMemberTemplate()) {
312 if (Pattern->isMemberSpecialization())
313 break;
314 Pattern = Pattern->getInstantiatedFromMemberTemplate();
315 NestedPattern = Pattern;
316 }
317
318 if (NestedPattern)
319 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
320 }
321
322 Sema &SemaRef;
323 ClassTemplateDecl *Template;
324 ClassTemplateDecl *NestedPattern = nullptr;
325
326 DeclContext *DC = Template->getDeclContext();
327 CXXRecordDecl *Primary = Template->getTemplatedDecl();
328 DeclarationName DeductionGuideName =
330
331 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
332
333 // Index adjustment to apply to convert depth-1 template parameters into
334 // depth-0 template parameters.
335 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
336
337 // Instantiation arguments for the outermost depth-1 templates
338 // when the template is nested
339 MultiLevelTemplateArgumentList OuterInstantiationArgs;
340
341 /// Transform a constructor declaration into a deduction guide.
342 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
343 CXXConstructorDecl *CD) {
345
347
348 // C++ [over.match.class.deduct]p1:
349 // -- For each constructor of the class template designated by the
350 // template-name, a function template with the following properties:
351
352 // -- The template parameters are the template parameters of the class
353 // template followed by the template parameters (including default
354 // template arguments) of the constructor, if any.
355 TemplateParameterList *TemplateParams =
356 SemaRef.GetTemplateParameterList(Template);
357 if (FTD) {
358 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
361 AllParams.reserve(TemplateParams->size() + InnerParams->size());
362 AllParams.insert(AllParams.begin(), TemplateParams->begin(),
363 TemplateParams->end());
364 SubstArgs.reserve(InnerParams->size());
365 Depth1Args.reserve(InnerParams->size());
366
367 // Later template parameters could refer to earlier ones, so build up
368 // a list of substituted template arguments as we go.
369 for (NamedDecl *Param : *InnerParams) {
371 Args.setKind(TemplateSubstitutionKind::Rewrite);
372 Args.addOuterTemplateArguments(Depth1Args);
374 if (NestedPattern)
375 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
376 auto [Depth, Index] = getDepthAndIndex(Param);
377 NamedDecl *NewParam = transformTemplateParameter(
378 SemaRef, DC, Param, Args, Index + Depth1IndexAdjustment, Depth - 1);
379 if (!NewParam)
380 return nullptr;
381 // Constraints require that we substitute depth-1 arguments
382 // to match depths when substituted for evaluation later
383 Depth1Args.push_back(SemaRef.Context.getInjectedTemplateArg(NewParam));
384
385 if (NestedPattern) {
386 auto [Depth, Index] = getDepthAndIndex(NewParam);
387 NewParam = transformTemplateParameter(
388 SemaRef, DC, NewParam, OuterInstantiationArgs, Index,
389 Depth - OuterInstantiationArgs.getNumSubstitutedLevels(),
390 /*EvaluateConstraint=*/false);
391 }
392
393 assert(NewParam->getTemplateDepth() == 0 &&
394 "Unexpected template parameter depth");
395
396 AllParams.push_back(NewParam);
397 SubstArgs.push_back(SemaRef.Context.getInjectedTemplateArg(NewParam));
398 }
399
400 // Substitute new template parameters into requires-clause if present.
401 Expr *RequiresClause = nullptr;
402 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
404 Args.setKind(TemplateSubstitutionKind::Rewrite);
405 Args.addOuterTemplateArguments(Depth1Args);
407 if (NestedPattern)
408 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
409 ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
410 if (E.isInvalid())
411 return nullptr;
412 RequiresClause = E.getAs<Expr>();
413 }
414
415 TemplateParams = TemplateParameterList::Create(
416 SemaRef.Context, InnerParams->getTemplateLoc(),
417 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
418 RequiresClause);
419 }
420
421 // If we built a new template-parameter-list, track that we need to
422 // substitute references to the old parameters into references to the
423 // new ones.
425 Args.setKind(TemplateSubstitutionKind::Rewrite);
426 if (FTD) {
427 Args.addOuterTemplateArguments(SubstArgs);
429 }
430
432 ->getTypeLoc()
434 assert(FPTL && "no prototype for constructor declaration");
435
436 // Transform the type of the function, adjusting the return type and
437 // replacing references to the old parameters with references to the
438 // new ones.
439 TypeLocBuilder TLB;
441 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
442 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
443 MaterializedTypedefs);
444 if (NewType.isNull())
445 return nullptr;
446 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
447
448 return buildDeductionGuide(
449 SemaRef, Template, TemplateParams, CD, CD->getExplicitSpecifier(),
450 NewTInfo, CD->getBeginLoc(), CD->getLocation(), CD->getEndLoc(),
451 /*IsImplicit=*/true, MaterializedTypedefs);
452 }
453
454 /// Build a deduction guide with the specified parameter types.
455 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
456 SourceLocation Loc = Template->getLocation();
457
458 // Build the requested type.
460 EPI.HasTrailingReturn = true;
461 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
462 DeductionGuideName, EPI);
463 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
464 if (NestedPattern)
465 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
466 DeductionGuideName);
467
468 if (!TSI)
469 return nullptr;
470
473
474 // Build the parameters, needed during deduction / substitution.
476 for (auto T : ParamTypes) {
477 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
478 if (NestedPattern)
479 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
481 if (!TSI)
482 return nullptr;
483
484 ParmVarDecl *NewParam =
485 ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
486 TSI->getType(), TSI, SC_None, nullptr);
487 NewParam->setScopeInfo(0, Params.size());
488 FPTL.setParam(Params.size(), NewParam);
489 Params.push_back(NewParam);
490 }
491
492 return buildDeductionGuide(
493 SemaRef, Template, SemaRef.GetTemplateParameterList(Template), nullptr,
494 ExplicitSpecifier(), TSI, Loc, Loc, Loc, /*IsImplicit=*/true);
495 }
496
497private:
498 QualType transformFunctionProtoType(
502 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
503 SmallVector<QualType, 4> ParamTypes;
504 const FunctionProtoType *T = TL.getTypePtr();
505
506 // -- The types of the function parameters are those of the constructor.
507 for (auto *OldParam : TL.getParams()) {
508 ParmVarDecl *NewParam = OldParam;
509 // Given
510 // template <class T> struct C {
511 // template <class U> struct D {
512 // template <class V> D(U, V);
513 // };
514 // };
515 // First, transform all the references to template parameters that are
516 // defined outside of the surrounding class template. That is T in the
517 // above example.
518 if (NestedPattern) {
519 NewParam = transformFunctionTypeParam(
520 NewParam, OuterInstantiationArgs, MaterializedTypedefs,
521 /*TransformingOuterPatterns=*/true);
522 if (!NewParam)
523 return QualType();
524 }
525 // Then, transform all the references to template parameters that are
526 // defined at the class template and the constructor. In this example,
527 // they're U and V, respectively.
528 NewParam =
529 transformFunctionTypeParam(NewParam, Args, MaterializedTypedefs,
530 /*TransformingOuterPatterns=*/false);
531 if (!NewParam)
532 return QualType();
533 ParamTypes.push_back(NewParam->getType());
534 Params.push_back(NewParam);
535 }
536
537 // -- The return type is the class template specialization designated by
538 // the template-name and template arguments corresponding to the
539 // template parameters obtained from the class template.
540 //
541 // We use the injected-class-name type of the primary template instead.
542 // This has the convenient property that it is different from any type that
543 // the user can write in a deduction-guide (because they cannot enter the
544 // context of the template), so implicit deduction guides can never collide
545 // with explicit ones.
546 QualType ReturnType = DeducedType;
547 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
548
549 // Resolving a wording defect, we also inherit the variadicness of the
550 // constructor.
552 EPI.Variadic = T->isVariadic();
553 EPI.HasTrailingReturn = true;
554
555 QualType Result = SemaRef.BuildFunctionType(
556 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
557 if (Result.isNull())
558 return QualType();
559
562 NewTL.setLParenLoc(TL.getLParenLoc());
563 NewTL.setRParenLoc(TL.getRParenLoc());
566 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
567 NewTL.setParam(I, Params[I]);
568
569 return Result;
570 }
571
572 ParmVarDecl *transformFunctionTypeParam(
574 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs,
575 bool TransformingOuterPatterns) {
576 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
577 TypeSourceInfo *NewDI;
578 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
579 // Expand out the one and only element in each inner pack.
580 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
581 NewDI =
582 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
583 OldParam->getLocation(), OldParam->getDeclName());
584 if (!NewDI)
585 return nullptr;
586 NewDI =
587 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
588 PackTL.getTypePtr()->getNumExpansions());
589 } else
590 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
591 OldParam->getDeclName());
592 if (!NewDI)
593 return nullptr;
594
595 // Extract the type. This (for instance) replaces references to typedef
596 // members of the current instantiations with the definitions of those
597 // typedefs, avoiding triggering instantiation of the deduced type during
598 // deduction.
599 NewDI = ExtractTypeForDeductionGuide(
600 SemaRef, MaterializedTypedefs, NestedPattern,
601 TransformingOuterPatterns ? &Args : nullptr)
602 .transform(NewDI);
603
604 // Resolving a wording defect, we also inherit default arguments from the
605 // constructor.
606 ExprResult NewDefArg;
607 if (OldParam->hasDefaultArg()) {
608 // We don't care what the value is (we won't use it); just create a
609 // placeholder to indicate there is a default argument.
610 QualType ParamTy = NewDI->getType();
611 NewDefArg = new (SemaRef.Context)
613 ParamTy.getNonLValueExprType(SemaRef.Context),
615 : ParamTy->isRValueReferenceType() ? VK_XValue
616 : VK_PRValue);
617 }
618 // Handle arrays and functions decay.
619 auto NewType = NewDI->getType();
620 if (NewType->isArrayType() || NewType->isFunctionType())
621 NewType = SemaRef.Context.getDecayedType(NewType);
622
624 SemaRef.Context, DC, OldParam->getInnerLocStart(),
625 OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewDI,
626 OldParam->getStorageClass(), NewDefArg.get());
627 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
628 OldParam->getFunctionScopeIndex());
629 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
630 return NewParam;
631 }
632};
633
634// Find all template parameters that appear in the given DeducedArgs.
635// Return the indices of the template parameters in the TemplateParams.
636SmallVector<unsigned> TemplateParamsReferencedInTemplateArgumentList(
637 const TemplateParameterList *TemplateParamsList,
638 ArrayRef<TemplateArgument> DeducedArgs) {
639 struct TemplateParamsReferencedFinder : DynamicRecursiveASTVisitor {
640 const TemplateParameterList *TemplateParamList;
641 llvm::BitVector ReferencedTemplateParams;
642
643 TemplateParamsReferencedFinder(
644 const TemplateParameterList *TemplateParamList)
645 : TemplateParamList(TemplateParamList),
646 ReferencedTemplateParams(TemplateParamList->size()) {}
647
648 bool VisitTemplateTypeParmType(TemplateTypeParmType *TTP) override {
649 // We use the index and depth to retrieve the corresponding template
650 // parameter from the parameter list, which is more robost.
651 Mark(TTP->getDepth(), TTP->getIndex());
652 return true;
653 }
654
655 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
656 MarkAppeared(DRE->getFoundDecl());
657 return true;
658 }
659
660 bool TraverseTemplateName(TemplateName Template) override {
661 if (auto *TD = Template.getAsTemplateDecl())
662 MarkAppeared(TD);
664 }
665
666 void MarkAppeared(NamedDecl *ND) {
669 auto [Depth, Index] = getDepthAndIndex(ND);
670 Mark(Depth, Index);
671 }
672 }
673 void Mark(unsigned Depth, unsigned Index) {
674 if (Index < TemplateParamList->size() &&
675 TemplateParamList->getParam(Index)->getTemplateDepth() == Depth)
676 ReferencedTemplateParams.set(Index);
677 }
678 };
679 TemplateParamsReferencedFinder Finder(TemplateParamsList);
680 Finder.TraverseTemplateArguments(DeducedArgs);
681
682 SmallVector<unsigned> Results;
683 for (unsigned Index = 0; Index < TemplateParamsList->size(); ++Index) {
684 if (Finder.ReferencedTemplateParams[Index])
685 Results.push_back(Index);
686 }
687 return Results;
688}
689
690bool hasDeclaredDeductionGuides(DeclarationName Name, DeclContext *DC) {
691 // Check whether we've already declared deduction guides for this template.
692 // FIXME: Consider storing a flag on the template to indicate this.
693 assert(Name.getNameKind() ==
694 DeclarationName::NameKind::CXXDeductionGuideName &&
695 "name must be a deduction guide name");
696 auto Existing = DC->lookup(Name);
697 for (auto *D : Existing)
698 if (D->isImplicit())
699 return true;
700 return false;
701}
702
703// Build the associated constraints for the alias deduction guides.
704// C++ [over.match.class.deduct]p3.3:
705// The associated constraints ([temp.constr.decl]) are the conjunction of the
706// associated constraints of g and a constraint that is satisfied if and only
707// if the arguments of A are deducible (see below) from the return type.
708//
709// The return result is expected to be the require-clause for the synthesized
710// alias deduction guide.
711Expr *
712buildAssociatedConstraints(Sema &SemaRef, FunctionTemplateDecl *F,
715 unsigned FirstUndeducedParamIdx, Expr *IsDeducible) {
717 if (!RC)
718 return IsDeducible;
719
720 ASTContext &Context = SemaRef.Context;
722
723 // In the clang AST, constraint nodes are deliberately not instantiated unless
724 // they are actively being evaluated. Consequently, occurrences of template
725 // parameters in the require-clause expression have a subtle "depth"
726 // difference compared to normal occurrences in places, such as function
727 // parameters. When transforming the require-clause, we must take this
728 // distinction into account:
729 //
730 // 1) In the transformed require-clause, occurrences of template parameters
731 // must use the "uninstantiated" depth;
732 // 2) When substituting on the require-clause expr of the underlying
733 // deduction guide, we must use the entire set of template argument lists;
734 //
735 // It's important to note that we're performing this transformation on an
736 // *instantiated* AliasTemplate.
737
738 // For 1), if the alias template is nested within a class template, we
739 // calcualte the 'uninstantiated' depth by adding the substitution level back.
740 unsigned AdjustDepth = 0;
741 if (auto *PrimaryTemplate =
742 AliasTemplate->getInstantiatedFromMemberTemplate())
743 AdjustDepth = PrimaryTemplate->getTemplateDepth();
744
745 // We rebuild all template parameters with the uninstantiated depth, and
746 // build template arguments refer to them.
747 SmallVector<TemplateArgument> AdjustedAliasTemplateArgs;
748
749 for (auto *TP : *AliasTemplate->getTemplateParameters()) {
750 // Rebuild any internal references to earlier parameters and reindex
751 // as we go.
753 Args.setKind(TemplateSubstitutionKind::Rewrite);
754 Args.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
755 NamedDecl *NewParam = transformTemplateParameter(
756 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
757 /*NewIndex=*/AdjustedAliasTemplateArgs.size(),
758 getDepthAndIndex(TP).first + AdjustDepth);
759
760 TemplateArgument NewTemplateArgument =
761 Context.getInjectedTemplateArg(NewParam);
762 AdjustedAliasTemplateArgs.push_back(NewTemplateArgument);
763 }
764 // Template arguments used to transform the template arguments in
765 // DeducedResults.
766 SmallVector<TemplateArgument> TemplateArgsForBuildingRC(
768 // Transform the transformed template args
770 Args.setKind(TemplateSubstitutionKind::Rewrite);
771 Args.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
772
773 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
774 const auto &D = DeduceResults[Index];
775 if (D.isNull()) { // non-deduced template parameters of f
776 NamedDecl *TP = F->getTemplateParameters()->getParam(Index);
778 Args.setKind(TemplateSubstitutionKind::Rewrite);
779 Args.addOuterTemplateArguments(TemplateArgsForBuildingRC);
780 // Rebuild the template parameter with updated depth and index.
781 NamedDecl *NewParam =
782 transformTemplateParameter(SemaRef, F->getDeclContext(), TP, Args,
783 /*NewIndex=*/FirstUndeducedParamIdx,
784 getDepthAndIndex(TP).first + AdjustDepth);
785 FirstUndeducedParamIdx += 1;
786 assert(TemplateArgsForBuildingRC[Index].isNull());
787 TemplateArgsForBuildingRC[Index] =
788 Context.getInjectedTemplateArg(NewParam);
789 continue;
790 }
791 TemplateArgumentLoc Input =
793 TemplateArgumentLoc Output;
794 if (!SemaRef.SubstTemplateArgument(Input, Args, Output)) {
795 assert(TemplateArgsForBuildingRC[Index].isNull() &&
796 "InstantiatedArgs must be null before setting");
797 TemplateArgsForBuildingRC[Index] = Output.getArgument();
798 }
799 }
800
801 // A list of template arguments for transforming the require-clause of F.
802 // It must contain the entire set of template argument lists.
803 MultiLevelTemplateArgumentList ArgsForBuildingRC;
805 ArgsForBuildingRC.addOuterTemplateArguments(TemplateArgsForBuildingRC);
806 // For 2), if the underlying deduction guide F is nested in a class template,
807 // we need the entire template argument list, as the constraint AST in the
808 // require-clause of F remains completely uninstantiated.
809 //
810 // For example:
811 // template <typename T> // depth 0
812 // struct Outer {
813 // template <typename U>
814 // struct Foo { Foo(U); };
815 //
816 // template <typename U> // depth 1
817 // requires C<U>
818 // Foo(U) -> Foo<int>;
819 // };
820 // template <typename U>
821 // using AFoo = Outer<int>::Foo<U>;
822 //
823 // In this scenario, the deduction guide for `Foo` inside `Outer<int>`:
824 // - The occurrence of U in the require-expression is [depth:1, index:0]
825 // - The occurrence of U in the function parameter is [depth:0, index:0]
826 // - The template parameter of U is [depth:0, index:0]
827 //
828 // We add the outer template arguments which is [int] to the multi-level arg
829 // list to ensure that the occurrence U in `C<U>` will be replaced with int
830 // during the substitution.
831 //
832 // NOTE: The underlying deduction guide F is instantiated -- either from an
833 // explicitly-written deduction guide member, or from a constructor.
834 // getInstantiatedFromMemberTemplate() can only handle the former case, so we
835 // check the DeclContext kind.
837 clang::Decl::ClassTemplateSpecialization) {
838 auto OuterLevelArgs = SemaRef.getTemplateInstantiationArgs(
839 F, F->getLexicalDeclContext(),
840 /*Final=*/false, /*Innermost=*/std::nullopt,
841 /*RelativeToPrimary=*/true,
842 /*Pattern=*/nullptr,
843 /*ForConstraintInstantiation=*/true);
844 for (auto It : OuterLevelArgs)
845 ArgsForBuildingRC.addOuterTemplateArguments(It.Args);
846 }
847
848 ExprResult E = SemaRef.SubstExpr(RC, ArgsForBuildingRC);
849 if (E.isInvalid())
850 return nullptr;
851
852 auto Conjunction =
853 SemaRef.BuildBinOp(SemaRef.getCurScope(), SourceLocation{},
854 BinaryOperatorKind::BO_LAnd, E.get(), IsDeducible);
855 if (Conjunction.isInvalid())
856 return nullptr;
857 return Conjunction.getAs<Expr>();
858}
859// Build the is_deducible constraint for the alias deduction guides.
860// [over.match.class.deduct]p3.3:
861// ... and a constraint that is satisfied if and only if the arguments
862// of A are deducible (see below) from the return type.
863Expr *buildIsDeducibleConstraint(Sema &SemaRef,
865 QualType ReturnType,
866 SmallVector<NamedDecl *> TemplateParams) {
867 ASTContext &Context = SemaRef.Context;
868 // Constraint AST nodes must use uninstantiated depth.
869 if (auto *PrimaryTemplate =
870 AliasTemplate->getInstantiatedFromMemberTemplate();
871 PrimaryTemplate && TemplateParams.size() > 0) {
873
874 // Adjust the depth for TemplateParams.
875 unsigned AdjustDepth = PrimaryTemplate->getTemplateDepth();
876 SmallVector<TemplateArgument> TransformedTemplateArgs;
877 for (auto *TP : TemplateParams) {
878 // Rebuild any internal references to earlier parameters and reindex
879 // as we go.
881 Args.setKind(TemplateSubstitutionKind::Rewrite);
882 Args.addOuterTemplateArguments(TransformedTemplateArgs);
883 NamedDecl *NewParam = transformTemplateParameter(
884 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
885 /*NewIndex=*/TransformedTemplateArgs.size(),
886 getDepthAndIndex(TP).first + AdjustDepth);
887
888 TemplateArgument NewTemplateArgument =
889 Context.getInjectedTemplateArg(NewParam);
890 TransformedTemplateArgs.push_back(NewTemplateArgument);
891 }
892 // Transformed the ReturnType to restore the uninstantiated depth.
894 Args.setKind(TemplateSubstitutionKind::Rewrite);
895 Args.addOuterTemplateArguments(TransformedTemplateArgs);
896 ReturnType = SemaRef.SubstType(
897 ReturnType, Args, AliasTemplate->getLocation(),
899 };
900
901 SmallVector<TypeSourceInfo *> IsDeducibleTypeTraitArgs = {
904 TemplateName(AliasTemplate), /*DeducedType=*/QualType(),
905 /*IsDependent=*/true),
906 AliasTemplate->getLocation()), // template specialization type whose
907 // arguments will be deduced.
909 ReturnType, AliasTemplate->getLocation()), // type from which template
910 // arguments are deduced.
911 };
913 Context, Context.getLogicalOperationType(), AliasTemplate->getLocation(),
914 TypeTrait::BTT_IsDeducible, IsDeducibleTypeTraitArgs,
915 AliasTemplate->getLocation(), /*Value*/ false);
916}
917
918std::pair<TemplateDecl *, llvm::ArrayRef<TemplateArgument>>
919getRHSTemplateDeclAndArgs(Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate) {
920 // Unwrap the sugared ElaboratedType.
921 auto RhsType = AliasTemplate->getTemplatedDecl()
922 ->getUnderlyingType()
923 .getSingleStepDesugaredType(SemaRef.Context);
924 TemplateDecl *Template = nullptr;
925 llvm::ArrayRef<TemplateArgument> AliasRhsTemplateArgs;
926 if (const auto *TST = RhsType->getAs<TemplateSpecializationType>()) {
927 // Cases where the RHS of the alias is dependent. e.g.
928 // template<typename T>
929 // using AliasFoo1 = Foo<T>; // a class/type alias template specialization
930 Template = TST->getTemplateName().getAsTemplateDecl();
931 AliasRhsTemplateArgs = TST->template_arguments();
932 } else if (const auto *RT = RhsType->getAs<RecordType>()) {
933 // Cases where template arguments in the RHS of the alias are not
934 // dependent. e.g.
935 // using AliasFoo = Foo<bool>;
936 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
937 RT->getAsCXXRecordDecl())) {
938 Template = CTSD->getSpecializedTemplate();
939 AliasRhsTemplateArgs = CTSD->getTemplateArgs().asArray();
940 }
941 } else {
942 assert(false && "unhandled RHS type of the alias");
943 }
944 return {Template, AliasRhsTemplateArgs};
945}
946
947// Build deduction guides for a type alias template from the given underlying
948// deduction guide F.
950BuildDeductionGuideForTypeAlias(Sema &SemaRef,
954 Sema::InstantiatingTemplate BuildingDeductionGuides(
955 SemaRef, AliasTemplate->getLocation(), F,
957 if (BuildingDeductionGuides.isInvalid())
958 return nullptr;
959
960 auto &Context = SemaRef.Context;
961 auto [Template, AliasRhsTemplateArgs] =
962 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
963
964 auto RType = F->getTemplatedDecl()->getReturnType();
965 // The (trailing) return type of the deduction guide.
966 const TemplateSpecializationType *FReturnType =
968 if (const auto *InjectedCNT = RType->getAs<InjectedClassNameType>())
969 // implicitly-generated deduction guide.
970 FReturnType = InjectedCNT->getInjectedTST();
971 else if (const auto *ET = RType->getAs<ElaboratedType>())
972 // explicit deduction guide.
973 FReturnType = ET->getNamedType()->getAs<TemplateSpecializationType>();
974 assert(FReturnType && "expected to see a return type");
975 // Deduce template arguments of the deduction guide f from the RHS of
976 // the alias.
977 //
978 // C++ [over.match.class.deduct]p3: ...For each function or function
979 // template f in the guides of the template named by the
980 // simple-template-id of the defining-type-id, the template arguments
981 // of the return type of f are deduced from the defining-type-id of A
982 // according to the process in [temp.deduct.type] with the exception
983 // that deduction does not fail if not all template arguments are
984 // deduced.
985 //
986 //
987 // template<typename X, typename Y>
988 // f(X, Y) -> f<Y, X>;
989 //
990 // template<typename U>
991 // using alias = f<int, U>;
992 //
993 // The RHS of alias is f<int, U>, we deduced the template arguments of
994 // the return type of the deduction guide from it: Y->int, X->U
995 sema::TemplateDeductionInfo TDeduceInfo(Loc);
996 // Must initialize n elements, this is required by DeduceTemplateArguments.
999
1000 // FIXME: DeduceTemplateArguments stops immediately at the first
1001 // non-deducible template argument. However, this doesn't seem to casue
1002 // issues for practice cases, we probably need to extend it to continue
1003 // performing deduction for rest of arguments to align with the C++
1004 // standard.
1006 F->getTemplateParameters(), FReturnType->template_arguments(),
1007 AliasRhsTemplateArgs, TDeduceInfo, DeduceResults,
1008 /*NumberOfArgumentsMustMatch=*/false);
1009
1011 SmallVector<unsigned> NonDeducedTemplateParamsInFIndex;
1012 // !!NOTE: DeduceResults respects the sequence of template parameters of
1013 // the deduction guide f.
1014 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
1015 if (const auto &D = DeduceResults[Index]; !D.isNull()) // Deduced
1016 DeducedArgs.push_back(D);
1017 else
1018 NonDeducedTemplateParamsInFIndex.push_back(Index);
1019 }
1020 auto DeducedAliasTemplateParams =
1021 TemplateParamsReferencedInTemplateArgumentList(
1022 AliasTemplate->getTemplateParameters(), DeducedArgs);
1023 // All template arguments null by default.
1024 SmallVector<TemplateArgument> TemplateArgsForBuildingFPrime(
1025 F->getTemplateParameters()->size());
1026
1027 // Create a template parameter list for the synthesized deduction guide f'.
1028 //
1029 // C++ [over.match.class.deduct]p3.2:
1030 // If f is a function template, f' is a function template whose template
1031 // parameter list consists of all the template parameters of A
1032 // (including their default template arguments) that appear in the above
1033 // deductions or (recursively) in their default template arguments
1034 SmallVector<NamedDecl *> FPrimeTemplateParams;
1035 // Store template arguments that refer to the newly-created template
1036 // parameters, used for building `TemplateArgsForBuildingFPrime`.
1037 SmallVector<TemplateArgument, 16> TransformedDeducedAliasArgs(
1038 AliasTemplate->getTemplateParameters()->size());
1039
1040 for (unsigned AliasTemplateParamIdx : DeducedAliasTemplateParams) {
1041 auto *TP =
1042 AliasTemplate->getTemplateParameters()->getParam(AliasTemplateParamIdx);
1043 // Rebuild any internal references to earlier parameters and reindex as
1044 // we go.
1046 Args.setKind(TemplateSubstitutionKind::Rewrite);
1047 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
1048 NamedDecl *NewParam = transformTemplateParameter(
1049 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
1050 /*NewIndex=*/FPrimeTemplateParams.size(), getDepthAndIndex(TP).first);
1051 FPrimeTemplateParams.push_back(NewParam);
1052
1053 TemplateArgument NewTemplateArgument =
1054 Context.getInjectedTemplateArg(NewParam);
1055 TransformedDeducedAliasArgs[AliasTemplateParamIdx] = NewTemplateArgument;
1056 }
1057 unsigned FirstUndeducedParamIdx = FPrimeTemplateParams.size();
1058 // ...followed by the template parameters of f that were not deduced
1059 // (including their default template arguments)
1060 for (unsigned FTemplateParamIdx : NonDeducedTemplateParamsInFIndex) {
1061 auto *TP = F->getTemplateParameters()->getParam(FTemplateParamIdx);
1063 Args.setKind(TemplateSubstitutionKind::Rewrite);
1064 // We take a shortcut here, it is ok to reuse the
1065 // TemplateArgsForBuildingFPrime.
1066 Args.addOuterTemplateArguments(TemplateArgsForBuildingFPrime);
1067 NamedDecl *NewParam = transformTemplateParameter(
1068 SemaRef, F->getDeclContext(), TP, Args, FPrimeTemplateParams.size(),
1069 getDepthAndIndex(TP).first);
1070 FPrimeTemplateParams.push_back(NewParam);
1071
1072 assert(TemplateArgsForBuildingFPrime[FTemplateParamIdx].isNull() &&
1073 "The argument must be null before setting");
1074 TemplateArgsForBuildingFPrime[FTemplateParamIdx] =
1075 Context.getInjectedTemplateArg(NewParam);
1076 }
1077
1078 // To form a deduction guide f' from f, we leverage clang's instantiation
1079 // mechanism, we construct a template argument list where the template
1080 // arguments refer to the newly-created template parameters of f', and
1081 // then apply instantiation on this template argument list to instantiate
1082 // f, this ensures all template parameter occurrences are updated
1083 // correctly.
1084 //
1085 // The template argument list is formed from the `DeducedArgs`, two parts:
1086 // 1) appeared template parameters of alias: transfrom the deduced
1087 // template argument;
1088 // 2) non-deduced template parameters of f: rebuild a
1089 // template argument;
1090 //
1091 // 2) has been built already (when rebuilding the new template
1092 // parameters), we now perform 1).
1094 Args.setKind(TemplateSubstitutionKind::Rewrite);
1095 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
1096 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
1097 const auto &D = DeduceResults[Index];
1098 if (D.isNull()) {
1099 // 2): Non-deduced template parameter has been built already.
1100 assert(!TemplateArgsForBuildingFPrime[Index].isNull() &&
1101 "template arguments for non-deduced template parameters should "
1102 "be been set!");
1103 continue;
1104 }
1105 TemplateArgumentLoc Input =
1107 TemplateArgumentLoc Output;
1108 if (!SemaRef.SubstTemplateArgument(Input, Args, Output)) {
1109 assert(TemplateArgsForBuildingFPrime[Index].isNull() &&
1110 "InstantiatedArgs must be null before setting");
1111 TemplateArgsForBuildingFPrime[Index] = Output.getArgument();
1112 }
1113 }
1114
1115 auto *TemplateArgListForBuildingFPrime =
1116 TemplateArgumentList::CreateCopy(Context, TemplateArgsForBuildingFPrime);
1117 // Form the f' by substituting the template arguments into f.
1118 if (auto *FPrime = SemaRef.InstantiateFunctionDeclaration(
1119 F, TemplateArgListForBuildingFPrime, AliasTemplate->getLocation(),
1121 auto *GG = cast<CXXDeductionGuideDecl>(FPrime);
1122
1123 Expr *IsDeducible = buildIsDeducibleConstraint(
1124 SemaRef, AliasTemplate, FPrime->getReturnType(), FPrimeTemplateParams);
1125 Expr *RequiresClause =
1126 buildAssociatedConstraints(SemaRef, F, AliasTemplate, DeduceResults,
1127 FirstUndeducedParamIdx, IsDeducible);
1128
1129 auto *FPrimeTemplateParamList = TemplateParameterList::Create(
1130 Context, AliasTemplate->getTemplateParameters()->getTemplateLoc(),
1131 AliasTemplate->getTemplateParameters()->getLAngleLoc(),
1132 FPrimeTemplateParams,
1133 AliasTemplate->getTemplateParameters()->getRAngleLoc(),
1134 /*RequiresClause=*/RequiresClause);
1135 auto *Result = cast<FunctionTemplateDecl>(buildDeductionGuide(
1136 SemaRef, AliasTemplate, FPrimeTemplateParamList,
1137 GG->getCorrespondingConstructor(), GG->getExplicitSpecifier(),
1138 GG->getTypeSourceInfo(), AliasTemplate->getBeginLoc(),
1139 AliasTemplate->getLocation(), AliasTemplate->getEndLoc(),
1140 F->isImplicit()));
1141 cast<CXXDeductionGuideDecl>(Result->getTemplatedDecl())
1142 ->setDeductionCandidateKind(GG->getDeductionCandidateKind());
1143 return Result;
1144 }
1145 return nullptr;
1146}
1147
1148void DeclareImplicitDeductionGuidesForTypeAlias(
1150 if (AliasTemplate->isInvalidDecl())
1151 return;
1152 auto &Context = SemaRef.Context;
1153 // FIXME: if there is an explicit deduction guide after the first use of the
1154 // type alias usage, we will not cover this explicit deduction guide. fix this
1155 // case.
1156 if (hasDeclaredDeductionGuides(
1158 AliasTemplate->getDeclContext()))
1159 return;
1160 auto [Template, AliasRhsTemplateArgs] =
1161 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
1162 if (!Template)
1163 return;
1164 DeclarationNameInfo NameInfo(
1165 Context.DeclarationNames.getCXXDeductionGuideName(Template), Loc);
1166 LookupResult Guides(SemaRef, NameInfo, clang::Sema::LookupOrdinaryName);
1167 SemaRef.LookupQualifiedName(Guides, Template->getDeclContext());
1168 Guides.suppressDiagnostics();
1169
1170 for (auto *G : Guides) {
1171 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(G)) {
1172 // The deduction guide is a non-template function decl, we just clone it.
1173 auto *FunctionType =
1174 SemaRef.Context.getTrivialTypeSourceInfo(DG->getType());
1176 FunctionType->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1177
1178 // Clone the parameters.
1179 for (unsigned I = 0, N = DG->getNumParams(); I != N; ++I) {
1180 const auto *P = DG->getParamDecl(I);
1181 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(P->getType());
1182 ParmVarDecl *NewParam = ParmVarDecl::Create(
1183 SemaRef.Context, G->getDeclContext(),
1184 DG->getParamDecl(I)->getBeginLoc(), P->getLocation(), nullptr,
1185 TSI->getType(), TSI, SC_None, nullptr);
1186 NewParam->setScopeInfo(0, I);
1187 FPTL.setParam(I, NewParam);
1188 }
1189 auto *Transformed = cast<FunctionDecl>(buildDeductionGuide(
1190 SemaRef, AliasTemplate, /*TemplateParams=*/nullptr,
1191 /*Constructor=*/nullptr, DG->getExplicitSpecifier(), FunctionType,
1192 AliasTemplate->getBeginLoc(), AliasTemplate->getLocation(),
1193 AliasTemplate->getEndLoc(), DG->isImplicit()));
1194
1195 // FIXME: Here the synthesized deduction guide is not a templated
1196 // function. Per [dcl.decl]p4, the requires-clause shall be present only
1197 // if the declarator declares a templated function, a bug in standard?
1198 auto *Constraint = buildIsDeducibleConstraint(
1199 SemaRef, AliasTemplate, Transformed->getReturnType(), {});
1200 if (auto *RC = DG->getTrailingRequiresClause()) {
1201 auto Conjunction =
1202 SemaRef.BuildBinOp(SemaRef.getCurScope(), SourceLocation{},
1203 BinaryOperatorKind::BO_LAnd, RC, Constraint);
1204 if (!Conjunction.isInvalid())
1205 Constraint = Conjunction.getAs<Expr>();
1206 }
1207 Transformed->setTrailingRequiresClause(Constraint);
1208 }
1209 FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(G);
1210 if (!F)
1211 continue;
1212 // The **aggregate** deduction guides are handled in a different code path
1213 // (DeclareAggregateDeductionGuideFromInitList), which involves the tricky
1214 // cache.
1215 if (cast<CXXDeductionGuideDecl>(F->getTemplatedDecl())
1216 ->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
1217 continue;
1218
1219 BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate, F, Loc);
1220 }
1221}
1222
1223// Build an aggregate deduction guide for a type alias template.
1224FunctionTemplateDecl *DeclareAggregateDeductionGuideForTypeAlias(
1227 TemplateDecl *RHSTemplate =
1228 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate).first;
1229 if (!RHSTemplate)
1230 return nullptr;
1231
1233 llvm::SmallVector<QualType> NewParamTypes;
1234 ExtractTypeForDeductionGuide TypeAliasTransformer(SemaRef, TypedefDecls);
1235 for (QualType P : ParamTypes) {
1236 QualType Type = TypeAliasTransformer.TransformType(P);
1237 if (Type.isNull())
1238 return nullptr;
1239 NewParamTypes.push_back(Type);
1240 }
1241
1242 auto *RHSDeductionGuide = SemaRef.DeclareAggregateDeductionGuideFromInitList(
1243 RHSTemplate, NewParamTypes, Loc);
1244 if (!RHSDeductionGuide)
1245 return nullptr;
1246
1247 for (TypedefNameDecl *TD : TypedefDecls)
1248 TD->setDeclContext(RHSDeductionGuide->getTemplatedDecl());
1249
1250 return BuildDeductionGuideForTypeAlias(SemaRef, AliasTemplate,
1251 RHSDeductionGuide, Loc);
1252}
1253
1254} // namespace
1255
1257 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
1259 llvm::FoldingSetNodeID ID;
1260 ID.AddPointer(Template);
1261 for (auto &T : ParamTypes)
1262 T.getCanonicalType().Profile(ID);
1263 unsigned Hash = ID.ComputeHash();
1264
1265 auto Found = AggregateDeductionCandidates.find(Hash);
1266 if (Found != AggregateDeductionCandidates.end()) {
1267 CXXDeductionGuideDecl *GD = Found->getSecond();
1268 return GD->getDescribedFunctionTemplate();
1269 }
1270
1271 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
1272 if (auto *FTD = DeclareAggregateDeductionGuideForTypeAlias(
1273 *this, AliasTemplate, ParamTypes, Loc)) {
1274 auto *GD = cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1275 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
1277 return FTD;
1278 }
1279 }
1280
1281 if (CXXRecordDecl *DefRecord =
1282 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
1283 if (TemplateDecl *DescribedTemplate =
1284 DefRecord->getDescribedClassTemplate())
1285 Template = DescribedTemplate;
1286 }
1287
1288 DeclContext *DC = Template->getDeclContext();
1289 if (DC->isDependentContext())
1290 return nullptr;
1291
1292 ConvertConstructorToDeductionGuideTransform Transform(
1293 *this, cast<ClassTemplateDecl>(Template));
1294 if (!isCompleteType(Loc, Transform.DeducedType))
1295 return nullptr;
1296
1297 // In case we were expanding a pack when we attempted to declare deduction
1298 // guides, turn off pack expansion for everything we're about to do.
1299 ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
1300 /*NewSubstitutionIndex=*/-1);
1301 // Create a template instantiation record to track the "instantiation" of
1302 // constructors into deduction guides.
1303 InstantiatingTemplate BuildingDeductionGuides(
1304 *this, Loc, Template,
1306 if (BuildingDeductionGuides.isInvalid())
1307 return nullptr;
1308
1309 ClassTemplateDecl *Pattern =
1310 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
1311 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
1312
1313 auto *FTD = cast<FunctionTemplateDecl>(
1314 Transform.buildSimpleDeductionGuide(ParamTypes));
1315 SavedContext.pop();
1316 auto *GD = cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1317 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
1319 return FTD;
1320}
1321
1324 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Template)) {
1325 DeclareImplicitDeductionGuidesForTypeAlias(*this, AliasTemplate, Loc);
1326 return;
1327 }
1328 if (CXXRecordDecl *DefRecord =
1329 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
1330 if (TemplateDecl *DescribedTemplate =
1331 DefRecord->getDescribedClassTemplate())
1332 Template = DescribedTemplate;
1333 }
1334
1335 DeclContext *DC = Template->getDeclContext();
1336 if (DC->isDependentContext())
1337 return;
1338
1339 ConvertConstructorToDeductionGuideTransform Transform(
1340 *this, cast<ClassTemplateDecl>(Template));
1341 if (!isCompleteType(Loc, Transform.DeducedType))
1342 return;
1343
1344 if (hasDeclaredDeductionGuides(Transform.DeductionGuideName, DC))
1345 return;
1346
1347 // In case we were expanding a pack when we attempted to declare deduction
1348 // guides, turn off pack expansion for everything we're about to do.
1349 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1350 // Create a template instantiation record to track the "instantiation" of
1351 // constructors into deduction guides.
1352 InstantiatingTemplate BuildingDeductionGuides(
1353 *this, Loc, Template,
1355 if (BuildingDeductionGuides.isInvalid())
1356 return;
1357
1358 // Convert declared constructors into deduction guide templates.
1359 // FIXME: Skip constructors for which deduction must necessarily fail (those
1360 // for which some class template parameter without a default argument never
1361 // appears in a deduced context).
1362 ClassTemplateDecl *Pattern =
1363 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
1364 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
1365 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
1366 bool AddedAny = false;
1367 for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) {
1368 D = D->getUnderlyingDecl();
1369 if (D->isInvalidDecl() || D->isImplicit())
1370 continue;
1371
1372 D = cast<NamedDecl>(D->getCanonicalDecl());
1373
1374 // Within C++20 modules, we may have multiple same constructors in
1375 // multiple same RecordDecls. And it doesn't make sense to create
1376 // duplicated deduction guides for the duplicated constructors.
1377 if (ProcessedCtors.count(D))
1378 continue;
1379
1380 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1381 auto *CD =
1382 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1383 // Class-scope explicit specializations (MS extension) do not result in
1384 // deduction guides.
1385 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1386 continue;
1387
1388 // Cannot make a deduction guide when unparsed arguments are present.
1389 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
1390 return !P || P->hasUnparsedDefaultArg();
1391 }))
1392 continue;
1393
1394 ProcessedCtors.insert(D);
1395 Transform.transformConstructor(FTD, CD);
1396 AddedAny = true;
1397 }
1398
1399 // C++17 [over.match.class.deduct]
1400 // -- If C is not defined or does not declare any constructors, an
1401 // additional function template derived as above from a hypothetical
1402 // constructor C().
1403 if (!AddedAny)
1404 Transform.buildSimpleDeductionGuide({});
1405
1406 // -- An additional function template derived as above from a hypothetical
1407 // constructor C(C), called the copy deduction candidate.
1408 cast<CXXDeductionGuideDecl>(
1409 cast<FunctionTemplateDecl>(
1410 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1411 ->getTemplatedDecl())
1412 ->setDeductionCandidateKind(DeductionCandidate::Copy);
1413
1414 SavedContext.pop();
1415}
Defines the clang::ASTContext interface.
StringRef P
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
SourceLocation Loc
Definition: SemaObjC.cpp:759
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.
Defines enumerations for the type traits support.
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:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2132
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
PtrTy get() const
Definition: Ownership.h:170
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
ExplicitSpecifier getExplicitSpecifier()
Definition: DeclCXX.h:2624
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1967
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2250
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
bool isRecord() const
Definition: DeclBase.h:2169
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2082
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1370
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:293
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:355
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
The name of a declaration.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:777
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6522
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6943
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1912
This represents one expression.
Definition: Expr.h:110
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4052
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3867
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5479
Declaration of a template function.
Definition: DeclTemplate.h:959
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:1531
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1483
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1479
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1495
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1538
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1522
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1503
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1487
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1517
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1475
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1491
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1499
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6793
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void InstantiatedLocal(const Decl *D, Decl *Inst)
Represents the results of name lookup.
Definition: Lookup.h:46
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:257
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition: Template.h:210
void setKind(TemplateSubstitutionKind K)
Definition: Template.h:109
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2992
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
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:2922
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3023
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1775
A (possibly-)qualified type.
Definition: Type.h:929
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:859
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:13212
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
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:12643
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:732
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8990
FunctionTemplateDecl * DeclareAggregateDeductionGuideFromInitList(TemplateDecl *Template, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc)
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...
ASTContext & Context
Definition: Sema.h:909
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2632
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ASTContext & getASTContext() const
Definition: Sema.h:532
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.
TemplateParameterList * GetTemplateParameterList(TemplateDecl *TD)
Returns the template parameter list with all default template argument information.
llvm::DenseMap< unsigned, CXXDeductionGuideDecl * > AggregateDeductionCandidates
Definition: Sema.h:8672
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.
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14957
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15345
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
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.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
Definition: DeclTemplate.h:431
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:183
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6661
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6729
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
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.
const TypeConstraint * getTypeConstraint() const
Returns the type constraint associated with this template parameter (if any).
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isExpandedParameterPack() const
Whether this parameter is a template type parameter pack that has a known list of different type-cons...
bool isParameterPack() const
Returns whether this is a parameter pack.
unsigned getNumExpansionParameters() const
Retrieves the number of parameters in an expanded parameter pack.
unsigned getIndex() const
Definition: Type.h:6343
unsigned getDepth() const
Definition: Type.h:6342
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
QualType RebuildTemplateSpecializationType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &Args)
Build a new template specialization type.
QualType TransformType(QualType T)
Transforms the given type into another type.
static TypeAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5576
Declaration of an alias template.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3398
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
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
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2715
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7902
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7913
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
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:1876
The base class of the type hierarchy.
Definition: Type.h:1828
bool isRValueReferenceType() const
Definition: Type.h:8212
bool isArrayType() const
Definition: Type.h:8258
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isLValueReferenceType() const
Definition: Type.h:8208
bool isFunctionType() const
Definition: Type.h:8182
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5525
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3413
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3463
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
TypedefNameDecl * getTypedefNameDecl() const
Definition: TypeLoc.h:695
QualType getType() const
Definition: Decl.h:682
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
Provides information about an attempted template argument deduction, whose success or failure was des...
The JSON file list parser is used to communicate input to InstallAPI.
@ Rewrite
We are substituting template parameters for (typically) other template parameters in order to rewrite...
@ SC_None
Definition: Specifiers.h:250
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
@ AS_public
Definition: Specifiers.h:124
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
Extra information about a function prototype.
Definition: Type.h:5187
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12767
A stack object to be created when performing template instantiation.
Definition: Sema.h:12845