clang 23.0.0git
SemaTemplateDeduction.cpp
Go to the documentation of this file.
1//===- SemaTemplateDeduction.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 C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TreeTransform.h"
14#include "TypeLocBuilder.h"
16#include "clang/AST/ASTLambda.h"
17#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"
35#include "clang/Basic/LLVM.h"
43#include "clang/Sema/Sema.h"
44#include "clang/Sema/Template.h"
46#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/APSInt.h"
48#include "llvm/ADT/ArrayRef.h"
49#include "llvm/ADT/DenseMap.h"
50#include "llvm/ADT/FoldingSet.h"
51#include "llvm/ADT/SmallBitVector.h"
52#include "llvm/ADT/SmallPtrSet.h"
53#include "llvm/ADT/SmallVector.h"
54#include "llvm/Support/Casting.h"
55#include "llvm/Support/Compiler.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/SaveAndRestore.h"
58#include <algorithm>
59#include <cassert>
60#include <optional>
61#include <tuple>
62#include <type_traits>
63#include <utility>
64
65namespace clang {
66
67 /// Various flags that control template argument deduction.
68 ///
69 /// These flags can be bitwise-OR'd together.
71 /// No template argument deduction flags, which indicates the
72 /// strictest results for template argument deduction (as used for, e.g.,
73 /// matching class template partial specializations).
75
76 /// Within template argument deduction from a function call, we are
77 /// matching with a parameter type for which the original parameter was
78 /// a reference.
80
81 /// Within template argument deduction from a function call, we
82 /// are matching in a case where we ignore cv-qualifiers.
84
85 /// Within template argument deduction from a function call,
86 /// we are matching in a case where we can perform template argument
87 /// deduction from a template-id of a derived class of the argument type.
89
90 /// Allow non-dependent types to differ, e.g., when performing
91 /// template argument deduction from a function call where conversions
92 /// may apply.
94
95 /// Whether we are performing template argument deduction for
96 /// parameters and arguments in a top-level template argument
98
99 /// Within template argument deduction from overload resolution per
100 /// C++ [over.over] allow matching function types that are compatible in
101 /// terms of noreturn and default calling convention adjustments, or
102 /// similarly matching a declared template specialization against a
103 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
104 /// deduction where the parameter is a function type that can be converted
105 /// to the argument type.
107
108 /// Within template argument deduction for a conversion function, we are
109 /// matching with an argument type for which the original argument was
110 /// a reference.
112 };
113}
114
115using namespace clang;
116using namespace sema;
117
118/// The kind of PartialOrdering we're performing template argument deduction
119/// for (C++11 [temp.deduct.partial]).
121
123 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
126 PartialOrderingKind POK, bool DeducedFromArrayBound,
127 bool *HasDeducedAnyParam);
128
129/// What directions packs are allowed to match non-packs.
131
138 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
139 PackFold PackFold, bool *HasDeducedAnyParam);
140
143 bool OnlyDeduced, unsigned Depth,
144 llvm::SmallBitVector &Used);
145
147 bool OnlyDeduced, unsigned Level,
148 llvm::SmallBitVector &Deduced);
149
150static const Expr *unwrapExpressionForDeduction(const Expr *E) {
151 // If we are within an alias template, the expression may have undergone
152 // any number of parameter substitutions already.
153 while (true) {
154 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
155 E = IC->getSubExpr();
156 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
157 E = CE->getSubExpr();
158 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
159 E = Subst->getReplacement();
160 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
161 // Look through implicit copy construction from an lvalue of the same type.
162 if (CCE->getParenOrBraceRange().isValid())
163 break;
164 // Note, there could be default arguments.
165 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
166 E = CCE->getArg(0);
167 } else
168 break;
169 }
170 return E;
171}
172
174public:
175 NonTypeOrVarTemplateParmDecl(const NamedDecl *Template) : Template(Template) {
176 assert(
177 !Template || isa<NonTypeTemplateParmDecl>(Template) ||
179 (cast<TemplateTemplateParmDecl>(Template)->templateParameterKind() ==
181 cast<TemplateTemplateParmDecl>(Template)->templateParameterKind() ==
183 }
184
186 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
187 return NTTP->getType();
191 }
192
193 unsigned getDepth() const {
194 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
195 return NTTP->getDepth();
196 return getTemplate()->getDepth();
197 }
198
199 unsigned getIndex() const {
200 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
201 return NTTP->getIndex();
202 return getTemplate()->getIndex();
203 }
204
206 return cast<TemplateTemplateParmDecl>(Template);
207 }
208
210 return cast<NonTypeTemplateParmDecl>(Template);
211 }
212
214 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
215 return const_cast<NonTypeTemplateParmDecl *>(NTTP);
216 return const_cast<TemplateTemplateParmDecl *>(getTemplate());
217 }
218
220 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
221 return NTTP->isExpandedParameterPack();
223 }
224
226 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
227 return NTTP->getLocation();
228 return getTemplate()->getLocation();
229 }
230
231 operator bool() const { return Template; }
232
233private:
234 const NamedDecl *Template;
235};
236
237/// If the given expression is of a form that permits the deduction
238/// of a non-type template parameter, return the declaration of that
239/// non-type template parameter.
241getDeducedNTTParameterFromExpr(const Expr *E, unsigned Depth) {
242 // If we are within an alias template, the expression may have undergone
243 // any number of parameter substitutions already.
245 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
246 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
247 if (NTTP->getDepth() == Depth)
248 return NTTP;
249
250 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E);
251 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
252 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
253
254 if (TTP->getDepth() == Depth)
255 return TTP;
256 }
257 }
258 return nullptr;
259}
260
265
266/// Determine whether two declaration pointers refer to the same
267/// declaration.
268static bool isSameDeclaration(Decl *X, Decl *Y) {
269 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
270 X = NX->getUnderlyingDecl();
271 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
272 Y = NY->getUnderlyingDecl();
273
274 return X->getCanonicalDecl() == Y->getCanonicalDecl();
275}
276
277/// Verify that the given, deduced template arguments are compatible.
278///
279/// \returns The deduced template argument, or a NULL template argument if
280/// the deduced template arguments were incompatible.
285 bool AggregateCandidateDeduction = false) {
286 // We have no deduction for one or both of the arguments; they're compatible.
287 if (X.isNull())
288 return Y;
289 if (Y.isNull())
290 return X;
291
292 // If we have two non-type template argument values deduced for the same
293 // parameter, they must both match the type of the parameter, and thus must
294 // match each other's type. As we're only keeping one of them, we must check
295 // for that now. The exception is that if either was deduced from an array
296 // bound, the type is permitted to differ.
297 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
298 QualType XType = X.getNonTypeTemplateArgumentType();
299 if (!XType.isNull()) {
301 if (YType.isNull() || !Context.hasSameType(XType, YType))
303 }
304 }
305
306 switch (X.getKind()) {
308 llvm_unreachable("Non-deduced template arguments handled above");
309
311 // If two template type arguments have the same type, they're compatible.
312 QualType TX = X.getAsType(), TY = Y.getAsType();
313 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
314 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
315 X.wasDeducedFromArrayBound() ||
317
318 // If one of the two arguments was deduced from an array bound, the other
319 // supersedes it.
320 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
321 return X.wasDeducedFromArrayBound() ? Y : X;
322
323 // The arguments are not compatible.
325 }
326
328 // If we deduced a constant in one case and either a dependent expression or
329 // declaration in another case, keep the integral constant.
330 // If both are integral constants with the same value, keep that value.
334 llvm::APSInt::isSameValue(X.getAsIntegral(), Y.getAsIntegral())))
335 return X.wasDeducedFromArrayBound() ? Y : X;
336
337 // All other combinations are incompatible.
339
341 // If we deduced a value and a dependent expression, keep the value.
344 X.structurallyEquals(Y)))
345 return X;
346
347 // All other combinations are incompatible.
349
352 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
353 return X;
354
355 // All other combinations are incompatible.
357
360 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
362 return X;
363
364 // All other combinations are incompatible.
366
369 return checkDeducedTemplateArguments(Context, Y, X);
370
371 // Compare the expressions for equality
372 llvm::FoldingSetNodeID ID1, ID2;
373 X.getAsExpr()->Profile(ID1, Context, true);
374 Y.getAsExpr()->Profile(ID2, Context, true);
375 if (ID1 == ID2)
376 return X.wasDeducedFromArrayBound() ? Y : X;
377
378 // Differing dependent expressions are incompatible.
380 }
381
383 assert(!X.wasDeducedFromArrayBound());
384
385 // If we deduced a declaration and a dependent expression, keep the
386 // declaration.
388 return X;
389
390 // If we deduced a declaration and an integral constant, keep the
391 // integral constant and whichever type did not come from an array
392 // bound.
395 return TemplateArgument(Context, Y.getAsIntegral(),
396 X.getParamTypeForDecl());
397 return Y;
398 }
399
400 // If we deduced two declarations, make sure that they refer to the
401 // same declaration.
403 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
404 return X;
405
406 // All other combinations are incompatible.
408
410 // If we deduced a null pointer and a dependent expression, keep the
411 // null pointer.
413 return TemplateArgument(Context.getCommonSugaredType(
414 X.getNullPtrType(), Y.getAsExpr()->getType()),
415 true);
416
417 // If we deduced a null pointer and an integral constant, keep the
418 // integral constant.
420 return Y;
421
422 // If we deduced two null pointers, they are the same.
424 return TemplateArgument(
425 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
426 true);
427
428 // All other combinations are incompatible.
430
432 if (Y.getKind() != TemplateArgument::Pack ||
433 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
435
438 XA = X.pack_begin(),
439 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
440 XA != XAEnd; ++XA) {
441 if (YA != YAEnd) {
443 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
445 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
447 NewPack.push_back(Merged);
448 ++YA;
449 } else {
450 NewPack.push_back(*XA);
451 }
452 }
453
455 TemplateArgument::CreatePackCopy(Context, NewPack),
456 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
457 }
458 }
459
460 llvm_unreachable("Invalid TemplateArgument Kind!");
461}
462
463/// Deduce the value of the given non-type template parameter
464/// as the given deduced template argument. All non-type template parameter
465/// deduction is funneled through here.
469 const DeducedTemplateArgument &NewDeduced,
470 QualType ValueType, TemplateDeductionInfo &Info,
471 bool PartialOrdering,
473 bool *HasDeducedAnyParam) {
474 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
475 "deducing non-type template argument with wrong depth");
476
478 S.Context, Deduced[NTTP.getIndex()], NewDeduced);
479 if (Result.isNull()) {
480 Info.Param = NTTP.asTemplateParam();
481 Info.FirstArg = Deduced[NTTP.getIndex()];
482 Info.SecondArg = NewDeduced;
484 }
485 Deduced[NTTP.getIndex()] = Result;
486 if (!S.getLangOpts().CPlusPlus17 && !PartialOrdering)
488
489 if (NTTP.isExpandedParameterPack())
490 // FIXME: We may still need to deduce parts of the type here! But we
491 // don't have any way to find which slice of the type to use, and the
492 // type stored on the NTTP itself is nonsense. Perhaps the type of an
493 // expanded NTTP should be a pack expansion type?
495
496 // Get the type of the parameter for deduction. If it's a (dependent) array
497 // or function type, we will not have decayed it yet, so do that now.
498 QualType ParamType = S.Context.getAdjustedParameterType(NTTP.getType());
499 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
500 ParamType = Expansion->getPattern();
501
502 // FIXME: It's not clear how deduction of a parameter of reference
503 // type from an argument (of non-reference type) should be performed.
504 // For now, we just make the argument have same reference type as the
505 // parameter.
506 if (ParamType->isReferenceType() && !ValueType->isReferenceType()) {
507 if (ParamType->isRValueReferenceType())
508 ValueType = S.Context.getRValueReferenceType(ValueType);
509 else
510 ValueType = S.Context.getLValueReferenceType(ValueType);
511 }
512
514 S, TemplateParams, ParamType, ValueType, Info, Deduced,
518 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
519}
520
521/// Deduce the value of the given non-type template parameter
522/// from the given integral constant.
524 Sema &S, TemplateParameterList *TemplateParams,
525 NonTypeOrVarTemplateParmDecl NTTP, const llvm::APSInt &Value,
526 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
528 bool *HasDeducedAnyParam) {
530 S, TemplateParams, NTTP,
532 DeducedFromArrayBound),
533 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
534}
535
536/// Deduce the value of the given non-type template parameter
537/// from the given null pointer template argument type.
541 QualType NullPtrType, TemplateDeductionInfo &Info,
542 bool PartialOrdering,
544 bool *HasDeducedAnyParam) {
547 NTTP.getLocation()),
548 NullPtrType,
549 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
550 : CK_NullToPointer)
551 .get();
553 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
554 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
555}
556
557/// Deduce the value of the given non-type template parameter
558/// from the given type- or value-dependent expression.
559///
560/// \returns true if deduction succeeded, false otherwise.
566 bool *HasDeducedAnyParam) {
568 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
569 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
570}
571
572/// Deduce the value of the given non-type template parameter
573/// from the given declaration.
574///
575/// \returns true if deduction succeeded, false otherwise.
580 bool PartialOrdering,
582 bool *HasDeducedAnyParam) {
583 TemplateArgument New(D, T);
585 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
586 PartialOrdering, Deduced, HasDeducedAnyParam);
587}
588
590 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
594 bool *HasDeducedAnyParam) {
595 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
596 if (!ParamDecl) {
597 // The parameter type is dependent and is not a template template parameter,
598 // so there is nothing that we can deduce.
600 }
601
602 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
603 // If we're not deducing at this depth, there's nothing to deduce.
604 if (TempParam->getDepth() != Info.getDeducedDepth())
606
607 ArrayRef<NamedDecl *> Params =
608 ParamDecl->getTemplateParameters()->asArray();
609 unsigned StartPos = 0;
610 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
611 I < E; ++I) {
612 if (Params[I]->isParameterPack()) {
613 StartPos = DefaultArguments.size();
614 break;
615 }
616 StartPos = I + 1;
617 }
618
619 // Provisional resolution for CWG2398: If Arg names a template
620 // specialization, then we deduce a synthesized template name
621 // based on A, but using the TS's extra arguments, relative to P, as
622 // defaults.
623 DeducedTemplateArgument NewDeduced =
626 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
627 : Arg;
628
630 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
631 if (Result.isNull()) {
632 Info.Param = TempParam;
633 Info.FirstArg = Deduced[TempParam->getIndex()];
634 Info.SecondArg = NewDeduced;
636 }
637
638 Deduced[TempParam->getIndex()] = Result;
639 if (HasDeducedAnyParam)
640 *HasDeducedAnyParam = true;
642 }
643
644 // Verify that the two template names are equivalent.
646 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
648
649 // Mismatch of non-dependent template parameter to argument.
650 Info.FirstArg = TemplateArgument(Param);
651 Info.SecondArg = TemplateArgument(Arg);
653}
654
655/// Deduce the template arguments by comparing the template parameter
656/// type (which is a template-id) with the template argument type.
657///
658/// \param S the Sema
659///
660/// \param TemplateParams the template parameters that we are deducing
661///
662/// \param P the parameter type
663///
664/// \param A the argument type
665///
666/// \param Info information about the template argument deduction itself
667///
668/// \param Deduced the deduced template arguments
669///
670/// \returns the result of template argument deduction so far. Note that a
671/// "success" result means that template argument deduction has not yet failed,
672/// but it may still fail, later, for other reasons.
673
674static const TemplateSpecializationType *getLastTemplateSpecType(QualType QT) {
675 const TemplateSpecializationType *LastTST = nullptr;
676 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
677 const TemplateSpecializationType *TST =
678 T->getAs<TemplateSpecializationType>();
679 if (!TST)
680 return LastTST;
681 if (!TST->isSugared())
682 return TST;
683 LastTST = TST;
684 T = TST->desugar().getTypePtr();
685 }
686}
687
690 const QualType P, QualType A,
693 bool *HasDeducedAnyParam) {
694 TemplateName TNP;
697 const TemplateSpecializationType *TP = ::getLastTemplateSpecType(P);
698 TNP = TP->getTemplateName();
699
700 // No deduction for specializations of dependent template names.
703
704 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
705 // arguments.
706 PResolved =
707 TP->castAsCanonical<TemplateSpecializationType>()->template_arguments();
708 } else {
709 const auto *TT = P->castAs<InjectedClassNameType>();
710 TNP = TT->getTemplateName(S.Context);
711 PResolved = TT->getTemplateArgs(S.Context);
712 }
713
714 // If the parameter is an alias template, there is nothing to deduce.
715 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
717 // Pack-producing templates can only be matched after substitution.
720
721 // Check whether the template argument is a dependent template-id.
723 const TemplateSpecializationType *SA = ::getLastTemplateSpecType(A);
724 TemplateName TNA = SA->getTemplateName();
725
726 // If the argument is an alias template, there is nothing to deduce.
727 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
729
730 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
731 // arguments.
733 SA->getCanonicalTypeInternal()
734 ->castAs<TemplateSpecializationType>()
735 ->template_arguments();
736
737 // Perform template argument deduction for the template name.
738 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
739 /*DefaultArguments=*/AResolved,
741 HasDeducedAnyParam);
743 return Result;
744
745 // Perform template argument deduction on each template
746 // argument. Ignore any missing/extra arguments, since they could be
747 // filled in by default arguments.
749 S, TemplateParams, PResolved, AResolved, Info, Deduced,
750 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
751 PackFold::ParameterToArgument, HasDeducedAnyParam);
752 }
753
754 // If the argument type is a class template specialization, we
755 // perform template argument deduction using its template
756 // arguments.
757 const auto *TA = A->getAs<TagType>();
758 TemplateName TNA;
759 if (TA) {
760 // FIXME: Can't use the template arguments from this TST, as they are not
761 // resolved.
762 if (const auto *TST = A->getAsNonAliasTemplateSpecializationType())
763 TNA = TST->getTemplateName();
764 else
765 TNA = TA->getTemplateName(S.Context);
766 }
767 if (TNA.isNull()) {
768 Info.FirstArg = TemplateArgument(P);
769 Info.SecondArg = TemplateArgument(A);
771 }
772
773 ArrayRef<TemplateArgument> AResolved = TA->getTemplateArgs(S.Context);
774 // Perform template argument deduction for the template name.
775 if (auto Result =
776 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
777 /*DefaultArguments=*/AResolved,
778 PartialOrdering, Deduced, HasDeducedAnyParam);
780 return Result;
781
782 // Perform template argument deduction for the template arguments.
784 S, TemplateParams, PResolved, AResolved, Info, Deduced,
785 /*NumberOfArgumentsMustMatch=*/true, PartialOrdering,
786 PackFold::ParameterToArgument, HasDeducedAnyParam);
787}
788
790 assert(T->isCanonicalUnqualified());
791
792 switch (T->getTypeClass()) {
793 case Type::TypeOfExpr:
794 case Type::TypeOf:
795 case Type::DependentName:
796 case Type::Decltype:
797 case Type::PackIndexing:
798 case Type::UnresolvedUsing:
799 case Type::TemplateTypeParm:
800 case Type::Auto:
801 return true;
802
803 case Type::ConstantArray:
804 case Type::IncompleteArray:
805 case Type::VariableArray:
806 case Type::DependentSizedArray:
808 cast<ArrayType>(T)->getElementType().getTypePtr());
809
810 default:
811 return false;
812 }
813}
814
815/// Determines whether the given type is an opaque type that
816/// might be more qualified when instantiated.
819 T->getCanonicalTypeInternal().getTypePtr());
820}
821
822/// Helper function to build a TemplateParameter when we don't
823/// know its type statically.
825 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
826 return TemplateParameter(TTP);
827 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
828 return TemplateParameter(NTTP);
829
831}
832
833/// A pack that we're currently deducing.
835 // The index of the pack.
836 unsigned Index;
837
838 // The old value of the pack before we started deducing it.
840
841 // A deferred value of this pack from an inner deduction, that couldn't be
842 // deduced because this deduction hadn't happened yet.
844
845 // The new value of the pack.
847
848 // The outer deduction for this pack, if any.
849 DeducedPack *Outer = nullptr;
850
851 DeducedPack(unsigned Index) : Index(Index) {}
852};
853
854namespace {
855
856/// A scope in which we're performing pack deduction.
857class PackDeductionScope {
858public:
859 /// Prepare to deduce the packs named within Pattern.
860 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
861 /// just checking a previous deduction of the pack.
862 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
865 bool DeducePackIfNotAlreadyDeduced = false,
866 bool FinishingDeduction = false)
867 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
868 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
869 FinishingDeduction(FinishingDeduction) {
870 unsigned NumNamedPacks = addPacks(Pattern);
871 finishConstruction(NumNamedPacks);
872 }
873
874 /// Prepare to directly deduce arguments of the parameter with index \p Index.
875 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
876 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
877 TemplateDeductionInfo &Info, unsigned Index)
878 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
879 addPack(Index);
880 finishConstruction(1);
881 }
882
883private:
884 void addPack(unsigned Index) {
885 // Save the deduced template argument for the parameter pack expanded
886 // by this pack expansion, then clear out the deduction.
887 DeducedFromEarlierParameter = !Deduced[Index].isNull();
888 DeducedPack Pack(Index);
889 if (!FinishingDeduction) {
890 Pack.Saved = Deduced[Index];
891 Deduced[Index] = TemplateArgument();
892 }
893
894 // FIXME: What if we encounter multiple packs with different numbers of
895 // pre-expanded expansions? (This should already have been diagnosed
896 // during substitution.)
897 if (UnsignedOrNone ExpandedPackExpansions =
898 getExpandedPackSize(TemplateParams->getParam(Index)))
899 FixedNumExpansions = ExpandedPackExpansions;
900
901 Packs.push_back(Pack);
902 }
903
904 unsigned addPacks(TemplateArgument Pattern) {
905 // Compute the set of template parameter indices that correspond to
906 // parameter packs expanded by the pack expansion.
907 llvm::SmallBitVector SawIndices(TemplateParams->size());
908 llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
909
910 auto AddPack = [&](unsigned Index) {
911 if (SawIndices[Index])
912 return;
913 SawIndices[Index] = true;
914 addPack(Index);
915
916 // Deducing a parameter pack that is a pack expansion also constrains the
917 // packs appearing in that parameter to have the same deduced arity. Also,
918 // in C++17 onwards, deducing a non-type template parameter deduces its
919 // type, so we need to collect the pending deduced values for those packs.
920 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
921 TemplateParams->getParam(Index))) {
922 if (!NTTP->isExpandedParameterPack())
923 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
924 // context, however it is not yet resolved.
925 if (auto *Expansion = dyn_cast<PackExpansionType>(
926 S.Context.getUnconstrainedType(NTTP->getType())))
927 ExtraDeductions.push_back(Expansion->getPattern());
928 }
929 // FIXME: Also collect the unexpanded packs in any type and template
930 // parameter packs that are pack expansions.
931 };
932
933 auto Collect = [&](TemplateArgument Pattern) {
934 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
935 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
936 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
937 unsigned Depth, Index;
938 if (auto DI = getDepthAndIndex(Unexpanded[I]))
939 std::tie(Depth, Index) = *DI;
940 else
941 continue;
942
943 if (Depth == Info.getDeducedDepth())
944 AddPack(Index);
945 }
946 };
947
948 // Look for unexpanded packs in the pattern.
949 Collect(Pattern);
950
951 unsigned NumNamedPacks = Packs.size();
952
953 // Also look for unexpanded packs that are indirectly deduced by deducing
954 // the sizes of the packs in this pattern.
955 while (!ExtraDeductions.empty())
956 Collect(ExtraDeductions.pop_back_val());
957
958 return NumNamedPacks;
959 }
960
961 void finishConstruction(unsigned NumNamedPacks) {
962 // Dig out the partially-substituted pack, if there is one.
963 const TemplateArgument *PartialPackArgs = nullptr;
964 unsigned NumPartialPackArgs = 0;
965 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
966 if (auto *Scope = S.CurrentInstantiationScope)
967 if (auto *Partial = Scope->getPartiallySubstitutedPack(
968 &PartialPackArgs, &NumPartialPackArgs))
969 PartialPackDepthIndex = getDepthAndIndex(Partial);
970
971 // This pack expansion will have been partially or fully expanded if
972 // it only names explicitly-specified parameter packs (including the
973 // partially-substituted one, if any).
974 bool IsExpanded = true;
975 for (unsigned I = 0; I != NumNamedPacks; ++I) {
976 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
977 IsExpanded = false;
978 IsPartiallyExpanded = false;
979 break;
980 }
981 if (PartialPackDepthIndex ==
982 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
983 IsPartiallyExpanded = true;
984 }
985 }
986
987 // Skip over the pack elements that were expanded into separate arguments.
988 // If we partially expanded, this is the number of partial arguments.
989 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
990 // https://github.com/llvm/llvm-project/issues/100095
991 if (IsPartiallyExpanded)
992 PackElements += NumPartialPackArgs;
993 else if (IsExpanded && FixedNumExpansions)
994 PackElements += *FixedNumExpansions;
995
996 for (auto &Pack : Packs) {
997 if (Info.PendingDeducedPacks.size() > Pack.Index)
998 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
999 else
1000 Info.PendingDeducedPacks.resize(Pack.Index + 1);
1001 Info.PendingDeducedPacks[Pack.Index] = &Pack;
1002
1003 if (PartialPackDepthIndex ==
1004 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
1005 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
1006 }
1007 }
1008 }
1009
1010public:
1011 ~PackDeductionScope() {
1012 for (auto &Pack : Packs)
1013 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
1014 }
1015
1016 // Return the size of the saved packs if all of them has the same size.
1017 UnsignedOrNone getSavedPackSizeIfAllEqual() const {
1018 unsigned PackSize = Packs[0].Saved.pack_size();
1019
1020 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
1021 return P.Saved.pack_size() == PackSize;
1022 }))
1023 return PackSize;
1024 return std::nullopt;
1025 }
1026
1027 /// Determine whether this pack has already been deduced from a previous
1028 /// argument.
1029 bool isDeducedFromEarlierParameter() const {
1030 return DeducedFromEarlierParameter;
1031 }
1032
1033 /// Determine whether this pack has already been partially expanded into a
1034 /// sequence of (prior) function parameters / template arguments.
1035 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
1036
1037 /// Determine whether this pack expansion scope has a known, fixed arity.
1038 /// This happens if it involves a pack from an outer template that has
1039 /// (notionally) already been expanded.
1040 bool hasFixedArity() { return static_cast<bool>(FixedNumExpansions); }
1041
1042 /// Determine whether the next element of the argument is still part of this
1043 /// pack. This is the case unless the pack is already expanded to a fixed
1044 /// length.
1045 bool hasNextElement() {
1046 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1047 }
1048
1049 /// Move to deducing the next element in each pack that is being deduced.
1050 void nextPackElement() {
1051 // Capture the deduced template arguments for each parameter pack expanded
1052 // by this pack expansion, add them to the list of arguments we've deduced
1053 // for that pack, then clear out the deduced argument.
1054 if (!FinishingDeduction) {
1055 for (auto &Pack : Packs) {
1056 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1057 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1058 while (Pack.New.size() < PackElements)
1059 Pack.New.push_back(DeducedTemplateArgument());
1060 if (Pack.New.size() == PackElements)
1061 Pack.New.push_back(DeducedArg);
1062 else
1063 Pack.New[PackElements] = DeducedArg;
1064 DeducedArg = Pack.New.size() > PackElements + 1
1065 ? Pack.New[PackElements + 1]
1066 : DeducedTemplateArgument();
1067 }
1068 }
1069 }
1070 ++PackElements;
1071 }
1072
1073 /// Finish template argument deduction for a set of argument packs,
1074 /// producing the argument packs and checking for consistency with prior
1075 /// deductions.
1076 TemplateDeductionResult finish() {
1077 if (FinishingDeduction)
1078 return TemplateDeductionResult::Success;
1079 // Build argument packs for each of the parameter packs expanded by this
1080 // pack expansion.
1081 for (auto &Pack : Packs) {
1082 // Put back the old value for this pack.
1083 if (!FinishingDeduction)
1084 Deduced[Pack.Index] = Pack.Saved;
1085
1086 // Always make sure the size of this pack is correct, even if we didn't
1087 // deduce any values for it.
1088 //
1089 // FIXME: This isn't required by the normative wording, but substitution
1090 // and post-substitution checking will always fail if the arity of any
1091 // pack is not equal to the number of elements we processed. (Either that
1092 // or something else has gone *very* wrong.) We're permitted to skip any
1093 // hard errors from those follow-on steps by the intent (but not the
1094 // wording) of C++ [temp.inst]p8:
1095 //
1096 // If the function selected by overload resolution can be determined
1097 // without instantiating a class template definition, it is unspecified
1098 // whether that instantiation actually takes place
1099 Pack.New.resize(PackElements);
1100
1101 // Build or find a new value for this pack.
1102 DeducedTemplateArgument NewPack;
1103 if (Pack.New.empty()) {
1104 // If we deduced an empty argument pack, create it now.
1105 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
1106 } else {
1107 TemplateArgument *ArgumentPack =
1108 new (S.Context) TemplateArgument[Pack.New.size()];
1109 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1110 NewPack = DeducedTemplateArgument(
1111 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1112 // FIXME: This is wrong, it's possible that some pack elements are
1113 // deduced from an array bound and others are not:
1114 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1115 // g({1, 2, 3}, {{}, {}});
1116 // ... should deduce T = {int, size_t (from array bound)}.
1117 Pack.New[0].wasDeducedFromArrayBound());
1118 }
1119
1120 // Pick where we're going to put the merged pack.
1121 DeducedTemplateArgument *Loc;
1122 if (Pack.Outer) {
1123 if (Pack.Outer->DeferredDeduction.isNull()) {
1124 // Defer checking this pack until we have a complete pack to compare
1125 // it against.
1126 Pack.Outer->DeferredDeduction = NewPack;
1127 continue;
1128 }
1129 Loc = &Pack.Outer->DeferredDeduction;
1130 } else {
1131 Loc = &Deduced[Pack.Index];
1132 }
1133
1134 // Check the new pack matches any previous value.
1135 DeducedTemplateArgument OldPack = *Loc;
1136 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
1137 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1138
1139 Info.AggregateDeductionCandidateHasMismatchedArity =
1140 OldPack.getKind() == TemplateArgument::Pack &&
1141 NewPack.getKind() == TemplateArgument::Pack &&
1142 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1143
1144 // If we deferred a deduction of this pack, check that one now too.
1145 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1146 OldPack = Result;
1147 NewPack = Pack.DeferredDeduction;
1148 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1149 }
1150
1151 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1152 if (Result.isNull()) {
1153 Info.Param = makeTemplateParameter(Param);
1154 Info.FirstArg = OldPack;
1155 Info.SecondArg = NewPack;
1156 return TemplateDeductionResult::Inconsistent;
1157 }
1158
1159 // If we have a pre-expanded pack and we didn't deduce enough elements
1160 // for it, fail deduction.
1161 if (UnsignedOrNone Expansions = getExpandedPackSize(Param)) {
1162 if (*Expansions != PackElements) {
1163 Info.Param = makeTemplateParameter(Param);
1164 Info.FirstArg = Result;
1165 return TemplateDeductionResult::IncompletePack;
1166 }
1167 }
1168
1169 *Loc = Result;
1170 }
1171
1172 return TemplateDeductionResult::Success;
1173 }
1174
1175private:
1176 Sema &S;
1177 TemplateParameterList *TemplateParams;
1178 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
1179 TemplateDeductionInfo &Info;
1180 unsigned PackElements = 0;
1181 bool IsPartiallyExpanded = false;
1182 bool DeducePackIfNotAlreadyDeduced = false;
1183 bool DeducedFromEarlierParameter = false;
1184 bool FinishingDeduction = false;
1185 /// The number of expansions, if we have a fully-expanded pack in this scope.
1186 UnsignedOrNone FixedNumExpansions = std::nullopt;
1187
1188 SmallVector<DeducedPack, 2> Packs;
1189};
1190
1191} // namespace
1192
1193template <class T>
1195 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1198 bool FinishingDeduction, T &&DeductFunc) {
1199 // C++0x [temp.deduct.type]p10:
1200 // Similarly, if P has a form that contains (T), then each parameter type
1201 // Pi of the respective parameter-type- list of P is compared with the
1202 // corresponding parameter type Ai of the corresponding parameter-type-list
1203 // of A. [...]
1204 unsigned ArgIdx = 0, ParamIdx = 0;
1205 for (; ParamIdx != Params.size(); ++ParamIdx) {
1206 // Check argument types.
1207 const PackExpansionType *Expansion
1208 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1209 if (!Expansion) {
1210 // Simple case: compare the parameter and argument types at this point.
1211
1212 // Make sure we have an argument.
1213 if (ArgIdx >= Args.size())
1215
1216 if (isa<PackExpansionType>(Args[ArgIdx])) {
1217 // C++0x [temp.deduct.type]p22:
1218 // If the original function parameter associated with A is a function
1219 // parameter pack and the function parameter associated with P is not
1220 // a function parameter pack, then template argument deduction fails.
1222 }
1223
1224 if (TemplateDeductionResult Result =
1225 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1226 Params[ParamIdx].getUnqualifiedType(),
1227 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1229 return Result;
1230
1231 ++ArgIdx;
1232 continue;
1233 }
1234
1235 // C++0x [temp.deduct.type]p10:
1236 // If the parameter-declaration corresponding to Pi is a function
1237 // parameter pack, then the type of its declarator- id is compared with
1238 // each remaining parameter type in the parameter-type-list of A. Each
1239 // comparison deduces template arguments for subsequent positions in the
1240 // template parameter packs expanded by the function parameter pack.
1241
1242 QualType Pattern = Expansion->getPattern();
1243 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1244 /*DeducePackIfNotAlreadyDeduced=*/false,
1245 FinishingDeduction);
1246
1247 // A pack scope with fixed arity is not really a pack any more, so is not
1248 // a non-deduced context.
1249 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1250 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1251 // Deduce template arguments from the pattern.
1252 if (TemplateDeductionResult Result = DeductFunc(
1253 S, TemplateParams, ParamIdx, ArgIdx,
1254 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1255 Info, Deduced, POK);
1257 return Result;
1258 PackScope.nextPackElement();
1259 }
1260 } else {
1261 // C++0x [temp.deduct.type]p5:
1262 // The non-deduced contexts are:
1263 // - A function parameter pack that does not occur at the end of the
1264 // parameter-declaration-clause.
1265 //
1266 // FIXME: There is no wording to say what we should do in this case. We
1267 // choose to resolve this by applying the same rule that is applied for a
1268 // function call: that is, deduce all contained packs to their
1269 // explicitly-specified values (or to <> if there is no such value).
1270 //
1271 // This is seemingly-arbitrarily different from the case of a template-id
1272 // with a non-trailing pack-expansion in its arguments, which renders the
1273 // entire template-argument-list a non-deduced context.
1274
1275 // If the parameter type contains an explicitly-specified pack that we
1276 // could not expand, skip the number of parameters notionally created
1277 // by the expansion.
1278 UnsignedOrNone NumExpansions = Expansion->getNumExpansions();
1279 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1280 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1281 ++I, ++ArgIdx)
1282 PackScope.nextPackElement();
1283 }
1284 }
1285
1286 // Build argument packs for each of the parameter packs expanded by this
1287 // pack expansion.
1288 if (auto Result = PackScope.finish();
1290 return Result;
1291 }
1292
1293 // DR692, DR1395
1294 // C++0x [temp.deduct.type]p10:
1295 // If the parameter-declaration corresponding to P_i ...
1296 // During partial ordering, if Ai was originally a function parameter pack:
1297 // - if P does not contain a function parameter type corresponding to Ai then
1298 // Ai is ignored;
1299 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1300 isa<PackExpansionType>(Args[ArgIdx]))
1302
1303 // Make sure we don't have any extra arguments.
1304 if (ArgIdx < Args.size())
1306
1308}
1309
1310/// Deduce the template arguments by comparing the list of parameter
1311/// types to the list of argument types, as in the parameter-type-lists of
1312/// function types (C++ [temp.deduct.type]p10).
1313///
1314/// \param S The semantic analysis object within which we are deducing
1315///
1316/// \param TemplateParams The template parameters that we are deducing
1317///
1318/// \param Params The list of parameter types
1319///
1320/// \param Args The list of argument types
1321///
1322/// \param Info information about the template argument deduction itself
1323///
1324/// \param Deduced the deduced template arguments
1325///
1326/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1327/// how template argument deduction is performed.
1328///
1329/// \param PartialOrdering If true, we are performing template argument
1330/// deduction for during partial ordering for a call
1331/// (C++0x [temp.deduct.partial]).
1332///
1333/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1334/// whether any template parameter was deduced.
1335///
1336/// \param HasDeducedParam If set, the bit vector will be used to represent
1337/// which template parameters were deduced, in order.
1338///
1339/// \returns the result of template argument deduction so far. Note that a
1340/// "success" result means that template argument deduction has not yet failed,
1341/// but it may still fail, later, for other reasons.
1343 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1346 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1347 llvm::SmallBitVector *HasDeducedParam) {
1348 return ::DeduceForEachType(
1349 S, TemplateParams, Params, Args, Info, Deduced, POK,
1350 /*FinishingDeduction=*/false,
1351 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1352 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1354 PartialOrderingKind POK) {
1355 bool HasDeducedAnyParamCopy = false;
1357 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1358 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1359 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1360 *HasDeducedAnyParam = true;
1361 if (HasDeducedParam && HasDeducedAnyParamCopy)
1362 (*HasDeducedParam)[ParamIdx] = true;
1363 return TDR;
1364 });
1365}
1366
1367/// Determine whether the parameter has qualifiers that the argument
1368/// lacks. Put another way, determine whether there is no way to add
1369/// a deduced set of qualifiers to the ParamType that would result in
1370/// its qualifiers matching those of the ArgType.
1372 QualType ArgType) {
1373 Qualifiers ParamQs = ParamType.getQualifiers();
1374 Qualifiers ArgQs = ArgType.getQualifiers();
1375
1376 if (ParamQs == ArgQs)
1377 return false;
1378
1379 // Mismatched (but not missing) Objective-C GC attributes.
1380 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1381 ParamQs.hasObjCGCAttr())
1382 return true;
1383
1384 // Mismatched (but not missing) address spaces.
1385 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1386 ParamQs.hasAddressSpace())
1387 return true;
1388
1389 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1390 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1391 ParamQs.hasObjCLifetime())
1392 return true;
1393
1394 // CVR qualifiers inconsistent or a superset.
1395 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1396}
1397
1399 const FunctionType *PF = P->getAs<FunctionType>(),
1400 *AF = A->getAs<FunctionType>();
1401
1402 // Just compare if not functions.
1403 if (!PF || !AF)
1404 return Context.hasSameType(P, A);
1405
1406 // Noreturn and noexcept adjustment.
1407 if (QualType AdjustedParam; TryFunctionConversion(P, A, AdjustedParam))
1408 P = AdjustedParam;
1409
1410 // FIXME: Compatible calling conventions.
1411 return Context.hasSameFunctionTypeIgnoringExceptionSpec(P, A);
1412}
1413
1414/// Get the index of the first template parameter that was originally from the
1415/// innermost template-parameter-list. This is 0 except when we concatenate
1416/// the template parameter lists of a class template and a constructor template
1417/// when forming an implicit deduction guide.
1419 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1420 if (!Guide || !Guide->isImplicit())
1421 return 0;
1422 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1423}
1424
1425/// Determine whether a type denotes a forwarding reference.
1426static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1427 // C++1z [temp.deduct.call]p3:
1428 // A forwarding reference is an rvalue reference to a cv-unqualified
1429 // template parameter that does not represent a template parameter of a
1430 // class template.
1431 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1432 if (ParamRef->getPointeeType().getQualifiers())
1433 return false;
1434 auto *TypeParm =
1435 ParamRef->getPointeeType()->getAsCanonical<TemplateTypeParmType>();
1436 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1437 }
1438 return false;
1439}
1440
1441/// Attempt to deduce the template arguments by checking the base types
1442/// according to (C++20 [temp.deduct.call] p4b3.
1443///
1444/// \param S the semantic analysis object within which we are deducing.
1445///
1446/// \param RD the top level record object we are deducing against.
1447///
1448/// \param TemplateParams the template parameters that we are deducing.
1449///
1450/// \param P the template specialization parameter type.
1451///
1452/// \param Info information about the template argument deduction itself.
1453///
1454/// \param Deduced the deduced template arguments.
1455///
1456/// \returns the result of template argument deduction with the bases. "invalid"
1457/// means no matches, "success" found a single item, and the
1458/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1461 TemplateParameterList *TemplateParams, QualType P,
1464 bool *HasDeducedAnyParam) {
1465 // C++14 [temp.deduct.call] p4b3:
1466 // If P is a class and P has the form simple-template-id, then the
1467 // transformed A can be a derived class of the deduced A. Likewise if
1468 // P is a pointer to a class of the form simple-template-id, the
1469 // transformed A can be a pointer to a derived class pointed to by the
1470 // deduced A. However, if there is a class C that is a (direct or
1471 // indirect) base class of D and derived (directly or indirectly) from a
1472 // class B and that would be a valid deduced A, the deduced A cannot be
1473 // B or pointer to B, respectively.
1474 //
1475 // These alternatives are considered only if type deduction would
1476 // otherwise fail. If they yield more than one possible deduced A, the
1477 // type deduction fails.
1478
1479 // Use a breadth-first search through the bases to collect the set of
1480 // successful matches. Visited contains the set of nodes we have already
1481 // visited, while ToVisit is our stack of records that we still need to
1482 // visit. Matches contains a list of matches that have yet to be
1483 // disqualified.
1486 // We iterate over this later, so we have to use MapVector to ensure
1487 // determinism.
1488 struct MatchValue {
1490 bool HasDeducedAnyParam;
1491 };
1492 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1493
1494 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1495 for (const auto &Base : RD->bases()) {
1496 QualType T = Base.getType();
1497 assert(T->isRecordType() && "Base class that isn't a record?");
1498 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1499 ToVisit.push_back(T);
1500 }
1501 };
1502
1503 // Set up the loop by adding all the bases.
1504 AddBases(RD);
1505
1506 // Search each path of bases until we either run into a successful match
1507 // (where all bases of it are invalid), or we run out of bases.
1508 while (!ToVisit.empty()) {
1509 QualType NextT = ToVisit.pop_back_val();
1510
1512 Deduced.end());
1514 bool HasDeducedAnyParamCopy = false;
1516 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1517 &HasDeducedAnyParamCopy);
1518
1519 // If this was a successful deduction, add it to the list of matches,
1520 // otherwise we need to continue searching its bases.
1521 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1523 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1524 else
1525 AddBases(RD);
1526 }
1527
1528 // At this point, 'Matches' contains a list of seemingly valid bases, however
1529 // in the event that we have more than 1 match, it is possible that the base
1530 // of one of the matches might be disqualified for being a base of another
1531 // valid match. We can count on cyclical instantiations being invalid to
1532 // simplify the disqualifications. That is, if A & B are both matches, and B
1533 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1534 if (Matches.size() > 1) {
1535 Visited.clear();
1536 for (const auto &Match : Matches)
1537 AddBases(Match.first);
1538
1539 // We can give up once we have a single item (or have run out of things to
1540 // search) since cyclical inheritance isn't valid.
1541 while (Matches.size() > 1 && !ToVisit.empty()) {
1542 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1543 Matches.erase(RD);
1544
1545 // Always add all bases, since the inheritance tree can contain
1546 // disqualifications for multiple matches.
1547 AddBases(RD);
1548 }
1549 }
1550
1551 if (Matches.empty())
1553 if (Matches.size() > 1)
1555
1556 std::swap(Matches.front().second.Deduced, Deduced);
1557 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1558 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1559 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1561}
1562
1563/// When propagating a partial ordering kind into a NonCall context,
1564/// this is used to downgrade a 'Call' into a 'NonCall', so that
1565/// the kind still reflects whether we are in a partial ordering context.
1570
1571/// Deduce the template arguments by comparing the parameter type and
1572/// the argument type (C++ [temp.deduct.type]).
1573///
1574/// \param S the semantic analysis object within which we are deducing
1575///
1576/// \param TemplateParams the template parameters that we are deducing
1577///
1578/// \param P the parameter type
1579///
1580/// \param A the argument type
1581///
1582/// \param Info information about the template argument deduction itself
1583///
1584/// \param Deduced the deduced template arguments
1585///
1586/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1587/// how template argument deduction is performed.
1588///
1589/// \param PartialOrdering Whether we're performing template argument deduction
1590/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1591///
1592/// \returns the result of template argument deduction so far. Note that a
1593/// "success" result means that template argument deduction has not yet failed,
1594/// but it may still fail, later, for other reasons.
1596 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1599 PartialOrderingKind POK, bool DeducedFromArrayBound,
1600 bool *HasDeducedAnyParam) {
1601
1602 // If the argument type is a pack expansion, look at its pattern.
1603 // This isn't explicitly called out
1604 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1605 A = AExp->getPattern();
1607
1608 if (POK == PartialOrderingKind::Call) {
1609 // C++11 [temp.deduct.partial]p5:
1610 // Before the partial ordering is done, certain transformations are
1611 // performed on the types used for partial ordering:
1612 // - If P is a reference type, P is replaced by the type referred to.
1613 const ReferenceType *PRef = P->getAs<ReferenceType>();
1614 if (PRef)
1615 P = PRef->getPointeeType();
1616
1617 // - If A is a reference type, A is replaced by the type referred to.
1618 const ReferenceType *ARef = A->getAs<ReferenceType>();
1619 if (ARef)
1620 A = A->getPointeeType();
1621
1622 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1623 // C++11 [temp.deduct.partial]p9:
1624 // If, for a given type, deduction succeeds in both directions (i.e.,
1625 // the types are identical after the transformations above) and both
1626 // P and A were reference types [...]:
1627 // - if [one type] was an lvalue reference and [the other type] was
1628 // not, [the other type] is not considered to be at least as
1629 // specialized as [the first type]
1630 // - if [one type] is more cv-qualified than [the other type],
1631 // [the other type] is not considered to be at least as specialized
1632 // as [the first type]
1633 // Objective-C ARC adds:
1634 // - [one type] has non-trivial lifetime, [the other type] has
1635 // __unsafe_unretained lifetime, and the types are otherwise
1636 // identical
1637 //
1638 // A is "considered to be at least as specialized" as P iff deduction
1639 // succeeds, so we model this as a deduction failure. Note that
1640 // [the first type] is P and [the other type] is A here; the standard
1641 // gets this backwards.
1642 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1643 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1644 PQuals.isStrictSupersetOf(AQuals) ||
1645 (PQuals.hasNonTrivialObjCLifetime() &&
1646 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1647 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1648 Info.FirstArg = TemplateArgument(P);
1649 Info.SecondArg = TemplateArgument(A);
1651 }
1652 }
1653 Qualifiers DiscardedQuals;
1654 // C++11 [temp.deduct.partial]p7:
1655 // Remove any top-level cv-qualifiers:
1656 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1657 // version of P.
1658 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1659 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1660 // version of A.
1661 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1662 } else {
1663 // C++0x [temp.deduct.call]p4 bullet 1:
1664 // - If the original P is a reference type, the deduced A (i.e., the type
1665 // referred to by the reference) can be more cv-qualified than the
1666 // transformed A.
1667 if (TDF & TDF_ParamWithReferenceType) {
1668 Qualifiers Quals;
1669 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1671 P = S.Context.getQualifiedType(UnqualP, Quals);
1672 }
1673
1674 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1675 // C++0x [temp.deduct.type]p10:
1676 // If P and A are function types that originated from deduction when
1677 // taking the address of a function template (14.8.2.2) or when deducing
1678 // template arguments from a function declaration (14.8.2.6) and Pi and
1679 // Ai are parameters of the top-level parameter-type-list of P and A,
1680 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1681 // is an lvalue reference, in
1682 // which case the type of Pi is changed to be the template parameter
1683 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1684 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1685 // deduced as X&. - end note ]
1687 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1689 P = P->getPointeeType();
1690 }
1691 }
1692
1693 // C++ [temp.deduct.type]p9:
1694 // A template type argument T, a template template argument TT or a
1695 // template non-type argument i can be deduced if P and A have one of
1696 // the following forms:
1697 //
1698 // T
1699 // cv-list T
1700 if (const auto *TTP = P->getAsCanonical<TemplateTypeParmType>()) {
1701 // Just skip any attempts to deduce from a placeholder type or a parameter
1702 // at a different depth.
1703 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1705
1706 unsigned Index = TTP->getIndex();
1707
1708 // If the argument type is an array type, move the qualifiers up to the
1709 // top level, so they can be matched with the qualifiers on the parameter.
1710 if (A->isArrayType()) {
1711 Qualifiers Quals;
1712 A = S.Context.getUnqualifiedArrayType(A, Quals);
1713 if (Quals)
1714 A = S.Context.getQualifiedType(A, Quals);
1715 }
1716
1717 // The argument type can not be less qualified than the parameter
1718 // type.
1719 if (!(TDF & TDF_IgnoreQualifiers) &&
1721 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1722 Info.FirstArg = TemplateArgument(P);
1723 Info.SecondArg = TemplateArgument(A);
1725 }
1726
1727 // Do not match a function type with a cv-qualified type.
1728 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1729 if (A->isFunctionType() && P.hasQualifiers())
1731
1732 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1733 "saw template type parameter with wrong depth");
1734 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1735 "Unresolved overloaded function");
1736 QualType DeducedType = A;
1737
1738 // Remove any qualifiers on the parameter from the deduced type.
1739 // We checked the qualifiers for consistency above.
1740 Qualifiers DeducedQs = DeducedType.getQualifiers();
1741 Qualifiers ParamQs = P.getQualifiers();
1742 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1743 if (ParamQs.hasObjCGCAttr())
1744 DeducedQs.removeObjCGCAttr();
1745 if (ParamQs.hasAddressSpace())
1746 DeducedQs.removeAddressSpace();
1747 if (ParamQs.hasObjCLifetime())
1748 DeducedQs.removeObjCLifetime();
1749
1750 // Objective-C ARC:
1751 // If template deduction would produce a lifetime qualifier on a type
1752 // that is not a lifetime type, template argument deduction fails.
1753 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1754 !DeducedType->isDependentType()) {
1755 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1756 Info.FirstArg = TemplateArgument(P);
1757 Info.SecondArg = TemplateArgument(A);
1759 }
1760
1761 // Objective-C ARC:
1762 // If template deduction would produce an argument type with lifetime type
1763 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1764 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1765 !DeducedQs.hasObjCLifetime())
1767
1768 DeducedType =
1769 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1770
1771 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1773 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1774 if (Result.isNull()) {
1775 // We can also get inconsistencies when matching NTTP type.
1776 switch (NamedDecl *Param = TemplateParams->getParam(Index);
1777 Param->getKind()) {
1778 case Decl::TemplateTypeParm:
1779 Info.Param = cast<TemplateTypeParmDecl>(Param);
1780 break;
1781 case Decl::NonTypeTemplateParm:
1783 break;
1784 case Decl::TemplateTemplateParm:
1786 break;
1787 default:
1788 llvm_unreachable("unexpected kind");
1789 }
1790 Info.FirstArg = Deduced[Index];
1791 Info.SecondArg = NewDeduced;
1793 }
1794
1795 Deduced[Index] = Result;
1796 if (HasDeducedAnyParam)
1797 *HasDeducedAnyParam = true;
1799 }
1800
1801 // Set up the template argument deduction information for a failure.
1802 Info.FirstArg = TemplateArgument(P);
1803 Info.SecondArg = TemplateArgument(A);
1804
1805 // If the parameter is an already-substituted template parameter
1806 // pack, do nothing: we don't know which of its arguments to look
1807 // at, so we have to wait until all of the parameter packs in this
1808 // expansion have arguments.
1809 if (P->getAs<SubstTemplateTypeParmPackType>())
1811
1812 // Check the cv-qualifiers on the parameter and argument types.
1813 if (!(TDF & TDF_IgnoreQualifiers)) {
1814 if (TDF & TDF_ParamWithReferenceType) {
1817 } else if (TDF & TDF_ArgWithReferenceType) {
1818 // C++ [temp.deduct.conv]p4:
1819 // If the original A is a reference type, A can be more cv-qualified
1820 // than the deduced A
1822 S.getASTContext()))
1824
1825 // Strip out all extra qualifiers from the argument to figure out the
1826 // type we're converting to, prior to the qualification conversion.
1827 Qualifiers Quals;
1828 A = S.Context.getUnqualifiedArrayType(A, Quals);
1830 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1831 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1833 }
1834 }
1835
1836 // If the parameter type is not dependent, there is nothing to deduce.
1837 if (!P->isDependentType()) {
1838 if (TDF & TDF_SkipNonDependent)
1841 : S.Context.hasSameType(P, A))
1846 if (!(TDF & TDF_IgnoreQualifiers))
1848 // Otherwise, when ignoring qualifiers, the types not having the same
1849 // unqualified type does not mean they do not match, so in this case we
1850 // must keep going and analyze with a non-dependent parameter type.
1851 }
1852
1853 switch (P.getCanonicalType()->getTypeClass()) {
1854 // Non-canonical types cannot appear here.
1855#define NON_CANONICAL_TYPE(Class, Base) \
1856 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1857#define TYPE(Class, Base)
1858#include "clang/AST/TypeNodes.inc"
1859
1860 case Type::TemplateTypeParm:
1861 case Type::SubstTemplateTypeParmPack:
1862 case Type::SubstBuiltinTemplatePack:
1863 llvm_unreachable("Type nodes handled above");
1864
1865 case Type::Auto:
1866 // C++23 [temp.deduct.funcaddr]/3:
1867 // A placeholder type in the return type of a function template is a
1868 // non-deduced context.
1869 // There's no corresponding wording for [temp.deduct.decl], but we treat
1870 // it the same to match other compilers.
1871 if (P->isDependentType())
1873 [[fallthrough]];
1874 case Type::Builtin:
1875 case Type::VariableArray:
1876 case Type::Vector:
1877 case Type::FunctionNoProto:
1878 case Type::Record:
1879 case Type::Enum:
1880 case Type::ObjCObject:
1881 case Type::ObjCInterface:
1882 case Type::ObjCObjectPointer:
1883 case Type::BitInt:
1884 return (TDF & TDF_SkipNonDependent) ||
1885 ((TDF & TDF_IgnoreQualifiers)
1887 : S.Context.hasSameType(P, A))
1890
1891 // _Complex T [placeholder extension]
1892 case Type::Complex: {
1893 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1894 if (!CA)
1897 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1899 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1900 }
1901
1902 // _Atomic T [extension]
1903 case Type::Atomic: {
1904 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1905 if (!AA)
1908 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1910 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1911 }
1912
1913 // T *
1914 case Type::Pointer: {
1915 QualType PointeeType;
1916 if (const auto *PA = A->getAs<PointerType>()) {
1917 PointeeType = PA->getPointeeType();
1918 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1919 PointeeType = PA->getPointeeType();
1920 } else {
1922 }
1924 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1925 PointeeType, Info, Deduced,
1928 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1929 }
1930
1931 // T &
1932 case Type::LValueReference: {
1933 const auto *RP = P->castAs<LValueReferenceType>(),
1934 *RA = A->getAs<LValueReferenceType>();
1935 if (!RA)
1937
1939 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1941 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1942 }
1943
1944 // T && [C++0x]
1945 case Type::RValueReference: {
1946 const auto *RP = P->castAs<RValueReferenceType>(),
1947 *RA = A->getAs<RValueReferenceType>();
1948 if (!RA)
1950
1952 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1954 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1955 }
1956
1957 // T [] (implied, but not stated explicitly)
1958 case Type::IncompleteArray: {
1959 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1960 if (!IAA)
1962
1963 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1964 assert(IAP && "Template parameter not of incomplete array type");
1965
1967 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1970 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1971 }
1972
1973 // T [integer-constant]
1974 case Type::ConstantArray: {
1975 const auto *CAA = S.Context.getAsConstantArrayType(A),
1976 *CAP = S.Context.getAsConstantArrayType(P);
1977 assert(CAP);
1978 if (!CAA || CAA->getSize() != CAP->getSize())
1980
1982 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1985 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1986 }
1987
1988 // type [i]
1989 case Type::DependentSizedArray: {
1990 const auto *AA = S.Context.getAsArrayType(A);
1991 if (!AA)
1993
1994 // Check the element type of the arrays
1995 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1996 assert(DAP);
1997 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1998 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1999 Info, Deduced, TDF & TDF_IgnoreQualifiers,
2001 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2003 return Result;
2004
2005 // Determine the array bound is something we can deduce.
2007 getDeducedNTTParameterFromExpr(Info, DAP->getSizeExpr());
2008 if (!NTTP)
2010
2011 // We can perform template argument deduction for the given non-type
2012 // template parameter.
2013 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2014 "saw non-type template parameter with wrong depth");
2015 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
2016 llvm::APSInt Size(CAA->getSize());
2018 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
2019 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2020 Deduced, HasDeducedAnyParam);
2021 }
2022 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
2023 if (DAA->getSizeExpr())
2025 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
2026 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2027
2028 // Incomplete type does not match a dependently-sized array type
2030 }
2031
2032 // type(*)(T)
2033 // T(*)()
2034 // T(*)(T)
2035 case Type::FunctionProto: {
2036 const auto *FPP = P->castAs<FunctionProtoType>(),
2037 *FPA = A->getAs<FunctionProtoType>();
2038 if (!FPA)
2040
2041 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
2042 FPP->getRefQualifier() != FPA->getRefQualifier() ||
2043 FPP->isVariadic() != FPA->isVariadic())
2045
2046 // Check return types.
2047 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2048 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
2050 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2052 return Result;
2053
2054 // Check parameter types.
2055 if (auto Result = DeduceTemplateArguments(
2056 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
2058 HasDeducedAnyParam,
2059 /*HasDeducedParam=*/nullptr);
2061 return Result;
2062
2065
2066 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
2067 // deducing through the noexcept-specifier if it's part of the canonical
2068 // type. libstdc++ relies on this.
2069 Expr *NoexceptExpr = FPP->getNoexceptExpr();
2071 NoexceptExpr ? getDeducedNTTParameterFromExpr(Info, NoexceptExpr)
2072 : nullptr) {
2073 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2074 "saw non-type template parameter with wrong depth");
2075
2076 llvm::APSInt Noexcept(1);
2077 switch (FPA->canThrow()) {
2078 case CT_Cannot:
2079 Noexcept = 1;
2080 [[fallthrough]];
2081
2082 case CT_Can:
2083 // We give E in noexcept(E) the "deduced from array bound" treatment.
2084 // FIXME: Should we?
2086 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2087 /*DeducedFromArrayBound=*/true, Info,
2088 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2089
2090 case CT_Dependent:
2091 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2093 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2094 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2095 // Can't deduce anything from throw(T...).
2096 break;
2097 }
2098 }
2099 // FIXME: Detect non-deduced exception specification mismatches?
2100 //
2101 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2102 // top-level differences in noexcept-specifications.
2103
2105 }
2106
2107 case Type::InjectedClassName:
2108 // Treat a template's injected-class-name as if the template
2109 // specialization type had been used.
2110
2111 // template-name<T> (where template-name refers to a class template)
2112 // template-name<i>
2113 // TT<T>
2114 // TT<i>
2115 // TT<>
2116 case Type::TemplateSpecialization: {
2117 // When Arg cannot be a derived class, we can just try to deduce template
2118 // arguments from the template-id.
2119 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2120 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2122 Deduced, HasDeducedAnyParam);
2123
2125 Deduced.end());
2126
2127 auto Result = DeduceTemplateSpecArguments(
2128 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2129 Deduced, HasDeducedAnyParam);
2131 return Result;
2132
2133 // We cannot inspect base classes as part of deduction when the type
2134 // is incomplete, so either instantiate any templates necessary to
2135 // complete the type, or skip over it if it cannot be completed.
2136 if (!S.isCompleteType(Info.getLocation(), A))
2137 return Result;
2138
2139 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2140 if (RD->isInvalidDecl())
2141 return Result;
2142
2143 // Reset the incorrectly deduced argument from above.
2144 Deduced = DeducedOrig;
2145
2146 // Check bases according to C++14 [temp.deduct.call] p4b3:
2147 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2149 Deduced, HasDeducedAnyParam);
2151 : Result;
2152 }
2153
2154 // T type::*
2155 // T T::*
2156 // T (type::*)()
2157 // type (T::*)()
2158 // type (type::*)(T)
2159 // type (T::*)(T)
2160 // T (type::*)(T)
2161 // T (T::*)()
2162 // T (T::*)(T)
2163 case Type::MemberPointer: {
2164 const auto *MPP = P->castAs<MemberPointerType>(),
2165 *MPA = A->getAs<MemberPointerType>();
2166 if (!MPA)
2168
2169 QualType PPT = MPP->getPointeeType();
2170 if (PPT->isFunctionType())
2171 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2172 /*IsCtorOrDtor=*/false, Info.getLocation());
2173 QualType APT = MPA->getPointeeType();
2174 if (APT->isFunctionType())
2175 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2176 /*IsCtorOrDtor=*/false, Info.getLocation());
2177
2178 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2179 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2180 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2182 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2184 return Result;
2185
2186 QualType TP =
2187 MPP->isSugared()
2188 ? S.Context.getCanonicalTagType(MPP->getMostRecentCXXRecordDecl())
2189 : QualType(MPP->getQualifier().getAsType(), 0);
2190 assert(!TP.isNull() && "member pointer with non-type class");
2191
2192 QualType TA =
2193 MPA->isSugared()
2194 ? S.Context.getCanonicalTagType(MPA->getMostRecentCXXRecordDecl())
2195 : QualType(MPA->getQualifier().getAsType(), 0)
2197 assert(!TA.isNull() && "member pointer with non-type class");
2198
2200 S, TemplateParams, TP, TA, Info, Deduced, SubTDF,
2202 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2203 }
2204
2205 // (clang extension)
2206 //
2207 // type(^)(T)
2208 // T(^)()
2209 // T(^)(T)
2210 case Type::BlockPointer: {
2211 const auto *BPP = P->castAs<BlockPointerType>(),
2212 *BPA = A->getAs<BlockPointerType>();
2213 if (!BPA)
2216 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2218 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2219 }
2220
2221 // (clang extension)
2222 //
2223 // T __attribute__(((ext_vector_type(<integral constant>))))
2224 case Type::ExtVector: {
2225 const auto *VP = P->castAs<ExtVectorType>();
2226 QualType ElementType;
2227 if (const auto *VA = A->getAs<ExtVectorType>()) {
2228 // Make sure that the vectors have the same number of elements.
2229 if (VP->getNumElements() != VA->getNumElements())
2231 ElementType = VA->getElementType();
2232 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2233 // We can't check the number of elements, since the argument has a
2234 // dependent number of elements. This can only occur during partial
2235 // ordering.
2236 ElementType = VA->getElementType();
2237 } else {
2239 }
2240 // Perform deduction on the element types.
2242 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2244 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2245 }
2246
2247 case Type::DependentVector: {
2248 const auto *VP = P->castAs<DependentVectorType>();
2249
2250 if (const auto *VA = A->getAs<VectorType>()) {
2251 // Perform deduction on the element types.
2252 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2253 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2254 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2255 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2257 return Result;
2258
2259 // Perform deduction on the vector size, if we can.
2261 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2262 if (!NTTP)
2264
2265 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2266 ArgSize = VA->getNumElements();
2267 // Note that we use the "array bound" rules here; just like in that
2268 // case, we don't have any particular type for the vector size, but
2269 // we can provide one if necessary.
2271 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2272 Info, POK != PartialOrderingKind::None, Deduced,
2273 HasDeducedAnyParam);
2274 }
2275
2276 if (const auto *VA = A->getAs<DependentVectorType>()) {
2277 // Perform deduction on the element types.
2278 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2279 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2280 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2281 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2283 return Result;
2284
2285 // Perform deduction on the vector size, if we can.
2287 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2288 if (!NTTP)
2290
2292 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2293 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2294 }
2295
2297 }
2298
2299 // (clang extension)
2300 //
2301 // T __attribute__(((ext_vector_type(N))))
2302 case Type::DependentSizedExtVector: {
2303 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2304
2305 if (const auto *VA = A->getAs<ExtVectorType>()) {
2306 // Perform deduction on the element types.
2307 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2308 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2309 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2310 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2312 return Result;
2313
2314 // Perform deduction on the vector size, if we can.
2316 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2317 if (!NTTP)
2319
2320 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2321 ArgSize = VA->getNumElements();
2322 // Note that we use the "array bound" rules here; just like in that
2323 // case, we don't have any particular type for the vector size, but
2324 // we can provide one if necessary.
2326 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2327 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2328 }
2329
2330 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2331 // Perform deduction on the element types.
2332 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2333 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2334 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2335 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2337 return Result;
2338
2339 // Perform deduction on the vector size, if we can.
2341 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2342 if (!NTTP)
2344
2346 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2347 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2348 }
2349
2351 }
2352
2353 // (clang extension)
2354 //
2355 // T __attribute__((matrix_type(<integral constant>,
2356 // <integral constant>)))
2357 case Type::ConstantMatrix: {
2358 const auto *MP = P->castAs<ConstantMatrixType>(),
2359 *MA = A->getAs<ConstantMatrixType>();
2360 if (!MA)
2362
2363 // Check that the dimensions are the same
2364 if (MP->getNumRows() != MA->getNumRows() ||
2365 MP->getNumColumns() != MA->getNumColumns()) {
2367 }
2368 // Perform deduction on element types.
2370 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2372 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2373 }
2374
2375 case Type::DependentSizedMatrix: {
2376 const auto *MP = P->castAs<DependentSizedMatrixType>();
2377 const auto *MA = A->getAs<MatrixType>();
2378 if (!MA)
2380
2381 // Check the element type of the matrixes.
2382 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2383 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2384 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2385 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2387 return Result;
2388
2389 // Try to deduce a matrix dimension.
2390 auto DeduceMatrixArg =
2391 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2392 Expr *ParamExpr, const MatrixType *A,
2393 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2394 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2395 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2396 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2397 if (!ParamExpr->isValueDependent()) {
2398 std::optional<llvm::APSInt> ParamConst =
2399 ParamExpr->getIntegerConstantExpr(S.Context);
2400 if (!ParamConst)
2402
2403 if (ACM) {
2404 if ((ACM->*GetArgDimension)() == *ParamConst)
2407 }
2408
2409 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2410 if (std::optional<llvm::APSInt> ArgConst =
2411 ArgExpr->getIntegerConstantExpr(S.Context))
2412 if (*ArgConst == *ParamConst)
2415 }
2416
2418 getDeducedNTTParameterFromExpr(Info, ParamExpr);
2419 if (!NTTP)
2421
2422 if (ACM) {
2423 llvm::APSInt ArgConst(
2425 ArgConst = (ACM->*GetArgDimension)();
2427 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2428 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2429 Deduced, HasDeducedAnyParam);
2430 }
2431
2433 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2434 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2435 };
2436
2437 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2441 return Result;
2442
2443 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2446 }
2447
2448 // (clang extension)
2449 //
2450 // T __attribute__(((address_space(N))))
2451 case Type::DependentAddressSpace: {
2452 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2453
2454 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2455 // Perform deduction on the pointer type.
2456 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2457 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2458 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2459 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2461 return Result;
2462
2463 // Perform deduction on the address space, if we can.
2465 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2466 if (!NTTP)
2468
2470 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2471 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2472 }
2473
2475 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2476 false);
2477 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2478
2479 // Perform deduction on the pointer types.
2480 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2481 S, TemplateParams, ASP->getPointeeType(),
2482 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2484 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2486 return Result;
2487
2488 // Perform deduction on the address space, if we can.
2490 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2491 if (!NTTP)
2493
2495 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2496 Info, POK != PartialOrderingKind::None, Deduced,
2497 HasDeducedAnyParam);
2498 }
2499
2501 }
2502 case Type::DependentBitInt: {
2503 const auto *IP = P->castAs<DependentBitIntType>();
2504
2505 if (const auto *IA = A->getAs<BitIntType>()) {
2506 if (IP->isUnsigned() != IA->isUnsigned())
2508
2510 getDeducedNTTParameterFromExpr(Info, IP->getNumBitsExpr());
2511 if (!NTTP)
2513
2514 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2515 ArgSize = IA->getNumBits();
2516
2518 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2519 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2520 }
2521
2522 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2523 if (IP->isUnsigned() != IA->isUnsigned())
2526 }
2527
2529 }
2530
2531 case Type::TypeOfExpr:
2532 case Type::TypeOf:
2533 case Type::DependentName:
2534 case Type::UnresolvedUsing:
2535 case Type::Decltype:
2536 case Type::UnaryTransform:
2537 case Type::DeducedTemplateSpecialization:
2538 case Type::PackExpansion:
2539 case Type::Pipe:
2540 case Type::ArrayParameter:
2541 case Type::HLSLAttributedResource:
2542 case Type::HLSLInlineSpirv:
2543 case Type::OverflowBehavior:
2544 // No template argument deduction for these types
2546
2547 case Type::PackIndexing: {
2548 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2549 if (PIT->hasSelectedType()) {
2551 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2553 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2554 }
2556 }
2557 }
2558
2559 llvm_unreachable("Invalid Type Class!");
2560}
2561
2567 bool *HasDeducedAnyParam) {
2568 // If the template argument is a pack expansion, perform template argument
2569 // deduction against the pattern of that expansion. This only occurs during
2570 // partial ordering.
2571 if (A.isPackExpansion())
2573
2574 switch (P.getKind()) {
2576 llvm_unreachable("Null template argument in parameter list");
2577
2581 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2584 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2585 Info.FirstArg = P;
2586 Info.SecondArg = A;
2588
2590 // PartialOrdering does not matter here, since template specializations are
2591 // not being deduced.
2594 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2595 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2596 HasDeducedAnyParam);
2597 Info.FirstArg = P;
2598 Info.SecondArg = A;
2600
2602 llvm_unreachable("caller should handle pack expansions");
2603
2608
2609 Info.FirstArg = P;
2610 Info.SecondArg = A;
2612
2614 // 'nullptr' has only one possible value, so it always matches.
2617 Info.FirstArg = P;
2618 Info.SecondArg = A;
2620
2623 if (llvm::APSInt::isSameValue(P.getAsIntegral(), A.getAsIntegral()))
2625 }
2626 Info.FirstArg = P;
2627 Info.SecondArg = A;
2629
2631 // FIXME: structural equality will also compare types,
2632 // but they should match iff they have the same value.
2634 A.structurallyEquals(P))
2636
2637 Info.FirstArg = P;
2638 Info.SecondArg = A;
2640
2644 switch (A.getKind()) {
2646 // The type of the value is the type of the expression as written.
2648 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2650 PartialOrdering, Deduced, HasDeducedAnyParam);
2651 }
2655 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2657 HasDeducedAnyParam);
2658
2661 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2662 Deduced, HasDeducedAnyParam);
2663
2666 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2667 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2668
2674 Info.FirstArg = P;
2675 Info.SecondArg = A;
2677 }
2678 llvm_unreachable("Unknown template argument kind");
2679 }
2680 // Can't deduce anything, but that's okay.
2683 llvm_unreachable("Argument packs should be expanded by the caller!");
2684 }
2685
2686 llvm_unreachable("Invalid TemplateArgument Kind!");
2687}
2688
2689/// Determine whether there is a template argument to be used for
2690/// deduction.
2691///
2692/// This routine "expands" argument packs in-place, overriding its input
2693/// parameters so that \c Args[ArgIdx] will be the available template argument.
2694///
2695/// \returns true if there is another template argument (which will be at
2696/// \c Args[ArgIdx]), false otherwise.
2698 unsigned &ArgIdx) {
2699 if (ArgIdx == Args.size())
2700 return false;
2701
2702 const TemplateArgument &Arg = Args[ArgIdx];
2703 if (Arg.getKind() != TemplateArgument::Pack)
2704 return true;
2705
2706 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2707 Args = Arg.pack_elements();
2708 ArgIdx = 0;
2709 return ArgIdx < Args.size();
2710}
2711
2712/// Determine whether the given set of template arguments has a pack
2713/// expansion that is not the last template argument.
2715 bool FoundPackExpansion = false;
2716 for (const auto &A : Args) {
2717 if (FoundPackExpansion)
2718 return true;
2719
2720 if (A.getKind() == TemplateArgument::Pack)
2721 return hasPackExpansionBeforeEnd(A.pack_elements());
2722
2723 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2724 // templates, it should not be treated as a pack expansion.
2725 if (A.isPackExpansion())
2726 FoundPackExpansion = true;
2727 }
2728
2729 return false;
2730}
2731
2738 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2739 PackFold PackFold, bool *HasDeducedAnyParam) {
2740 bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
2742 FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
2744
2745 // C++0x [temp.deduct.type]p9:
2746 // If the template argument list of P contains a pack expansion that is not
2747 // the last template argument, the entire template argument list is a
2748 // non-deduced context.
2749 if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
2751
2752 // C++0x [temp.deduct.type]p9:
2753 // If P has a form that contains <T> or <i>, then each argument Pi of the
2754 // respective template argument list P is compared with the corresponding
2755 // argument Ai of the corresponding template argument list of A.
2756 for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
2758 return !FoldPackParameter && hasTemplateArgumentForDeduction(As, ArgIdx)
2761
2762 if (!Ps[ParamIdx].isPackExpansion()) {
2763 // The simple case: deduce template arguments by matching Pi and Ai.
2764
2765 // Check whether we have enough arguments.
2766 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2767 return !FoldPackArgument && NumberOfArgumentsMustMatch
2770
2771 if (As[ArgIdx].isPackExpansion()) {
2772 // C++1z [temp.deduct.type]p9:
2773 // During partial ordering, if Ai was originally a pack expansion
2774 // [and] Pi is not a pack expansion, template argument deduction
2775 // fails.
2776 if (!FoldPackArgument)
2778
2779 TemplateArgument Pattern = As[ArgIdx].getPackExpansionPattern();
2780 for (;;) {
2781 // Deduce template parameters from the pattern.
2782 if (auto Result = DeduceTemplateArguments(
2783 S, TemplateParams, Ps[ParamIdx], Pattern, Info,
2784 PartialOrdering, Deduced, HasDeducedAnyParam);
2786 return Result;
2787
2788 ++ParamIdx;
2791 if (Ps[ParamIdx].isPackExpansion())
2792 break;
2793 }
2794 } else {
2795 // Perform deduction for this Pi/Ai pair.
2796 if (auto Result = DeduceTemplateArguments(
2797 S, TemplateParams, Ps[ParamIdx], As[ArgIdx], Info,
2798 PartialOrdering, Deduced, HasDeducedAnyParam);
2800 return Result;
2801
2802 ++ArgIdx;
2803 ++ParamIdx;
2804 continue;
2805 }
2806 }
2807
2808 // The parameter is a pack expansion.
2809
2810 // C++0x [temp.deduct.type]p9:
2811 // If Pi is a pack expansion, then the pattern of Pi is compared with
2812 // each remaining argument in the template argument list of A. Each
2813 // comparison deduces template arguments for subsequent positions in the
2814 // template parameter packs expanded by Pi.
2815 TemplateArgument Pattern = Ps[ParamIdx].getPackExpansionPattern();
2816
2817 // Prepare to deduce the packs within the pattern.
2818 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2819
2820 // Keep track of the deduced template arguments for each parameter pack
2821 // expanded by this pack expansion (the outer index) and for each
2822 // template argument (the inner SmallVectors).
2823 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2824 PackScope.hasNextElement();
2825 ++ArgIdx) {
2826 if (!As[ArgIdx].isPackExpansion()) {
2827 if (!FoldPackParameter)
2829 if (FoldPackArgument)
2830 Info.setStrictPackMatch();
2831 }
2832 // Deduce template arguments from the pattern.
2833 if (auto Result = DeduceTemplateArguments(
2834 S, TemplateParams, Pattern, As[ArgIdx], Info, PartialOrdering,
2835 Deduced, HasDeducedAnyParam);
2837 return Result;
2838
2839 PackScope.nextPackElement();
2840 }
2841
2842 // Build argument packs for each of the parameter packs expanded by this
2843 // pack expansion.
2844 return PackScope.finish();
2845 }
2846}
2847
2852 bool NumberOfArgumentsMustMatch) {
2853 return ::DeduceTemplateArguments(
2854 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2855 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2856 /*HasDeducedAnyParam=*/nullptr);
2857}
2858
2861 QualType NTTPType, SourceLocation Loc,
2863 switch (Arg.getKind()) {
2865 llvm_unreachable("Can't get a NULL template argument here");
2866
2868 return TemplateArgumentLoc(
2869 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2870
2872 if (NTTPType.isNull())
2873 NTTPType = Arg.getParamTypeForDecl();
2874 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc,
2876 .getAs<Expr>();
2877 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2878 }
2879
2881 if (NTTPType.isNull())
2882 NTTPType = Arg.getNullPtrType();
2883 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2884 .getAs<Expr>();
2885 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2886 E);
2887 }
2888
2892 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2893 }
2894
2899 Builder.MakeTrivial(Context, Template.getQualifier(), Loc);
2900 return TemplateArgumentLoc(
2901 Context, Arg, Loc, Builder.getWithLocInContext(Context), Loc,
2902 /*EllipsisLoc=*/Arg.getKind() == TemplateArgument::TemplateExpansion
2903 ? Loc
2904 : SourceLocation());
2905 }
2906
2908 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2909
2912 }
2913
2914 llvm_unreachable("Invalid TemplateArgument Kind!");
2915}
2916
2919 SourceLocation Location) {
2921 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2922}
2923
2924/// Convert the given deduced template argument and add it to the set of
2925/// fully-converted template arguments.
2926static bool
2929 TemplateDeductionInfo &Info, bool IsDeduced,
2931 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2932 unsigned ArgumentPackIndex) {
2933 // Convert the deduced template argument into a template
2934 // argument that we can check, almost as if the user had written
2935 // the template argument explicitly.
2937 Arg, QualType(), Info.getLocation(), Param);
2938
2939 SaveAndRestore _1(CTAI.MatchingTTP, false);
2940 SaveAndRestore _2(CTAI.StrictPackMatch, false);
2941 // Check the template argument, converting it as necessary.
2942 auto Res = S.CheckTemplateArgument(
2943 Param, ArgLoc, Template, Template->getLocation(),
2944 Template->getSourceRange().getEnd(), ArgumentPackIndex, CTAI,
2945 IsDeduced
2949 if (CTAI.StrictPackMatch)
2950 Info.setStrictPackMatch();
2951 return Res;
2952 };
2953
2954 if (Arg.getKind() == TemplateArgument::Pack) {
2955 // This is a template argument pack, so check each of its arguments against
2956 // the template parameter.
2957 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2958 CanonicalPackedArgsBuilder;
2959 for (const auto &P : Arg.pack_elements()) {
2960 // When converting the deduced template argument, append it to the
2961 // general output list. We need to do this so that the template argument
2962 // checking logic has all of the prior template arguments available.
2963 DeducedTemplateArgument InnerArg(P);
2965 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2966 "deduced nested pack");
2967 if (P.isNull()) {
2968 // We deduced arguments for some elements of this pack, but not for
2969 // all of them. This happens if we get a conditionally-non-deduced
2970 // context in a pack expansion (such as an overload set in one of the
2971 // arguments).
2972 S.Diag(Param->getLocation(),
2973 diag::err_template_arg_deduced_incomplete_pack)
2974 << Arg << Param;
2975 return true;
2976 }
2977 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2978 return true;
2979
2980 // Move the converted template argument into our argument pack.
2981 SugaredPackedArgsBuilder.push_back(CTAI.SugaredConverted.pop_back_val());
2982 CanonicalPackedArgsBuilder.push_back(
2983 CTAI.CanonicalConverted.pop_back_val());
2984 }
2985
2986 // If the pack is empty, we still need to substitute into the parameter
2987 // itself, in case that substitution fails.
2988 if (SugaredPackedArgsBuilder.empty()) {
2991 /*Final=*/true);
2992 Sema::ArgPackSubstIndexRAII OnlySubstNonPackExpansion(S, std::nullopt);
2993
2994 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2995 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2996 NTTP, CTAI.SugaredConverted,
2997 Template->getSourceRange());
2998 if (Inst.isInvalid() ||
2999 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
3000 NTTP->getDeclName()).isNull())
3001 return true;
3002 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3003 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3004 TTP, CTAI.SugaredConverted,
3005 Template->getSourceRange());
3006 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
3007 return true;
3008 }
3009 // For type parameters, no substitution is ever required.
3010 }
3011
3012 // Create the resulting argument pack.
3013 CTAI.SugaredConverted.push_back(
3014 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
3016 S.Context, CanonicalPackedArgsBuilder));
3017 return false;
3018 }
3019
3020 return ConvertArg(Arg, 0);
3021}
3022
3023/// \param IsIncomplete When used, we only consider template parameters that
3024/// were deduced, disregarding any default arguments. After the function
3025/// finishes, the object pointed at will contain a value indicating if the
3026/// conversion was actually incomplete.
3028 Sema &S, NamedDecl *Template, TemplateParameterList *TemplateParams,
3031 LocalInstantiationScope *CurrentInstantiationScope,
3032 unsigned NumAlreadyConverted, bool *IsIncomplete) {
3033 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3034 NamedDecl *Param = TemplateParams->getParam(I);
3035
3036 // C++0x [temp.arg.explicit]p3:
3037 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3038 // be deduced to an empty sequence of template arguments.
3039 // FIXME: Where did the word "trailing" come from?
3040 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3041 if (auto Result =
3042 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3044 return Result;
3045 }
3046
3047 if (!Deduced[I].isNull()) {
3048 if (I < NumAlreadyConverted) {
3049 // We may have had explicitly-specified template arguments for a
3050 // template parameter pack (that may or may not have been extended
3051 // via additional deduced arguments).
3052 if (Param->isParameterPack() && CurrentInstantiationScope &&
3053 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3054 // Forget the partially-substituted pack; its substitution is now
3055 // complete.
3056 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3057 // We still need to check the argument in case it was extended by
3058 // deduction.
3059 } else {
3060 // We have already fully type-checked and converted this
3061 // argument, because it was explicitly-specified. Just record the
3062 // presence of this argument.
3063 CTAI.SugaredConverted.push_back(Deduced[I]);
3064 CTAI.CanonicalConverted.push_back(
3066 continue;
3067 }
3068 }
3069
3070 // We may have deduced this argument, so it still needs to be
3071 // checked and converted.
3072 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3073 IsDeduced, CTAI)) {
3074 Info.Param = makeTemplateParameter(Param);
3075 // FIXME: These template arguments are temporary. Free them!
3076 Info.reset(
3079 CTAI.CanonicalConverted));
3081 }
3082
3083 continue;
3084 }
3085
3086 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3087 // template parameters to remain not deduced. As a provisional fix for a
3088 // core issue that does not exist yet, which may be related to CWG2160, only
3089 // consider template parameters that were deduced, disregarding any default
3090 // arguments.
3091 if (IsIncomplete) {
3092 *IsIncomplete = true;
3093 CTAI.SugaredConverted.push_back({});
3094 CTAI.CanonicalConverted.push_back({});
3095 continue;
3096 }
3097
3098 // Substitute into the default template argument, if available.
3099 bool HasDefaultArg = false;
3100 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3101 if (!TD) {
3105 }
3106
3107 TemplateArgumentLoc DefArg;
3108 {
3109 Qualifiers ThisTypeQuals;
3110 CXXRecordDecl *ThisContext = nullptr;
3111 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3112 if (Rec->isLambda())
3113 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3114 ThisContext = Method->getParent();
3115 ThisTypeQuals = Method->getMethodQualifiers();
3116 }
3117
3118 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3119 S.getLangOpts().CPlusPlus17);
3120
3122 TD, /*TemplateKWLoc=*/SourceLocation(), TD->getLocation(),
3123 TD->getSourceRange().getEnd(), Param, CTAI.SugaredConverted,
3124 CTAI.CanonicalConverted, HasDefaultArg);
3125 }
3126
3127 // If there was no default argument, deduction is incomplete.
3128 if (DefArg.getArgument().isNull()) {
3129 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3130 Info.reset(
3133
3136 }
3137
3138 SaveAndRestore _1(CTAI.PartialOrdering, false);
3139 SaveAndRestore _2(CTAI.MatchingTTP, false);
3140 SaveAndRestore _3(CTAI.StrictPackMatch, false);
3141 // Check whether we can actually use the default argument.
3143 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3144 /*ArgumentPackIndex=*/0, CTAI, Sema::CTAK_Specified)) {
3145 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3146 // FIXME: These template arguments are temporary. Free them!
3147 Info.reset(
3151 }
3152
3153 // If we get here, we successfully used the default template argument.
3154 }
3155
3157}
3158
3160 if (auto *DC = dyn_cast<DeclContext>(D))
3161 return DC;
3162 return D->getDeclContext();
3163}
3164
3165template<typename T> struct IsPartialSpecialization {
3166 static constexpr bool value = false;
3167};
3168template<>
3172template<>
3174 static constexpr bool value = true;
3175};
3176
3179 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3180 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3181 TemplateDeductionInfo &Info) {
3182 llvm::SmallVector<AssociatedConstraint, 3> AssociatedConstraints;
3183 bool DeducedArgsNeedReplacement = false;
3184 if (auto *TD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Template)) {
3185 TD->getAssociatedConstraints(AssociatedConstraints);
3186 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3187 } else if (auto *TD =
3188 dyn_cast<VarTemplatePartialSpecializationDecl>(Template)) {
3189 TD->getAssociatedConstraints(AssociatedConstraints);
3190 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3191 } else {
3192 cast<TemplateDecl>(Template)->getAssociatedConstraints(
3193 AssociatedConstraints);
3194 }
3195
3196 std::optional<ArrayRef<TemplateArgument>> Innermost;
3197 // If we don't need to replace the deduced template arguments,
3198 // we can add them immediately as the inner-most argument list.
3199 if (!DeducedArgsNeedReplacement)
3200 Innermost = SugaredDeducedArgs;
3201
3203 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3204 /*RelativeToPrimary=*/true, /*Pattern=*/
3205 nullptr, /*ForConstraintInstantiation=*/true);
3206
3207 // getTemplateInstantiationArgs picks up the non-deduced version of the
3208 // template args when this is a variable template partial specialization and
3209 // not class-scope explicit specialization, so replace with Deduced Args
3210 // instead of adding to inner-most.
3211 if (!Innermost)
3212 MLTAL.replaceInnermostTemplateArguments(Template, SugaredDeducedArgs);
3213
3214 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3215 Info.getLocation(),
3218 Info.reset(
3219 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3220 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3222 }
3224}
3225
3226/// Complete template argument deduction.
3228 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3232 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3233 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Entity));
3234
3235 // C++ [temp.deduct.type]p2:
3236 // [...] or if any template argument remains neither deduced nor
3237 // explicitly specified, template argument deduction fails.
3239 if (auto Result = ConvertDeducedTemplateArguments(
3240 S, Entity, EntityTPL, /*IsDeduced=*/PartialOrdering, Deduced, Info,
3241 CTAI,
3242 /*CurrentInstantiationScope=*/nullptr,
3243 /*NumAlreadyConverted=*/0U, /*IsIncomplete=*/nullptr);
3245 return Result;
3246
3247 if (CopyDeducedArgs) {
3248 // Form the template argument list from the deduced template arguments.
3249 TemplateArgumentList *SugaredDeducedArgumentList =
3251 TemplateArgumentList *CanonicalDeducedArgumentList =
3253 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3254 }
3255
3256 TemplateParameterList *TPL = Template->getTemplateParameters();
3257 TemplateArgumentListInfo InstArgs(TPL->getLAngleLoc(), TPL->getRAngleLoc());
3259 /*Final=*/true);
3260 MLTAL.addOuterRetainedLevels(TPL->getDepth());
3261
3262 if (S.SubstTemplateArguments(Ps, MLTAL, InstArgs)) {
3263 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3264 if (ParamIdx >= TPL->size())
3265 ParamIdx = TPL->size() - 1;
3266
3267 Decl *Param = TPL->getParam(ParamIdx);
3268 Info.Param = makeTemplateParameter(Param);
3269 Info.FirstArg = Ps[ArgIdx].getArgument();
3271 }
3272
3275 if (S.CheckTemplateArgumentList(Template, Template->getLocation(), InstArgs,
3276 /*DefaultArgs=*/{}, false, InstCTAI,
3277 /*UpdateArgsWithConversions=*/true,
3282
3283 // Check that we produced the correct argument list.
3285 AsStack{As};
3286 for (;;) {
3287 auto take = [](SmallVectorImpl<ArrayRef<TemplateArgument>> &Stack)
3289 while (!Stack.empty()) {
3290 auto &Xs = Stack.back();
3291 if (Xs.empty()) {
3292 Stack.pop_back();
3293 continue;
3294 }
3295 auto &X = Xs.front();
3296 if (X.getKind() == TemplateArgument::Pack) {
3297 Stack.emplace_back(X.getPackAsArray());
3298 Xs = Xs.drop_front();
3299 continue;
3300 }
3301 assert(!X.isNull());
3302 return {Xs, X};
3303 }
3304 static constexpr ArrayRef<TemplateArgument> None;
3305 return {const_cast<ArrayRef<TemplateArgument> &>(None),
3307 };
3308 auto [Ps, P] = take(PsStack);
3309 auto [As, A] = take(AsStack);
3310 if (P.isNull() && A.isNull())
3311 break;
3312 TemplateArgument PP = P.isPackExpansion() ? P.getPackExpansionPattern() : P,
3313 PA = A.isPackExpansion() ? A.getPackExpansionPattern() : A;
3314 if (!S.Context.isSameTemplateArgument(PP, PA)) {
3315 if (!P.isPackExpansion() && !A.isPackExpansion()) {
3317 (AsStack.empty() ? As.end() : AsStack.back().begin()) -
3318 As.begin()));
3319 Info.FirstArg = P;
3320 Info.SecondArg = A;
3322 }
3323 if (P.isPackExpansion()) {
3324 Ps = Ps.drop_front();
3325 continue;
3326 }
3327 if (A.isPackExpansion()) {
3328 As = As.drop_front();
3329 continue;
3330 }
3331 }
3332 Ps = Ps.drop_front(P.isPackExpansion() ? 0 : 1);
3333 As = As.drop_front(A.isPackExpansion() && !P.isPackExpansion() ? 0 : 1);
3334 }
3335 assert(PsStack.empty());
3336 assert(AsStack.empty());
3337
3338 if (!PartialOrdering) {
3339 if (auto Result = CheckDeducedArgumentConstraints(
3340 S, Entity, CTAI.SugaredConverted, CTAI.CanonicalConverted, Info);
3342 return Result;
3343 }
3344
3346}
3348 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3352 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3353 TemplateParameterList *TPL = Template->getTemplateParameters();
3354 SmallVector<TemplateArgumentLoc, 8> PsLoc(Ps.size());
3355 for (unsigned I = 0, N = Ps.size(); I != N; ++I)
3356 PsLoc[I] = S.getTrivialTemplateArgumentLoc(Ps[I], QualType(),
3357 TPL->getParam(I)->getLocation());
3358 return FinishTemplateArgumentDeduction(S, Entity, EntityTPL, Template,
3359 PartialOrdering, PsLoc, As, Deduced,
3360 Info, CopyDeducedArgs);
3361}
3362
3363/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3364/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3365/// the three implementations.
3367 Sema &S, TemplateDecl *TD,
3369 TemplateDeductionInfo &Info) {
3371
3372 // C++ [temp.deduct.type]p2:
3373 // [...] or if any template argument remains neither deduced nor
3374 // explicitly specified, template argument deduction fails.
3376 if (auto Result = ConvertDeducedTemplateArguments(
3377 S, TD, TD->getTemplateParameters(), /*IsDeduced=*/false, Deduced,
3378 Info, CTAI,
3379 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3380 /*IsIncomplete=*/nullptr);
3382 return Result;
3383
3384 return ::CheckDeducedArgumentConstraints(S, TD, CTAI.SugaredConverted,
3385 CTAI.CanonicalConverted, Info);
3386}
3387
3388/// Perform template argument deduction to determine whether the given template
3389/// arguments match the given class or variable template partial specialization
3390/// per C++ [temp.class.spec.match].
3391template <typename T>
3392static std::enable_if_t<IsPartialSpecialization<T>::value,
3395 ArrayRef<TemplateArgument> TemplateArgs,
3396 TemplateDeductionInfo &Info) {
3397 if (Partial->isInvalidDecl())
3399
3400 // C++ [temp.class.spec.match]p2:
3401 // A partial specialization matches a given actual template
3402 // argument list if the template arguments of the partial
3403 // specialization can be deduced from the actual template argument
3404 // list (14.8.2).
3405
3406 // Unevaluated SFINAE context.
3409 Sema::SFINAETrap Trap(S, Info);
3410
3411 // This deduction has no relation to any outer instantiation we might be
3412 // performing.
3413 LocalInstantiationScope InstantiationScope(S);
3414
3416 Deduced.resize(Partial->getTemplateParameters()->size());
3418 S, Partial->getTemplateParameters(),
3419 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3420 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3422 /*HasDeducedAnyParam=*/nullptr);
3424 return Result;
3425
3426 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3427 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs);
3428 if (Inst.isInvalid())
3430
3433 Result = ::FinishTemplateArgumentDeduction(
3434 S, Partial, Partial->getTemplateParameters(),
3435 Partial->getSpecializedTemplate(),
3436 /*IsPartialOrdering=*/false,
3437 Partial->getTemplateArgsAsWritten()->arguments(), TemplateArgs, Deduced,
3438 Info, /*CopyDeducedArgs=*/true);
3439 });
3440
3442 return Result;
3443
3444 if (Trap.hasErrorOccurred())
3446
3448}
3449
3452 ArrayRef<TemplateArgument> TemplateArgs,
3453 TemplateDeductionInfo &Info) {
3454 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3455}
3458 ArrayRef<TemplateArgument> TemplateArgs,
3459 TemplateDeductionInfo &Info) {
3460 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3461}
3462
3466 if (TD->isInvalidDecl())
3468
3469 QualType PType;
3470 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3471 // Use the InjectedClassNameType.
3472 PType = Context.getCanonicalTagType(CTD->getTemplatedDecl());
3473 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3474 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3475 } else {
3476 assert(false && "Expected a class or alias template");
3477 }
3478
3479 // Unevaluated SFINAE context.
3482 SFINAETrap Trap(*this, Info);
3483
3484 // This deduction has no relation to any outer instantiation we might be
3485 // performing.
3486 LocalInstantiationScope InstantiationScope(*this);
3487
3489 TD->getTemplateParameters()->size());
3492 if (auto DeducedResult = DeduceTemplateArguments(
3493 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3494 DeducedResult != TemplateDeductionResult::Success) {
3495 return DeducedResult;
3496 }
3497
3498 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3499 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs);
3500 if (Inst.isInvalid())
3502
3505 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3506 });
3507
3509 return Result;
3510
3511 if (Trap.hasErrorOccurred())
3513
3515}
3516
3517/// Determine whether the given type T is a simple-template-id type.
3519 if (const TemplateSpecializationType *Spec
3520 = T->getAs<TemplateSpecializationType>())
3521 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3522
3523 // C++17 [temp.local]p2:
3524 // the injected-class-name [...] is equivalent to the template-name followed
3525 // by the template-arguments of the class template specialization or partial
3526 // specialization enclosed in <>
3527 // ... which means it's equivalent to a simple-template-id.
3528 //
3529 // This only arises during class template argument deduction for a copy
3530 // deduction candidate, where it permits slicing.
3531 if (isa<InjectedClassNameType>(T.getCanonicalType()))
3532 return true;
3533
3534 return false;
3535}
3536
3539 TemplateArgumentListInfo &ExplicitTemplateArgs,
3542 TemplateDeductionInfo &Info) {
3543 assert(isSFINAEContext());
3544 assert(isUnevaluatedContext());
3545
3546 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3547 TemplateParameterList *TemplateParams
3548 = FunctionTemplate->getTemplateParameters();
3549
3550 if (ExplicitTemplateArgs.size() == 0) {
3551 // No arguments to substitute; just copy over the parameter types and
3552 // fill in the function type.
3553 for (auto *P : Function->parameters())
3554 ParamTypes.push_back(P->getType());
3555
3556 if (FunctionType)
3557 *FunctionType = Function->getType();
3559 }
3560
3561 // C++ [temp.arg.explicit]p3:
3562 // Template arguments that are present shall be specified in the
3563 // declaration order of their corresponding template-parameters. The
3564 // template argument list shall not specify more template-arguments than
3565 // there are corresponding template-parameters.
3566
3567 // Enter a new template instantiation context where we check the
3568 // explicitly-specified template arguments against this function template,
3569 // and then substitute them into the function parameter types.
3572 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3574 if (Inst.isInvalid())
3576
3579 ExplicitTemplateArgs, /*DefaultArgs=*/{},
3580 /*PartialTemplateArgs=*/true, CTAI,
3581 /*UpdateArgsWithConversions=*/false)) {
3582 unsigned Index = CTAI.SugaredConverted.size();
3583 if (Index >= TemplateParams->size())
3585 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3587 }
3588
3589 // Form the template argument list from the explicitly-specified
3590 // template arguments.
3591 TemplateArgumentList *SugaredExplicitArgumentList =
3593 TemplateArgumentList *CanonicalExplicitArgumentList =
3595 Info.setExplicitArgs(SugaredExplicitArgumentList,
3596 CanonicalExplicitArgumentList);
3597
3598 // Template argument deduction and the final substitution should be
3599 // done in the context of the templated declaration. Explicit
3600 // argument substitution, on the other hand, needs to happen in the
3601 // calling context.
3602 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3603
3604 // If we deduced template arguments for a template parameter pack,
3605 // note that the template argument pack is partially substituted and record
3606 // the explicit template arguments. They'll be used as part of deduction
3607 // for this template parameter pack.
3608 unsigned PartiallySubstitutedPackIndex = -1u;
3609 if (!CTAI.SugaredConverted.empty()) {
3610 const TemplateArgument &Arg = CTAI.SugaredConverted.back();
3611 if (Arg.getKind() == TemplateArgument::Pack) {
3612 auto *Param = TemplateParams->getParam(CTAI.SugaredConverted.size() - 1);
3613 // If this is a fully-saturated fixed-size pack, it should be
3614 // fully-substituted, not partially-substituted.
3615 UnsignedOrNone Expansions = getExpandedPackSize(Param);
3616 if (!Expansions || Arg.pack_size() < *Expansions) {
3617 PartiallySubstitutedPackIndex = CTAI.SugaredConverted.size() - 1;
3618 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3619 Param, Arg.pack_begin(), Arg.pack_size());
3620 }
3621 }
3622 }
3623
3624 const FunctionProtoType *Proto
3625 = Function->getType()->getAs<FunctionProtoType>();
3626 assert(Proto && "Function template does not have a prototype?");
3627
3628 // Isolate our substituted parameters from our caller.
3629 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3630
3631 ExtParameterInfoBuilder ExtParamInfos;
3632
3634 SugaredExplicitArgumentList->asArray(),
3635 /*Final=*/true);
3636
3637 // Instantiate the types of each of the function parameters given the
3638 // explicitly-specified template arguments. If the function has a trailing
3639 // return type, substitute it after the arguments to ensure we substitute
3640 // in lexical order.
3641 if (Proto->hasTrailingReturn()) {
3642 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3643 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3644 /*params=*/nullptr, ExtParamInfos))
3646 }
3647
3648 // Instantiate the return type.
3649 QualType ResultType;
3650 {
3651 // C++11 [expr.prim.general]p3:
3652 // If a declaration declares a member function or member function
3653 // template of a class X, the expression this is a prvalue of type
3654 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3655 // and the end of the function-definition, member-declarator, or
3656 // declarator.
3657 Qualifiers ThisTypeQuals;
3658 CXXRecordDecl *ThisContext = nullptr;
3659 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3660 ThisContext = Method->getParent();
3661 ThisTypeQuals = Method->getMethodQualifiers();
3662 }
3663
3664 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3666
3667 ResultType =
3668 SubstType(Proto->getReturnType(), MLTAL,
3669 Function->getTypeSpecStartLoc(), Function->getDeclName());
3670 if (ResultType.isNull())
3672 // CUDA: Kernel function must have 'void' return type.
3673 if (getLangOpts().CUDA)
3674 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3675 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3676 << Function->getType() << Function->getSourceRange();
3678 }
3679 }
3680
3681 // Instantiate the types of each of the function parameters given the
3682 // explicitly-specified template arguments if we didn't do so earlier.
3683 if (!Proto->hasTrailingReturn() &&
3684 SubstParmTypes(Function->getLocation(), Function->parameters(),
3685 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3686 /*params*/ nullptr, ExtParamInfos))
3688
3689 if (FunctionType) {
3690 auto EPI = Proto->getExtProtoInfo();
3691 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3692 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3693 Function->getLocation(),
3694 Function->getDeclName(),
3695 EPI);
3696 if (FunctionType->isNull())
3698 }
3699
3700 // C++ [temp.arg.explicit]p2:
3701 // Trailing template arguments that can be deduced (14.8.2) may be
3702 // omitted from the list of explicit template-arguments. If all of the
3703 // template arguments can be deduced, they may all be omitted; in this
3704 // case, the empty template argument list <> itself may also be omitted.
3705 //
3706 // Take all of the explicitly-specified arguments and put them into
3707 // the set of deduced template arguments. The partially-substituted
3708 // parameter pack, however, will be set to NULL since the deduction
3709 // mechanism handles the partially-substituted argument pack directly.
3710 Deduced.reserve(TemplateParams->size());
3711 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3712 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3713 if (I == PartiallySubstitutedPackIndex)
3714 Deduced.push_back(DeducedTemplateArgument());
3715 else
3716 Deduced.push_back(Arg);
3717 }
3718
3720}
3721
3722/// Check whether the deduced argument type for a call to a function
3723/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3726 Sema::OriginalCallArg OriginalArg,
3727 QualType DeducedA) {
3728 ASTContext &Context = S.Context;
3729
3730 auto Failed = [&]() -> TemplateDeductionResult {
3731 Info.FirstArg = TemplateArgument(DeducedA);
3732 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3733 Info.CallArgIndex = OriginalArg.ArgIdx;
3734 return OriginalArg.DecomposedParam
3737 };
3738
3739 QualType A = OriginalArg.OriginalArgType;
3740 QualType OriginalParamType = OriginalArg.OriginalParamType;
3741
3742 // Check for type equality (top-level cv-qualifiers are ignored).
3743 if (Context.hasSameUnqualifiedType(A, DeducedA))
3745
3746 // Strip off references on the argument types; they aren't needed for
3747 // the following checks.
3748 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3749 DeducedA = DeducedARef->getPointeeType();
3750 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3751 A = ARef->getPointeeType();
3752
3753 // C++ [temp.deduct.call]p4:
3754 // [...] However, there are three cases that allow a difference:
3755 // - If the original P is a reference type, the deduced A (i.e., the
3756 // type referred to by the reference) can be more cv-qualified than
3757 // the transformed A.
3758 if (const ReferenceType *OriginalParamRef
3759 = OriginalParamType->getAs<ReferenceType>()) {
3760 // We don't want to keep the reference around any more.
3761 OriginalParamType = OriginalParamRef->getPointeeType();
3762
3763 // FIXME: Resolve core issue (no number yet): if the original P is a
3764 // reference type and the transformed A is function type "noexcept F",
3765 // the deduced A can be F.
3766 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA))
3768
3769 Qualifiers AQuals = A.getQualifiers();
3770 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3771
3772 // Under Objective-C++ ARC, the deduced type may have implicitly
3773 // been given strong or (when dealing with a const reference)
3774 // unsafe_unretained lifetime. If so, update the original
3775 // qualifiers to include this lifetime.
3776 if (S.getLangOpts().ObjCAutoRefCount &&
3777 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3779 (DeducedAQuals.hasConst() &&
3780 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3781 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3782 }
3783
3784 if (AQuals == DeducedAQuals) {
3785 // Qualifiers match; there's nothing to do.
3786 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3787 return Failed();
3788 } else {
3789 // Qualifiers are compatible, so have the argument type adopt the
3790 // deduced argument type's qualifiers as if we had performed the
3791 // qualification conversion.
3792 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3793 }
3794 }
3795
3796 // - The transformed A can be another pointer or pointer to member
3797 // type that can be converted to the deduced A via a function pointer
3798 // conversion and/or a qualification conversion.
3799 //
3800 // Also allow conversions which merely strip __attribute__((noreturn)) from
3801 // function types (recursively).
3802 bool ObjCLifetimeConversion = false;
3803 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3804 (S.IsQualificationConversion(A, DeducedA, false,
3805 ObjCLifetimeConversion) ||
3806 S.IsFunctionConversion(A, DeducedA)))
3808
3809 // - If P is a class and P has the form simple-template-id, then the
3810 // transformed A can be a derived class of the deduced A. [...]
3811 // [...] Likewise, if P is a pointer to a class of the form
3812 // simple-template-id, the transformed A can be a pointer to a
3813 // derived class pointed to by the deduced A.
3814 if (const PointerType *OriginalParamPtr
3815 = OriginalParamType->getAs<PointerType>()) {
3816 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3817 if (const PointerType *APtr = A->getAs<PointerType>()) {
3818 if (A->getPointeeType()->isRecordType()) {
3819 OriginalParamType = OriginalParamPtr->getPointeeType();
3820 DeducedA = DeducedAPtr->getPointeeType();
3821 A = APtr->getPointeeType();
3822 }
3823 }
3824 }
3825 }
3826
3827 if (Context.hasSameUnqualifiedType(A, DeducedA))
3829
3830 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3831 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3833
3834 return Failed();
3835}
3836
3837/// Find the pack index for a particular parameter index in an instantiation of
3838/// a function template with specific arguments.
3839///
3840/// \return The pack index for whichever pack produced this parameter, or -1
3841/// if this was not produced by a parameter. Intended to be used as the
3842/// ArgumentPackSubstitutionIndex for further substitutions.
3843// FIXME: We should track this in OriginalCallArgs so we don't need to
3844// reconstruct it here.
3845static UnsignedOrNone
3848 unsigned ParamIdx) {
3849 unsigned Idx = 0;
3850 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3851 if (PD->isParameterPack()) {
3852 UnsignedOrNone NumArgs =
3853 S.getNumArgumentsInExpansion(PD->getType(), Args);
3854 unsigned NumExpansions = NumArgs ? *NumArgs : 1;
3855 if (Idx + NumExpansions > ParamIdx)
3856 return ParamIdx - Idx;
3857 Idx += NumExpansions;
3858 } else {
3859 if (Idx == ParamIdx)
3860 return std::nullopt; // Not a pack expansion
3861 ++Idx;
3862 }
3863 }
3864
3865 llvm_unreachable("parameter index would not be produced from template");
3866}
3867
3868// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3869// we'll try to instantiate and update its explicit specifier after constraint
3870// checking.
3873 const MultiLevelTemplateArgumentList &SubstArgs,
3875 ArrayRef<TemplateArgument> DeducedArgs) {
3876 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3877 return isa<CXXConstructorDecl>(D)
3878 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3879 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3880 };
3881 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3883 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3884 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3885 };
3886
3887 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3888 Expr *ExplicitExpr = ES.getExpr();
3889 if (!ExplicitExpr)
3891 if (!ExplicitExpr->isValueDependent())
3893
3894 // By this point, FinishTemplateArgumentDeduction will have been reverted back
3895 // to a regular non-SFINAE template instantiation context, so setup a new
3896 // SFINAE context.
3898 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3900 if (Inst.isInvalid())
3902 Sema::SFINAETrap Trap(S, Info);
3903 const ExplicitSpecifier InstantiatedES =
3904 S.instantiateExplicitSpecifier(SubstArgs, ES);
3905 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3906 Specialization->setInvalidDecl(true);
3908 }
3909 SetExplicitSpecifier(Specialization, InstantiatedES);
3911}
3912
3916 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3918 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3919 bool PartialOverloading, bool PartialOrdering,
3920 bool ForOverloadSetAddressResolution,
3921 llvm::function_ref<bool(bool)> CheckNonDependent) {
3922 // Enter a new template instantiation context while we instantiate the
3923 // actual function declaration.
3924 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3926 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3928 if (Inst.isInvalid())
3930
3931 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3932
3933 // C++ [temp.deduct.type]p2:
3934 // [...] or if any template argument remains neither deduced nor
3935 // explicitly specified, template argument deduction fails.
3936 bool IsIncomplete = false;
3939 *this, FunctionTemplate, FunctionTemplate->getTemplateParameters(),
3940 /*IsDeduced=*/true, Deduced, Info, CTAI, CurrentInstantiationScope,
3941 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
3943 return Result;
3944
3945 // Form the template argument list from the deduced template arguments.
3946 TemplateArgumentList *SugaredDeducedArgumentList =
3948 TemplateArgumentList *CanonicalDeducedArgumentList =
3950 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3951
3952 // Substitute the deduced template arguments into the function template
3953 // declaration to produce the function template specialization.
3954 DeclContext *Owner = FunctionTemplate->getDeclContext();
3955 if (FunctionTemplate->getFriendObjectKind())
3956 Owner = FunctionTemplate->getLexicalDeclContext();
3957 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3958
3959 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/true))
3961
3962 // C++20 [temp.deduct.general]p5: [CWG2369]
3963 // If the function template has associated constraints, those constraints
3964 // are checked for satisfaction. If the constraints are not satisfied, type
3965 // deduction fails.
3966 //
3967 // FIXME: We haven't implemented CWG2369 for lambdas yet, because we need
3968 // to figure out how to instantiate lambda captures to the scope without
3969 // first instantiating the lambda.
3970 bool IsLambda = isLambdaCallOperator(FD) || isLambdaConversionOperator(FD);
3971 if (!IsLambda && !IsIncomplete) {
3973 Info.getLocation(),
3974 FunctionTemplate->getCanonicalDecl()->getTemplatedDecl(),
3981 }
3982 }
3983 // C++ [temp.deduct.call]p10: [CWG1391]
3984 // If deduction succeeds for all parameters that contain
3985 // template-parameters that participate in template argument deduction,
3986 // and all template arguments are explicitly specified, deduced, or
3987 // obtained from default template arguments, remaining parameters are then
3988 // compared with the corresponding arguments. For each remaining parameter
3989 // P with a type that was non-dependent before substitution of any
3990 // explicitly-specified template arguments, if the corresponding argument
3991 // A cannot be implicitly converted to P, deduction fails.
3992 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/false))
3994
3996 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3997 /*Final=*/false);
3998 Specialization = cast_or_null<FunctionDecl>(
3999 SubstDecl(FD, Owner, SubstArgs));
4000 if (!Specialization || Specialization->isInvalidDecl())
4002
4003 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
4005
4006 // If the template argument list is owned by the function template
4007 // specialization, release it.
4008 if (Specialization->getTemplateSpecializationArgs() ==
4009 CanonicalDeducedArgumentList)
4010 Info.takeCanonical();
4011
4012 // C++2a [temp.deduct]p5
4013 // [...] When all template arguments have been deduced [...] all uses of
4014 // template parameters [...] are replaced with the corresponding deduced
4015 // or default argument values.
4016 // [...] If the function template has associated constraints
4017 // ([temp.constr.decl]), those constraints are checked for satisfaction
4018 // ([temp.constr.constr]). If the constraints are not satisfied, type
4019 // deduction fails.
4020 if (IsLambda && !IsIncomplete) {
4025
4030 }
4031 }
4032
4033 // We skipped the instantiation of the explicit-specifier during the
4034 // substitution of `FD` before. So, we try to instantiate it back if
4035 // `Specialization` is either a constructor or a conversion function.
4039 Info, FunctionTemplate,
4040 DeducedArgs)) {
4042 }
4043 }
4044
4045 if (OriginalCallArgs) {
4046 // C++ [temp.deduct.call]p4:
4047 // In general, the deduction process attempts to find template argument
4048 // values that will make the deduced A identical to A (after the type A
4049 // is transformed as described above). [...]
4050 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4051 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4052 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4053
4054 auto ParamIdx = OriginalArg.ArgIdx;
4055 unsigned ExplicitOffset =
4056 (Specialization->hasCXXExplicitFunctionObjectParameter() &&
4057 !ForOverloadSetAddressResolution)
4058 ? 1
4059 : 0;
4060 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4061 // FIXME: This presumably means a pack ended up smaller than we
4062 // expected while deducing. Should this not result in deduction
4063 // failure? Can it even happen?
4064 continue;
4065
4066 QualType DeducedA;
4067 if (!OriginalArg.DecomposedParam) {
4068 // P is one of the function parameters, just look up its substituted
4069 // type.
4070 DeducedA =
4071 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4072 } else {
4073 // P is a decomposed element of a parameter corresponding to a
4074 // braced-init-list argument. Substitute back into P to find the
4075 // deduced A.
4076 QualType &CacheEntry =
4077 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4078 if (CacheEntry.isNull()) {
4079 ArgPackSubstIndexRAII PackIndex(
4080 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4081 ParamIdx));
4082 CacheEntry =
4083 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4084 Specialization->getTypeSpecStartLoc(),
4085 Specialization->getDeclName());
4086 }
4087 DeducedA = CacheEntry;
4088 }
4089
4090 if (auto TDK =
4091 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4093 return TDK;
4094 }
4095 }
4096
4097 // If we suppressed any diagnostics while performing template argument
4098 // deduction, and if we haven't already instantiated this declaration,
4099 // keep track of these diagnostics. They'll be emitted if this specialization
4100 // is actually used.
4101 if (Info.diag_begin() != Info.diag_end()) {
4102 auto [Pos, Inserted] =
4103 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4104 if (Inserted)
4105 Pos->second.append(Info.diag_begin(), Info.diag_end());
4106 }
4107
4109}
4110
4111/// Gets the type of a function for template-argument-deducton
4112/// purposes when it's considered as part of an overload set.
4114 FunctionDecl *Fn) {
4115 // We may need to deduce the return type of the function now.
4116 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4117 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4118 return {};
4119
4120 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4121 if (Method->isImplicitObjectMemberFunction()) {
4122 // An instance method that's referenced in a form that doesn't
4123 // look like a member pointer is just invalid.
4124 if (!R.HasFormOfMemberPointer)
4125 return {};
4126
4128 Fn->getType(), /*Qualifier=*/std::nullopt, Method->getParent());
4129 }
4130
4131 if (!R.IsAddressOfOperand) return Fn->getType();
4132 return S.Context.getPointerType(Fn->getType());
4133}
4134
4135/// Apply the deduction rules for overload sets.
4136///
4137/// \return the null type if this argument should be treated as an
4138/// undeduced context
4139static QualType
4141 Expr *Arg, QualType ParamType,
4142 bool ParamWasReference,
4143 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4144
4146
4147 OverloadExpr *Ovl = R.Expression;
4148
4149 // C++0x [temp.deduct.call]p4
4150 unsigned TDF = 0;
4151 if (ParamWasReference)
4153 if (R.IsAddressOfOperand)
4154 TDF |= TDF_IgnoreQualifiers;
4155
4156 // C++0x [temp.deduct.call]p6:
4157 // When P is a function type, pointer to function type, or pointer
4158 // to member function type:
4159
4160 if (!ParamType->isFunctionType() &&
4161 !ParamType->isFunctionPointerType() &&
4162 !ParamType->isMemberFunctionPointerType()) {
4163 if (Ovl->hasExplicitTemplateArgs()) {
4164 // But we can still look for an explicit specialization.
4165 if (FunctionDecl *ExplicitSpec =
4167 Ovl, /*Complain=*/false,
4168 /*Found=*/nullptr, FailedTSC,
4169 /*ForTypeDeduction=*/true))
4170 return GetTypeOfFunction(S, R, ExplicitSpec);
4171 }
4172
4173 DeclAccessPair DAP;
4174 if (FunctionDecl *Viable =
4176 return GetTypeOfFunction(S, R, Viable);
4177
4178 return {};
4179 }
4180
4181 // Gather the explicit template arguments, if any.
4182 TemplateArgumentListInfo ExplicitTemplateArgs;
4183 if (Ovl->hasExplicitTemplateArgs())
4184 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4186 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4187 E = Ovl->decls_end(); I != E; ++I) {
4188 NamedDecl *D = (*I)->getUnderlyingDecl();
4189
4190 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4191 // - If the argument is an overload set containing one or more
4192 // function templates, the parameter is treated as a
4193 // non-deduced context.
4194 if (!Ovl->hasExplicitTemplateArgs())
4195 return {};
4196
4197 // Otherwise, see if we can resolve a function type
4198 FunctionDecl *Specialization = nullptr;
4199 TemplateDeductionInfo Info(Ovl->getNameLoc());
4200 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4203 continue;
4204
4205 D = Specialization;
4206 }
4207
4209 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4210 if (ArgType.isNull()) continue;
4211
4212 // Function-to-pointer conversion.
4213 if (!ParamWasReference && ParamType->isPointerType() &&
4214 ArgType->isFunctionType())
4215 ArgType = S.Context.getPointerType(ArgType);
4216
4217 // - If the argument is an overload set (not containing function
4218 // templates), trial argument deduction is attempted using each
4219 // of the members of the set. If deduction succeeds for only one
4220 // of the overload set members, that member is used as the
4221 // argument value for the deduction. If deduction succeeds for
4222 // more than one member of the overload set the parameter is
4223 // treated as a non-deduced context.
4224
4225 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4226 // Type deduction is done independently for each P/A pair, and
4227 // the deduced template argument values are then combined.
4228 // So we do not reject deductions which were made elsewhere.
4230 Deduced(TemplateParams->size());
4231 TemplateDeductionInfo Info(Ovl->getNameLoc());
4233 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4234 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4235 /*HasDeducedAnyParam=*/nullptr);
4237 continue;
4238 // C++ [temp.deduct.call]p6:
4239 // [...] If all successful deductions yield the same deduced A, that
4240 // deduced A is the result of deduction; otherwise, the parameter is
4241 // treated as a non-deduced context. [...]
4242 if (!Match.isNull() && !S.isSameOrCompatibleFunctionType(Match, ArgType))
4243 return {};
4244 Match = ArgType;
4245 }
4246
4247 return Match;
4248}
4249
4250/// Perform the adjustments to the parameter and argument types
4251/// described in C++ [temp.deduct.call].
4252///
4253/// \returns true if the caller should not attempt to perform any template
4254/// argument deduction based on this P/A pair because the argument is an
4255/// overloaded function set that could not be resolved.
4257 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4258 QualType &ParamType, QualType &ArgType,
4259 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4260 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4261 // C++0x [temp.deduct.call]p3:
4262 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4263 // are ignored for type deduction.
4264 if (ParamType.hasQualifiers())
4265 ParamType = ParamType.getUnqualifiedType();
4266
4267 // [...] If P is a reference type, the type referred to by P is
4268 // used for type deduction.
4269 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4270 if (ParamRefType)
4271 ParamType = ParamRefType->getPointeeType();
4272
4273 // Overload sets usually make this parameter an undeduced context,
4274 // but there are sometimes special circumstances. Typically
4275 // involving a template-id-expr.
4276 if (ArgType == S.Context.OverloadTy) {
4277 assert(Arg && "expected a non-null arg expression");
4278 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4279 ParamRefType != nullptr, FailedTSC);
4280 if (ArgType.isNull())
4281 return true;
4282 }
4283
4284 if (ParamRefType) {
4285 // If the argument has incomplete array type, try to complete its type.
4286 if (ArgType->isIncompleteArrayType()) {
4287 assert(Arg && "expected a non-null arg expression");
4288 ArgType = S.getCompletedType(Arg);
4289 }
4290
4291 // C++1z [temp.deduct.call]p3:
4292 // If P is a forwarding reference and the argument is an lvalue, the type
4293 // "lvalue reference to A" is used in place of A for type deduction.
4294 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4295 ArgClassification.isLValue()) {
4296 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4297 ArgType = S.Context.getAddrSpaceQualType(
4299 ArgType = S.Context.getLValueReferenceType(ArgType);
4300 }
4301 } else {
4302 // C++ [temp.deduct.call]p2:
4303 // If P is not a reference type:
4304 // - If A is an array type, the pointer type produced by the
4305 // array-to-pointer standard conversion (4.2) is used in place of
4306 // A for type deduction; otherwise,
4307 // - If A is a function type, the pointer type produced by the
4308 // function-to-pointer standard conversion (4.3) is used in place
4309 // of A for type deduction; otherwise,
4310 if (ArgType->canDecayToPointerType())
4311 ArgType = S.Context.getDecayedType(ArgType);
4312 else {
4313 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4314 // type are ignored for type deduction.
4315 ArgType = ArgType.getUnqualifiedType();
4316 }
4317 }
4318
4319 // C++0x [temp.deduct.call]p4:
4320 // In general, the deduction process attempts to find template argument
4321 // values that will make the deduced A identical to A (after the type A
4322 // is transformed as described above). [...]
4324
4325 // - If the original P is a reference type, the deduced A (i.e., the
4326 // type referred to by the reference) can be more cv-qualified than
4327 // the transformed A.
4328 if (ParamRefType)
4330 // - The transformed A can be another pointer or pointer to member
4331 // type that can be converted to the deduced A via a qualification
4332 // conversion (4.4).
4333 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4334 ArgType->isObjCObjectPointerType())
4335 TDF |= TDF_IgnoreQualifiers;
4336 // - If P is a class and P has the form simple-template-id, then the
4337 // transformed A can be a derived class of the deduced A. Likewise,
4338 // if P is a pointer to a class of the form simple-template-id, the
4339 // transformed A can be a pointer to a derived class pointed to by
4340 // the deduced A.
4341 if (isSimpleTemplateIdType(ParamType) ||
4342 (ParamType->getAs<PointerType>() &&
4344 ParamType->castAs<PointerType>()->getPointeeType())))
4345 TDF |= TDF_DerivedClass;
4346
4347 return false;
4348}
4349
4350static bool
4352 QualType T);
4353
4355 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4356 QualType ParamType, QualType ArgType,
4357 Expr::Classification ArgClassification, Expr *Arg,
4361 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4362 TemplateSpecCandidateSet *FailedTSC = nullptr);
4363
4364/// Attempt template argument deduction from an initializer list
4365/// deemed to be an argument in a function call.
4367 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4370 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4371 unsigned TDF) {
4372 // C++ [temp.deduct.call]p1: (CWG 1591)
4373 // If removing references and cv-qualifiers from P gives
4374 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4375 // a non-empty initializer list, then deduction is performed instead for
4376 // each element of the initializer list, taking P0 as a function template
4377 // parameter type and the initializer element as its argument
4378 //
4379 // We've already removed references and cv-qualifiers here.
4380 if (!ILE->getNumInits())
4382
4383 QualType ElTy;
4384 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4385 if (ArrTy)
4386 ElTy = ArrTy->getElementType();
4387 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4388 // Otherwise, an initializer list argument causes the parameter to be
4389 // considered a non-deduced context
4391 }
4392
4393 // Resolving a core issue: a braced-init-list containing any designators is
4394 // a non-deduced context.
4395 for (Expr *E : ILE->inits())
4398
4399 // Deduction only needs to be done for dependent types.
4400 if (ElTy->isDependentType()) {
4401 for (Expr *E : ILE->inits()) {
4403 S, TemplateParams, 0, ElTy, E->getType(),
4404 E->Classify(S.getASTContext()), E, Info, Deduced,
4405 OriginalCallArgs, true, ArgIdx, TDF);
4407 return Result;
4408 }
4409 }
4410
4411 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4412 // from the length of the initializer list.
4413 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4414 // Determine the array bound is something we can deduce.
4416 Info, DependentArrTy->getSizeExpr())) {
4417 // We can perform template argument deduction for the given non-type
4418 // template parameter.
4419 // C++ [temp.deduct.type]p13:
4420 // The type of N in the type T[N] is std::size_t.
4422 llvm::APInt Size(S.Context.getIntWidth(T),
4424 if (auto Result = DeduceNonTypeTemplateArgument(
4425 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4426 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4427 /*HasDeducedAnyParam=*/nullptr);
4429 return Result;
4430 }
4431 }
4432
4434}
4435
4436/// Perform template argument deduction per [temp.deduct.call] for a
4437/// single parameter / argument pair.
4439 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4440 QualType ParamType, QualType ArgType,
4441 Expr::Classification ArgClassification, Expr *Arg,
4445 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4446 TemplateSpecCandidateSet *FailedTSC) {
4447
4448 QualType OrigParamType = ParamType;
4449
4450 // If P is a reference type [...]
4451 // If P is a cv-qualified type [...]
4453 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4454 ArgClassification, Arg, TDF, FailedTSC))
4456
4457 // If [...] the argument is a non-empty initializer list [...]
4458 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4459 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4460 Deduced, OriginalCallArgs, ArgIdx, TDF);
4461
4462 // [...] the deduction process attempts to find template argument values
4463 // that will make the deduced A identical to A
4464 //
4465 // Keep track of the argument type and corresponding parameter index,
4466 // so we can check for compatibility between the deduced A and A.
4467 if (Arg)
4468 OriginalCallArgs.push_back(
4469 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4471 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4472 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4473 /*HasDeducedAnyParam=*/nullptr);
4474}
4475
4478 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4480 bool PartialOverloading, bool AggregateDeductionCandidate,
4481 bool PartialOrdering, QualType ObjectType,
4482 Expr::Classification ObjectClassification,
4483 bool ForOverloadSetAddressResolution,
4484 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent) {
4485 if (FunctionTemplate->isInvalidDecl())
4487
4488 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4489 unsigned NumParams = Function->getNumParams();
4490 bool HasExplicitObject = false;
4491 int ExplicitObjectOffset = 0;
4492
4493 // [C++26] [over.call.func]p3
4494 // If the primary-expression is the address of an overload set,
4495 // the argument list is the same as the expression-list in the call.
4496 // Otherwise, the argument list is the expression-list in the call augmented
4497 // by the addition of an implied object argument as in a qualified function
4498 // call.
4499 if (!ForOverloadSetAddressResolution &&
4500 Function->hasCXXExplicitFunctionObjectParameter()) {
4501 HasExplicitObject = true;
4502 ExplicitObjectOffset = 1;
4503 }
4504
4505 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4506
4507 // C++ [temp.deduct.call]p1:
4508 // Template argument deduction is done by comparing each function template
4509 // parameter type (call it P) with the type of the corresponding argument
4510 // of the call (call it A) as described below.
4511 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4512 !PartialOverloading)
4514 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4515 PartialOverloading)) {
4516 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4517 if (Proto->isTemplateVariadic())
4518 /* Do nothing */;
4519 else if (!Proto->isVariadic())
4521 }
4522
4525 Sema::SFINAETrap Trap(*this, Info);
4526
4527 // The types of the parameters from which we will perform template argument
4528 // deduction.
4529 LocalInstantiationScope InstScope(*this);
4530 TemplateParameterList *TemplateParams
4531 = FunctionTemplate->getTemplateParameters();
4533 SmallVector<QualType, 8> ParamTypes;
4534 unsigned NumExplicitlySpecified = 0;
4535 if (ExplicitTemplateArgs) {
4538 Result = SubstituteExplicitTemplateArguments(
4539 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4540 Info);
4541 });
4543 return Result;
4544 if (Trap.hasErrorOccurred())
4546
4547 NumExplicitlySpecified = Deduced.size();
4548 } else {
4549 // Just fill in the parameter types from the function declaration.
4550 for (unsigned I = 0; I != NumParams; ++I)
4551 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4552 }
4553
4554 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4555
4556 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4557 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4558 bool ExplicitObjectArgument) {
4559 // C++ [demp.deduct.call]p1: (DR1391)
4560 // Template argument deduction is done by comparing each function template
4561 // parameter that contains template-parameters that participate in
4562 // template argument deduction ...
4563 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4565
4566 if (ExplicitObjectArgument) {
4567 // ... with the type of the corresponding argument
4569 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4570 ObjectClassification,
4571 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4572 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4573 }
4574
4575 // ... with the type of the corresponding argument
4577 *this, TemplateParams, FirstInnerIndex, ParamType,
4578 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4579 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4580 ArgIdx, /*TDF*/ 0);
4581 };
4582
4583 // Deduce template arguments from the function parameters.
4584 Deduced.resize(TemplateParams->size());
4585 SmallVector<QualType, 8> ParamTypesForArgChecking;
4586 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4587 ParamIdx != NumParamTypes; ++ParamIdx) {
4588 QualType ParamType = ParamTypes[ParamIdx];
4589
4590 const PackExpansionType *ParamExpansion =
4591 dyn_cast<PackExpansionType>(ParamType);
4592 if (!ParamExpansion) {
4593 // Simple case: matching a function parameter to a function argument.
4594 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4595 break;
4596
4597 ParamTypesForArgChecking.push_back(ParamType);
4598
4599 if (ParamIdx == 0 && HasExplicitObject) {
4600 if (ObjectType.isNull())
4602
4603 if (auto Result = DeduceCallArgument(ParamType, 0,
4604 /*ExplicitObjectArgument=*/true);
4606 return Result;
4607 continue;
4608 }
4609
4610 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4611 /*ExplicitObjectArgument=*/false);
4613 return Result;
4614
4615 continue;
4616 }
4617
4618 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4619
4620 QualType ParamPattern = ParamExpansion->getPattern();
4621 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4622 ParamPattern,
4623 AggregateDeductionCandidate && IsTrailingPack);
4624
4625 // C++0x [temp.deduct.call]p1:
4626 // For a function parameter pack that occurs at the end of the
4627 // parameter-declaration-list, the type A of each remaining argument of
4628 // the call is compared with the type P of the declarator-id of the
4629 // function parameter pack. Each comparison deduces template arguments
4630 // for subsequent positions in the template parameter packs expanded by
4631 // the function parameter pack. When a function parameter pack appears
4632 // in a non-deduced context [not at the end of the list], the type of
4633 // that parameter pack is never deduced.
4634 //
4635 // FIXME: The above rule allows the size of the parameter pack to change
4636 // after we skip it (in the non-deduced case). That makes no sense, so
4637 // we instead notionally deduce the pack against N arguments, where N is
4638 // the length of the explicitly-specified pack if it's expanded by the
4639 // parameter pack and 0 otherwise, and we treat each deduction as a
4640 // non-deduced context.
4641 if (IsTrailingPack || PackScope.hasFixedArity()) {
4642 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4643 PackScope.nextPackElement(), ++ArgIdx) {
4644 ParamTypesForArgChecking.push_back(ParamPattern);
4645 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4646 /*ExplicitObjectArgument=*/false);
4648 return Result;
4649 }
4650 } else {
4651 // If the parameter type contains an explicitly-specified pack that we
4652 // could not expand, skip the number of parameters notionally created
4653 // by the expansion.
4654 UnsignedOrNone NumExpansions = ParamExpansion->getNumExpansions();
4655 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4656 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4657 ++I, ++ArgIdx) {
4658 ParamTypesForArgChecking.push_back(ParamPattern);
4659 // FIXME: Should we add OriginalCallArgs for these? What if the
4660 // corresponding argument is a list?
4661 PackScope.nextPackElement();
4662 }
4663 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4664 PackScope.isDeducedFromEarlierParameter()) {
4665 // [temp.deduct.general#3]
4666 // When all template arguments have been deduced
4667 // or obtained from default template arguments, all uses of template
4668 // parameters in the template parameter list of the template are
4669 // replaced with the corresponding deduced or default argument values
4670 //
4671 // If we have a trailing parameter pack, that has been deduced
4672 // previously we substitute the pack here in a similar fashion as
4673 // above with the trailing parameter packs. The main difference here is
4674 // that, in this case we are not processing all of the remaining
4675 // arguments. We are only process as many arguments as we have in
4676 // the already deduced parameter.
4677 UnsignedOrNone ArgPosAfterSubstitution =
4678 PackScope.getSavedPackSizeIfAllEqual();
4679 if (!ArgPosAfterSubstitution)
4680 continue;
4681
4682 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4683 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4684 ParamTypesForArgChecking.push_back(ParamPattern);
4685 if (auto Result =
4686 DeduceCallArgument(ParamPattern, ArgIdx,
4687 /*ExplicitObjectArgument=*/false);
4689 return Result;
4690
4691 PackScope.nextPackElement();
4692 }
4693 }
4694 }
4695
4696 // Build argument packs for each of the parameter packs expanded by this
4697 // pack expansion.
4698 if (auto Result = PackScope.finish();
4700 return Result;
4701 }
4702
4703 // Capture the context in which the function call is made. This is the context
4704 // that is needed when the accessibility of template arguments is checked.
4705 DeclContext *CallingCtx = CurContext;
4706
4709 Result = FinishTemplateArgumentDeduction(
4710 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4711 &OriginalCallArgs, PartialOverloading, PartialOrdering,
4712 ForOverloadSetAddressResolution,
4713 [&, CallingCtx](bool OnlyInitializeNonUserDefinedConversions) {
4714 ContextRAII SavedContext(*this, CallingCtx);
4715 return CheckNonDependent(ParamTypesForArgChecking,
4716 OnlyInitializeNonUserDefinedConversions);
4717 });
4718 });
4719 if (Trap.hasErrorOccurred()) {
4720 if (Specialization)
4721 Specialization->setInvalidDecl(true);
4723 }
4724 return Result;
4725}
4726
4729 bool AdjustExceptionSpec) {
4730 if (ArgFunctionType.isNull())
4731 return ArgFunctionType;
4732
4733 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4734 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4735 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4736 bool Rebuild = false;
4737
4738 CallingConv CC = FunctionTypeP->getCallConv();
4739 if (EPI.ExtInfo.getCC() != CC) {
4740 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4741 Rebuild = true;
4742 }
4743
4744 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4745 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4746 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4747 Rebuild = true;
4748 }
4749
4750 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4751 ArgFunctionTypeP->hasExceptionSpec())) {
4752 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4753 Rebuild = true;
4754 }
4755
4756 if (!Rebuild)
4757 return ArgFunctionType;
4758
4759 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4760 ArgFunctionTypeP->getParamTypes(), EPI);
4761}
4762
4765 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4767 bool IsAddressOfFunction) {
4768 if (FunctionTemplate->isInvalidDecl())
4770
4771 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4772 TemplateParameterList *TemplateParams
4773 = FunctionTemplate->getTemplateParameters();
4774 QualType FunctionType = Function->getType();
4775
4778
4779 // Unevaluated SFINAE context.
4782 SFINAETrap Trap(*this, Info);
4783
4784 // Substitute any explicit template arguments.
4785 LocalInstantiationScope InstScope(*this);
4787 unsigned NumExplicitlySpecified = 0;
4788 SmallVector<QualType, 4> ParamTypes;
4789 if (ExplicitTemplateArgs) {
4792 Result = SubstituteExplicitTemplateArguments(
4793 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4794 &FunctionType, Info);
4795 });
4797 return Result;
4798 if (Trap.hasErrorOccurred())
4800
4801 NumExplicitlySpecified = Deduced.size();
4802 }
4803
4804 // When taking the address of a function, we require convertibility of
4805 // the resulting function type. Otherwise, we allow arbitrary mismatches
4806 // of calling convention and noreturn.
4807 if (!IsAddressOfFunction)
4808 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4809 /*AdjustExceptionSpec*/false);
4810
4811 Deduced.resize(TemplateParams->size());
4812
4813 // If the function has a deduced return type, substitute it for a dependent
4814 // type so that we treat it as a non-deduced context in what follows.
4815 bool HasDeducedReturnType = false;
4816 if (getLangOpts().CPlusPlus14 &&
4817 Function->getReturnType()->getContainedAutoType()) {
4819 HasDeducedReturnType = true;
4820 }
4821
4822 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4823 unsigned TDF =
4825 // Deduce template arguments from the function type.
4827 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4828 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4829 /*HasDeducedAnyParam=*/nullptr);
4831 return Result;
4832 }
4833
4836 Result = FinishTemplateArgumentDeduction(
4837 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4838 /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false,
4839 /*PartialOrdering=*/true, IsAddressOfFunction);
4840 });
4842 return Result;
4843
4844 // If the function has a deduced return type, deduce it now, so we can check
4845 // that the deduced function type matches the requested type.
4846 if (HasDeducedReturnType && IsAddressOfFunction &&
4847 Specialization->getReturnType()->isUndeducedType() &&
4850
4851 // [C++26][expr.const]/p17
4852 // An expression or conversion is immediate-escalating if it is not initially
4853 // in an immediate function context and it is [...]
4854 // a potentially-evaluated id-expression that denotes an immediate function.
4855 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4856 Specialization->isImmediateEscalating() && PotentiallyEvaluated &&
4858 Info.getLocation()))
4860
4861 // Adjust the exception specification of the argument to match the
4862 // substituted and resolved type we just formed. (Calling convention and
4863 // noreturn can't be dependent, so we don't actually need this for them
4864 // right now.)
4865 QualType SpecializationType = Specialization->getType();
4866 if (!IsAddressOfFunction) {
4867 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4868 /*AdjustExceptionSpec*/true);
4869
4870 // Revert placeholder types in the return type back to undeduced types so
4871 // that the comparison below compares the declared return types.
4872 if (HasDeducedReturnType) {
4873 SpecializationType = SubstAutoType(SpecializationType, QualType());
4874 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4875 }
4876 }
4877
4878 // If the requested function type does not match the actual type of the
4879 // specialization with respect to arguments of compatible pointer to function
4880 // types, template argument deduction fails.
4881 if (!ArgFunctionType.isNull()) {
4882 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4883 SpecializationType, ArgFunctionType)
4884 : !Context.hasSameFunctionTypeIgnoringExceptionSpec(
4885 SpecializationType, ArgFunctionType)) {
4886 Info.FirstArg = TemplateArgument(SpecializationType);
4887 Info.SecondArg = TemplateArgument(ArgFunctionType);
4889 }
4890 }
4891
4893}
4894
4896 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4897 Expr::Classification ObjectClassification, QualType A,
4899 if (ConversionTemplate->isInvalidDecl())
4901
4902 CXXConversionDecl *ConversionGeneric
4903 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4904
4905 QualType P = ConversionGeneric->getConversionType();
4906 bool IsReferenceP = P->isReferenceType();
4907 bool IsReferenceA = A->isReferenceType();
4908
4909 // C++0x [temp.deduct.conv]p2:
4910 // If P is a reference type, the type referred to by P is used for
4911 // type deduction.
4912 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4913 P = PRef->getPointeeType();
4914
4915 // C++0x [temp.deduct.conv]p4:
4916 // [...] If A is a reference type, the type referred to by A is used
4917 // for type deduction.
4918 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4919 A = ARef->getPointeeType();
4920 // We work around a defect in the standard here: cv-qualifiers are also
4921 // removed from P and A in this case, unless P was a reference type. This
4922 // seems to mostly match what other compilers are doing.
4923 if (!IsReferenceP) {
4924 A = A.getUnqualifiedType();
4925 P = P.getUnqualifiedType();
4926 }
4927
4928 // C++ [temp.deduct.conv]p3:
4929 //
4930 // If A is not a reference type:
4931 } else {
4932 assert(!A->isReferenceType() && "Reference types were handled above");
4933
4934 // - If P is an array type, the pointer type produced by the
4935 // array-to-pointer standard conversion (4.2) is used in place
4936 // of P for type deduction; otherwise,
4937 if (P->isArrayType())
4938 P = Context.getArrayDecayedType(P);
4939 // - If P is a function type, the pointer type produced by the
4940 // function-to-pointer standard conversion (4.3) is used in
4941 // place of P for type deduction; otherwise,
4942 else if (P->isFunctionType())
4943 P = Context.getPointerType(P);
4944 // - If P is a cv-qualified type, the top level cv-qualifiers of
4945 // P's type are ignored for type deduction.
4946 else
4947 P = P.getUnqualifiedType();
4948
4949 // C++0x [temp.deduct.conv]p4:
4950 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4951 // type are ignored for type deduction. If A is a reference type, the type
4952 // referred to by A is used for type deduction.
4953 A = A.getUnqualifiedType();
4954 }
4955
4956 // Unevaluated SFINAE context.
4959 SFINAETrap Trap(*this, Info);
4960
4961 // C++ [temp.deduct.conv]p1:
4962 // Template argument deduction is done by comparing the return
4963 // type of the template conversion function (call it P) with the
4964 // type that is required as the result of the conversion (call it
4965 // A) as described in 14.8.2.4.
4966 TemplateParameterList *TemplateParams
4967 = ConversionTemplate->getTemplateParameters();
4969 Deduced.resize(TemplateParams->size());
4970
4971 // C++0x [temp.deduct.conv]p4:
4972 // In general, the deduction process attempts to find template
4973 // argument values that will make the deduced A identical to
4974 // A. However, there are two cases that allow a difference:
4975 unsigned TDF = 0;
4976 // - If the original A is a reference type, A can be more
4977 // cv-qualified than the deduced A (i.e., the type referred to
4978 // by the reference)
4979 if (IsReferenceA)
4981 // - The deduced A can be another pointer or pointer to member
4982 // type that can be converted to A via a qualification
4983 // conversion.
4984 //
4985 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4986 // both P and A are pointers or member pointers. In this case, we
4987 // just ignore cv-qualifiers completely).
4988 if ((P->isPointerType() && A->isPointerType()) ||
4990 TDF |= TDF_IgnoreQualifiers;
4991
4993 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
4994 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
4997 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
4998 ParamType, ObjectType, ObjectClassification,
4999 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
5000 /*Decomposed*/ false, 0, /*TDF*/ 0);
5002 return Result;
5003 }
5004
5006 *this, TemplateParams, P, A, Info, Deduced, TDF,
5007 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5008 /*HasDeducedAnyParam=*/nullptr);
5010 return Result;
5011
5012 // Create an Instantiation Scope for finalizing the operator.
5013 LocalInstantiationScope InstScope(*this);
5014 // Finish template argument deduction.
5015 FunctionDecl *ConversionSpecialized = nullptr;
5018 Result = FinishTemplateArgumentDeduction(
5019 ConversionTemplate, Deduced, 0, ConversionSpecialized, Info,
5020 &OriginalCallArgs, /*PartialOverloading=*/false,
5021 /*PartialOrdering=*/false, /*ForOverloadSetAddressResolution*/ false);
5022 });
5023 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
5024 return Result;
5025}
5026
5029 TemplateArgumentListInfo *ExplicitTemplateArgs,
5032 bool IsAddressOfFunction) {
5033 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5034 QualType(), Specialization, Info,
5035 IsAddressOfFunction);
5036}
5037
5038namespace {
5039 struct DependentAuto { bool IsPack; };
5040
5041 /// Substitute the 'auto' specifier or deduced template specialization type
5042 /// specifier within a type for a given replacement type.
5043 class SubstituteDeducedTypeTransform :
5044 public TreeTransform<SubstituteDeducedTypeTransform> {
5045 DeducedKind DK;
5046 QualType Replacement;
5047 bool UseTypeSugar;
5049
5050 public:
5051 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5052 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5053 DK(DA.IsPack ? DeducedKind::DeducedAsPack
5055 UseTypeSugar(true) {}
5056
5057 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5058 bool UseTypeSugar = true)
5059 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5060 DK(Replacement.isNull() ? DeducedKind::Undeduced
5061 : DeducedKind::Deduced),
5062 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {
5063 assert((!Replacement.isNull() || UseTypeSugar) &&
5064 "An undeduced auto type is never type sugar");
5065 }
5066
5067 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5068 assert(isa<TemplateTypeParmType>(Replacement) &&
5069 "unexpected unsugared replacement kind");
5070 QualType Result = Replacement;
5071 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
5072 NewTL.setNameLoc(TL.getNameLoc());
5073 return Result;
5074 }
5075
5076 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5077 // If we're building the type pattern to deduce against, don't wrap the
5078 // substituted type in an AutoType. Certain template deduction rules
5079 // apply only when a template type parameter appears directly (and not if
5080 // the parameter is found through desugaring). For instance:
5081 // auto &&lref = lvalue;
5082 // must transform into "rvalue reference to T" not "rvalue reference to
5083 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5084 //
5085 // FIXME: Is this still necessary?
5086 if (!UseTypeSugar)
5087 return TransformDesugared(TLB, TL);
5088
5089 QualType Result = SemaRef.Context.getAutoType(
5090 DK, Replacement, TL.getTypePtr()->getKeyword(),
5091 TL.getTypePtr()->getTypeConstraintConcept(),
5092 TL.getTypePtr()->getTypeConstraintArguments());
5093 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5094 NewTL.copy(TL);
5095 return Result;
5096 }
5097
5098 QualType TransformDeducedTemplateSpecializationType(
5099 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5100 if (!UseTypeSugar)
5101 return TransformDesugared(TLB, TL);
5102
5104 DK, Replacement, TL.getTypePtr()->getKeyword(),
5105 TL.getTypePtr()->getTemplateName());
5106 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5107 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5108 NewTL.setNameLoc(TL.getNameLoc());
5109 NewTL.setQualifierLoc(TL.getQualifierLoc());
5110 return Result;
5111 }
5112
5113 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5114 // Lambdas never need to be transformed.
5115 return E;
5116 }
5117 bool TransformExceptionSpec(SourceLocation Loc,
5118 FunctionProtoType::ExceptionSpecInfo &ESI,
5119 SmallVectorImpl<QualType> &Exceptions,
5120 bool &Changed) {
5121 if (ESI.Type == EST_Uninstantiated) {
5122 ESI.instantiate();
5123 Changed = true;
5124 }
5125 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5126 }
5127
5128 QualType Apply(TypeLoc TL) {
5129 // Create some scratch storage for the transformed type locations.
5130 // FIXME: We're just going to throw this information away. Don't build it.
5131 TypeLocBuilder TLB;
5132 TLB.reserve(TL.getFullDataSize());
5133 return TransformType(TLB, TL);
5134 }
5135 };
5136
5137} // namespace
5138
5139static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
5141 QualType Deduced) {
5142 ConstraintSatisfaction Satisfaction;
5143 ConceptDecl *Concept = cast<ConceptDecl>(Type.getTypeConstraintConcept());
5144 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5145 TypeLoc.getRAngleLoc());
5146 TemplateArgs.addArgument(
5149 Deduced, TypeLoc.getNameLoc())));
5150 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5151 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5152
5154 if (S.CheckTemplateArgumentList(Concept, TypeLoc.getNameLoc(), TemplateArgs,
5155 /*DefaultArgs=*/{},
5156 /*PartialTemplateArgs=*/false, CTAI))
5157 return true;
5159 /*Final=*/true);
5160 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5161 // that the template arguments of the constraint can be preserved. For
5162 // example:
5163 //
5164 // template <class T>
5165 // concept C = []<D U = void>() { return true; }();
5166 //
5167 // We need the argument for T while evaluating type constraint D in
5168 // building the CallExpr to the lambda.
5172 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5173 CTAI.SugaredConverted));
5175 Concept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
5176 TypeLoc.getLocalSourceRange(), Satisfaction))
5177 return true;
5178 if (!Satisfaction.IsSatisfied) {
5179 std::string Buf;
5180 llvm::raw_string_ostream OS(Buf);
5181 OS << "'" << Concept->getName();
5182 if (TypeLoc.hasExplicitTemplateArgs()) {
5183 printTemplateArgumentList(
5184 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5185 Type.getTypeConstraintConcept()->getTemplateParameters());
5186 }
5187 OS << "'";
5188 S.Diag(TypeLoc.getConceptNameLoc(),
5189 diag::err_placeholder_constraints_not_satisfied)
5190 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5191 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5192 return true;
5193 }
5194 return false;
5195}
5196
5199 TemplateDeductionInfo &Info, bool DependentDeduction,
5200 bool IgnoreConstraints,
5201 TemplateSpecCandidateSet *FailedTSC) {
5202 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5203 if (Init->containsErrors())
5205
5206 const AutoType *AT = Type.getType()->getContainedAutoType();
5207 assert(AT);
5208
5209 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5210 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5211 if (NonPlaceholder.isInvalid())
5213 Init = NonPlaceholder.get();
5214 }
5215
5216 DependentAuto DependentResult = {
5217 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5218
5219 if (!DependentDeduction &&
5220 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5221 Init->containsUnexpandedParameterPack())) {
5222 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5223 assert(!Result.isNull() && "substituting DependentTy can't fail");
5225 }
5226
5227 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5228 auto *String = dyn_cast<StringLiteral>(Init);
5229 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5230 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5231 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5232 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5233 assert(!Result.isNull() && "substituting DependentTy can't fail");
5235 }
5236
5237 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5238 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5239 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5240 }
5241
5242 auto *InitList = dyn_cast<InitListExpr>(Init);
5243 if (!getLangOpts().CPlusPlus && InitList) {
5244 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5245 << (int)AT->getKeyword() << getLangOpts().C23;
5247 }
5248
5249 // Deduce type of TemplParam in Func(Init)
5251 Deduced.resize(1);
5252
5253 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5254
5255 QualType DeducedType;
5256 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5257 if (AT->isDecltypeAuto()) {
5258 if (InitList) {
5259 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5261 }
5262
5263 DeducedType = getDecltypeForExpr(Init);
5264 assert(!DeducedType.isNull());
5265 } else {
5266 LocalInstantiationScope InstScope(*this);
5267
5268 // Build template<class TemplParam> void Func(FuncParam);
5269 SourceLocation Loc = Init->getExprLoc();
5271 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5272 nullptr, false, false, false);
5273 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5274 NamedDecl *TemplParamPtr = TemplParam;
5276 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5277
5278 if (InitList) {
5279 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5280 // deduce against that. Such deduction only succeeds if removing
5281 // cv-qualifiers and references results in std::initializer_list<T>.
5282 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5284
5285 SourceRange DeducedFromInitRange;
5286 for (Expr *Init : InitList->inits()) {
5287 // Resolving a core issue: a braced-init-list containing any designators
5288 // is a non-deduced context.
5292 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5293 Init->Classify(getASTContext()), Init, Info, Deduced,
5294 OriginalCallArgs,
5295 /*Decomposed=*/true,
5296 /*ArgIdx=*/0, /*TDF=*/0);
5299 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5300 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5301 << Init->getSourceRange();
5303 }
5304 return TDK;
5305 }
5306
5307 if (DeducedFromInitRange.isInvalid() &&
5308 Deduced[0].getKind() != TemplateArgument::Null)
5309 DeducedFromInitRange = Init->getSourceRange();
5310 }
5311 } else {
5312 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5313 Diag(Loc, diag::err_auto_bitfield);
5315 }
5316 QualType FuncParam =
5317 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5318 assert(!FuncParam.isNull() &&
5319 "substituting template parameter for 'auto' failed");
5321 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5322 Init->Classify(getASTContext()), Init, Info, Deduced,
5323 OriginalCallArgs,
5324 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5326 return TDK;
5327 }
5328
5329 // Could be null if somehow 'auto' appears in a non-deduced context.
5332 DeducedType = Deduced[0].getAsType();
5333
5334 if (InitList) {
5335 DeducedType = BuildStdInitializerList(DeducedType, Loc);
5336 if (DeducedType.isNull())
5338 }
5339 }
5340
5341 if (!Result.isNull()) {
5342 if (!Context.hasSameType(DeducedType, Result)) {
5343 Info.FirstArg = Result;
5344 Info.SecondArg = DeducedType;
5346 }
5347 DeducedType = Context.getCommonSugaredType(Result, DeducedType);
5348 }
5349
5350 if (AT->isConstrained() && !IgnoreConstraints &&
5352 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5354
5355 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5356 if (Result.isNull())
5358
5359 // Check that the deduced argument type is compatible with the original
5360 // argument type per C++ [temp.deduct.call]p4.
5361 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5362 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5363 assert((bool)InitList == OriginalArg.DecomposedParam &&
5364 "decomposed non-init-list in auto deduction?");
5365 if (auto TDK =
5366 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5368 Result = QualType();
5369 return TDK;
5370 }
5371 }
5372
5374}
5375
5377 QualType TypeToReplaceAuto) {
5378 assert(TypeToReplaceAuto != Context.DependentTy);
5379 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5380 .TransformType(TypeWithAuto);
5381}
5382
5384 QualType TypeToReplaceAuto) {
5385 assert(TypeToReplaceAuto != Context.DependentTy);
5386 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5387 .TransformType(TypeWithAuto);
5388}
5389
5391 return SubstituteDeducedTypeTransform(
5392 *this,
5393 DependentAuto{/*IsPack=*/isa<PackExpansionType>(TypeWithAuto)})
5394 .TransformType(TypeWithAuto);
5395}
5396
5399 return SubstituteDeducedTypeTransform(
5400 *this, DependentAuto{/*IsPack=*/isa<PackExpansionType>(
5401 TypeWithAuto->getType())})
5402 .TransformType(TypeWithAuto);
5403}
5404
5406 QualType TypeToReplaceAuto) {
5407 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5408 /*UseTypeSugar*/ false)
5409 .TransformType(TypeWithAuto);
5410}
5411
5413 QualType TypeToReplaceAuto) {
5414 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5415 /*UseTypeSugar*/ false)
5416 .TransformType(TypeWithAuto);
5417}
5418
5420 const Expr *Init) {
5422 Diag(VDecl->getLocation(),
5423 VDecl->isInitCapture()
5424 ? diag::err_init_capture_deduction_failure_from_init_list
5425 : diag::err_auto_var_deduction_failure_from_init_list)
5426 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5427 else
5428 Diag(VDecl->getLocation(),
5429 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5430 : diag::err_auto_var_deduction_failure)
5431 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5432 << Init->getSourceRange();
5433}
5434
5436 bool Diagnose) {
5437 assert(FD->getReturnType()->isUndeducedType());
5438
5439 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5440 // within the return type from the call operator's type.
5442 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5443 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5444
5445 // For a generic lambda, instantiate the call operator if needed.
5446 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5448 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5449 if (!CallOp || CallOp->isInvalidDecl())
5450 return true;
5451
5452 // We might need to deduce the return type by instantiating the definition
5453 // of the operator() function.
5454 if (CallOp->getReturnType()->isUndeducedType()) {
5456 InstantiateFunctionDefinition(Loc, CallOp);
5457 });
5458 }
5459 }
5460
5461 if (CallOp->isInvalidDecl())
5462 return true;
5463 assert(!CallOp->getReturnType()->isUndeducedType() &&
5464 "failed to deduce lambda return type");
5465
5466 // Build the new return type from scratch.
5467 CallingConv RetTyCC = FD->getReturnType()
5468 ->getPointeeType()
5469 ->castAs<FunctionType>()
5470 ->getCallConv();
5472 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5473 if (FD->getReturnType()->getAs<PointerType>())
5474 RetType = Context.getPointerType(RetType);
5475 else {
5476 assert(FD->getReturnType()->getAs<BlockPointerType>());
5477 RetType = Context.getBlockPointerType(RetType);
5478 }
5479 Context.adjustDeducedFunctionResultType(FD, RetType);
5480 return false;
5481 }
5482
5486 });
5487 }
5488
5489 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5490 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5491 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5492 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5493 }
5494
5495 return StillUndeduced;
5496}
5497
5499 SourceLocation Loc) {
5500 assert(FD->isImmediateEscalating());
5501
5503 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5504 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5505
5506 // For a generic lambda, instantiate the call operator if needed.
5507 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5509 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5510 if (!CallOp || CallOp->isInvalidDecl())
5511 return true;
5513 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5514 }
5515 return CallOp->isInvalidDecl();
5516 }
5517
5520 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5521 }
5522 return false;
5523}
5524
5526 const CXXMethodDecl *Method,
5527 QualType RawType,
5528 bool IsOtherRvr) {
5529 // C++20 [temp.func.order]p3.1, p3.2:
5530 // - The type X(M) is "rvalue reference to cv A" if the optional
5531 // ref-qualifier of M is && or if M has no ref-qualifier and the
5532 // positionally-corresponding parameter of the other transformed template
5533 // has rvalue reference type; if this determination depends recursively
5534 // upon whether X(M) is an rvalue reference type, it is not considered to
5535 // have rvalue reference type.
5536 //
5537 // - Otherwise, X(M) is "lvalue reference to cv A".
5538 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5539 "expected a member function with no explicit object parameter");
5540
5541 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5542 if (Method->getRefQualifier() == RQ_RValue ||
5543 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5544 return Context.getRValueReferenceType(RawType);
5545 return Context.getLValueReferenceType(RawType);
5546}
5547
5550 QualType A, ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5551 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5552 /*Final=*/true);
5554 S,
5555 ArgIdx ? ::getPackIndexForParam(S, FTD, MLTAL, *ArgIdx) : std::nullopt);
5556 bool IsIncompleteSubstitution = false;
5557 // FIXME: A substitution can be incomplete on a non-structural part of the
5558 // type. Use the canonical type for now, until the TemplateInstantiator can
5559 // deal with that.
5560
5561 // Workaround: Implicit deduction guides use InjectedClassNameTypes, whereas
5562 // the explicit guides don't. The substitution doesn't transform these types,
5563 // so let it transform their specializations instead.
5564 bool IsDeductionGuide = isa<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
5565 if (IsDeductionGuide) {
5566 if (auto *Injected = P->getAsCanonical<InjectedClassNameType>())
5567 P = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5568 S.Context);
5569 }
5570 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5571 FTD->getDeclName(), &IsIncompleteSubstitution);
5572 if (InstP.isNull() && !IsIncompleteSubstitution)
5574 if (!CheckConsistency)
5576 if (IsIncompleteSubstitution)
5578
5579 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5580 // This handles just the cases that can appear when partial ordering.
5581 if (auto *PA = dyn_cast<PackExpansionType>(A);
5582 PA && !isa<PackExpansionType>(InstP))
5583 A = PA->getPattern();
5586 if (IsDeductionGuide) {
5587 if (auto *Injected = T1->getAsCanonical<InjectedClassNameType>())
5588 T1 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5589 S.Context);
5590 if (auto *Injected = T2->getAsCanonical<InjectedClassNameType>())
5591 T2 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5592 S.Context);
5593 }
5594 if (!S.Context.hasSameType(T1, T2))
5597}
5598
5599template <class T>
5601 Sema &S, FunctionTemplateDecl *FTD,
5604 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5605
5606 // C++26 [temp.deduct.type]p2:
5607 // [...] or if any template argument remains neither deduced nor
5608 // explicitly specified, template argument deduction fails.
5609 bool IsIncomplete = false;
5610 Sema::CheckTemplateArgumentInfo CTAI(/*PartialOrdering=*/true);
5611 if (auto Result = ConvertDeducedTemplateArguments(
5612 S, FTD, FTD->getTemplateParameters(), /*IsDeduced=*/true, Deduced,
5613 Info, CTAI,
5614 /*CurrentInstantiationScope=*/nullptr,
5615 /*NumAlreadyConverted=*/0, &IsIncomplete);
5617 return Result;
5618
5619 // Form the template argument list from the deduced template arguments.
5620 TemplateArgumentList *SugaredDeducedArgumentList =
5622 TemplateArgumentList *CanonicalDeducedArgumentList =
5624
5625 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5626
5627 // Substitute the deduced template arguments into the argument
5628 // and verify that the instantiated argument is both valid
5629 // and equivalent to the parameter.
5630 LocalInstantiationScope InstScope(S);
5631 return CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted);
5632}
5633
5634/// Determine whether the function template \p FT1 is at least as
5635/// specialized as \p FT2.
5639 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5640 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5641 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5642 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5643 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5644 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5645
5646 // C++26 [temp.deduct.partial]p3:
5647 // The types used to determine the ordering depend on the context in which
5648 // the partial ordering is done:
5649 // - In the context of a function call, the types used are those function
5650 // parameter types for which the function call has arguments.
5651 // - In the context of a call to a conversion operator, the return types
5652 // of the conversion function templates are used.
5653 // - In other contexts (14.6.6.2) the function template's function type
5654 // is used.
5655
5656 if (TPOC == TPOC_Other) {
5657 // We wouldn't be partial ordering these candidates if these didn't match.
5658 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5659 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5660 Proto1->isVariadic() == Proto2->isVariadic() &&
5661 "shouldn't partial order functions with different qualifiers in a "
5662 "context where the function type is used");
5663
5664 assert(Args1.empty() && Args2.empty() &&
5665 "Only call context should have arguments");
5666 Args1 = Proto1->getParamTypes();
5667 Args2 = Proto2->getParamTypes();
5668 }
5669
5670 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5672 TemplateDeductionInfo Info(Loc);
5673
5674 bool HasDeducedAnyParamFromReturnType = false;
5675 if (TPOC != TPOC_Call) {
5677 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5679 /*DeducedFromArrayBound=*/false,
5680 &HasDeducedAnyParamFromReturnType) !=
5682 return false;
5683 }
5684
5685 llvm::SmallBitVector HasDeducedParam;
5686 if (TPOC != TPOC_Conversion) {
5687 HasDeducedParam.resize(Args2.size());
5688 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5690 /*HasDeducedAnyParam=*/nullptr,
5691 &HasDeducedParam) !=
5693 return false;
5694 }
5695
5696 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5699 Sema::SFINAETrap Trap(S, Info);
5701 S, Info.getLocation(), FT2, DeducedArgs,
5703 if (Inst.isInvalid())
5704 return false;
5705
5706 bool AtLeastAsSpecialized;
5708 AtLeastAsSpecialized =
5709 ::FinishTemplateArgumentDeduction(
5710 S, FT2, Deduced, Info,
5711 [&](Sema &S, FunctionTemplateDecl *FTD,
5712 ArrayRef<TemplateArgument> DeducedArgs) {
5713 // As a provisional fix for a core issue that does not
5714 // exist yet, which may be related to CWG2160, only check the
5715 // consistency of parameters and return types which participated
5716 // in deduction. We will still try to substitute them though.
5717 if (TPOC != TPOC_Call) {
5718 if (auto TDR = ::CheckDeductionConsistency(
5719 S, FTD, /*ArgIdx=*/std::nullopt,
5720 Proto2->getReturnType(), Proto1->getReturnType(),
5721 DeducedArgs,
5722 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5723 TDR != TemplateDeductionResult::Success)
5724 return TDR;
5725 }
5726
5727 if (TPOC == TPOC_Conversion)
5728 return TemplateDeductionResult::Success;
5729
5730 return ::DeduceForEachType(
5731 S, TemplateParams, Args2, Args1, Info, Deduced,
5732 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5733 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5734 UnsignedOrNone ArgIdx, QualType P, QualType A,
5735 TemplateDeductionInfo &Info,
5736 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5737 PartialOrderingKind) {
5738 if (ArgIdx && *ArgIdx >= static_cast<unsigned>(Args1Offset))
5739 ArgIdx = *ArgIdx - Args1Offset;
5740 else
5741 ArgIdx = std::nullopt;
5742 return ::CheckDeductionConsistency(
5743 S, FTD, ArgIdx, P, A, DeducedArgs,
5744 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5745 });
5747 });
5748 if (!AtLeastAsSpecialized || Trap.hasErrorOccurred())
5749 return false;
5750
5751 // C++0x [temp.deduct.partial]p11:
5752 // In most cases, all template parameters must have values in order for
5753 // deduction to succeed, but for partial ordering purposes a template
5754 // parameter may remain without a value provided it is not used in the
5755 // types being used for partial ordering. [ Note: a template parameter used
5756 // in a non-deduced context is considered used. -end note]
5757 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5758 for (; ArgIdx != NumArgs; ++ArgIdx)
5759 if (Deduced[ArgIdx].isNull())
5760 break;
5761
5762 if (ArgIdx == NumArgs) {
5763 // All template arguments were deduced. FT1 is at least as specialized
5764 // as FT2.
5765 return true;
5766 }
5767
5768 // Figure out which template parameters were used.
5769 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5770 switch (TPOC) {
5771 case TPOC_Call:
5772 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5773 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5774 TemplateParams->getDepth(), UsedParameters);
5775 break;
5776
5777 case TPOC_Conversion:
5778 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5779 /*OnlyDeduced=*/false,
5780 TemplateParams->getDepth(), UsedParameters);
5781 break;
5782
5783 case TPOC_Other:
5784 // We do not deduce template arguments from the exception specification
5785 // when determining the primary template of a function template
5786 // specialization or when taking the address of a function template.
5787 // Therefore, we do not mark template parameters in the exception
5788 // specification as used during partial ordering to prevent the following
5789 // from being ambiguous:
5790 //
5791 // template<typename T, typename U>
5792 // void f(U) noexcept(noexcept(T())); // #1
5793 //
5794 // template<typename T>
5795 // void f(T*) noexcept; // #2
5796 //
5797 // template<>
5798 // void f<int>(int*) noexcept; // explicit specialization of #2
5799 //
5800 // Although there is no corresponding wording in the standard, this seems
5801 // to be the intended behavior given the definition of
5802 // 'deduction substitution loci' in [temp.deduct].
5804 S.Context,
5805 S.Context.getFunctionTypeWithExceptionSpec(FD2->getType(), EST_None),
5806 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5807 break;
5808 }
5809
5810 for (; ArgIdx != NumArgs; ++ArgIdx)
5811 // If this argument had no value deduced but was used in one of the types
5812 // used for partial ordering, then deduction fails.
5813 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5814 return false;
5815
5816 return true;
5817}
5818
5820
5821// This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5822// there is no wording or even resolution for this issue.
5825 const TemplateSpecializationType *TST1,
5826 const TemplateSpecializationType *TST2) {
5827 ArrayRef<TemplateArgument> As1 = TST1->template_arguments(),
5828 As2 = TST2->template_arguments();
5829 const TemplateArgument &TA1 = As1.back(), &TA2 = As2.back();
5830 bool IsPack = TA1.getKind() == TemplateArgument::Pack;
5831 assert(IsPack == (TA2.getKind() == TemplateArgument::Pack));
5832 if (!IsPack)
5834 assert(As1.size() == As2.size());
5835
5836 unsigned PackSize1 = TA1.pack_size(), PackSize2 = TA2.pack_size();
5837 bool IsPackExpansion1 =
5838 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5839 bool IsPackExpansion2 =
5840 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5841 if (PackSize1 == PackSize2 && IsPackExpansion1 == IsPackExpansion2)
5843 if (PackSize1 > PackSize2 && IsPackExpansion1)
5845 if (PackSize1 < PackSize2 && IsPackExpansion2)
5848}
5849
5852 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5853 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed,
5854 bool PartialOverloading) {
5857 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5858 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5859 bool ShouldConvert1 = false;
5860 bool ShouldConvert2 = false;
5861 bool Args1Offset = false;
5862 bool Args2Offset = false;
5863 QualType Obj1Ty;
5864 QualType Obj2Ty;
5865 if (TPOC == TPOC_Call) {
5866 const FunctionProtoType *Proto1 =
5867 FD1->getType()->castAs<FunctionProtoType>();
5868 const FunctionProtoType *Proto2 =
5869 FD2->getType()->castAs<FunctionProtoType>();
5870
5871 // - In the context of a function call, the function parameter types are
5872 // used.
5873 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5874 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5875 // C++20 [temp.func.order]p3
5876 // [...] Each function template M that is a member function is
5877 // considered to have a new first parameter of type
5878 // X(M), described below, inserted in its function parameter list.
5879 //
5880 // Note that we interpret "that is a member function" as
5881 // "that is a member function with no expicit object argument".
5882 // Otherwise the ordering rules for methods with expicit objet arguments
5883 // against anything else make no sense.
5884
5885 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
5886 NonStaticMethod2 = Method2 && !Method2->isStatic();
5887
5888 auto Params1Begin = Proto1->param_type_begin(),
5889 Params2Begin = Proto2->param_type_begin();
5890
5891 size_t NumComparedArguments = NumCallArguments1;
5892
5893 if (auto OO = FD1->getOverloadedOperator();
5894 (NonStaticMethod1 && NonStaticMethod2) ||
5895 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
5896 ShouldConvert1 =
5897 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
5898 ShouldConvert2 =
5899 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
5900 NumComparedArguments += 1;
5901
5902 if (ShouldConvert1) {
5903 bool IsRValRef2 =
5904 ShouldConvert2
5905 ? Method2->getRefQualifier() == RQ_RValue
5906 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5907 // Compare 'this' from Method1 against first parameter from Method2.
5908 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
5909 RawObj1Ty, IsRValRef2);
5910 Args1.push_back(Obj1Ty);
5911 Args1Offset = true;
5912 }
5913 if (ShouldConvert2) {
5914 bool IsRValRef1 =
5915 ShouldConvert1
5916 ? Method1->getRefQualifier() == RQ_RValue
5917 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5918 // Compare 'this' from Method2 against first parameter from Method1.
5919 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
5920 RawObj2Ty, IsRValRef1);
5921 Args2.push_back(Obj2Ty);
5922 Args2Offset = true;
5923 }
5924 } else {
5925 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
5926 Params1Begin += 1;
5927 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
5928 Params2Begin += 1;
5929 }
5930 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
5931 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
5932
5933 // C++ [temp.func.order]p5:
5934 // The presence of unused ellipsis and default arguments has no effect on
5935 // the partial ordering of function templates.
5936 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5937 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5938
5939 if (Reversed)
5940 std::reverse(Args2.begin(), Args2.end());
5941 } else {
5942 assert(!Reversed && "Only call context could have reversed arguments");
5943 }
5944 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
5945 Args2, Args2Offset);
5946 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
5947 Args1, Args1Offset);
5948 // C++ [temp.deduct.partial]p10:
5949 // F is more specialized than G if F is at least as specialized as G and G
5950 // is not at least as specialized as F.
5951 if (Better1 != Better2) // We have a clear winner
5952 return Better1 ? FT1 : FT2;
5953
5954 if (!Better1 && !Better2) // Neither is better than the other
5955 return nullptr;
5956
5957 // C++ [temp.deduct.partial]p11:
5958 // ... and if G has a trailing function parameter pack for which F does not
5959 // have a corresponding parameter, and if F does not have a trailing
5960 // function parameter pack, then F is more specialized than G.
5961
5962 SmallVector<QualType> Param1;
5963 Param1.reserve(FD1->param_size() + ShouldConvert1);
5964 if (ShouldConvert1)
5965 Param1.push_back(Obj1Ty);
5966 for (const auto &P : FD1->parameters())
5967 Param1.push_back(P->getType());
5968
5969 SmallVector<QualType> Param2;
5970 Param2.reserve(FD2->param_size() + ShouldConvert2);
5971 if (ShouldConvert2)
5972 Param2.push_back(Obj2Ty);
5973 for (const auto &P : FD2->parameters())
5974 Param2.push_back(P->getType());
5975
5976 unsigned NumParams1 = Param1.size();
5977 unsigned NumParams2 = Param2.size();
5978
5979 bool Variadic1 =
5980 FD1->param_size() && FD1->parameters().back()->isParameterPack();
5981 bool Variadic2 =
5982 FD2->param_size() && FD2->parameters().back()->isParameterPack();
5983 if (Variadic1 != Variadic2) {
5984 if (Variadic1 && NumParams1 > NumParams2)
5985 return FT2;
5986 if (Variadic2 && NumParams2 > NumParams1)
5987 return FT1;
5988 }
5989
5990 // Skip this tie breaker if we are performing overload resolution with partial
5991 // arguments, as this breaks some assumptions about how closely related the
5992 // candidates are.
5993 for (int i = 0, e = std::min(NumParams1, NumParams2);
5994 !PartialOverloading && i < e; ++i) {
5995 QualType T1 = Param1[i].getCanonicalType();
5996 QualType T2 = Param2[i].getCanonicalType();
5997 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5998 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5999 if (!TST1 || !TST2)
6000 continue;
6001 switch (getMoreSpecializedTrailingPackTieBreaker(TST1, TST2)) {
6003 return FT1;
6005 return FT2;
6007 continue;
6008 }
6009 llvm_unreachable(
6010 "unknown MoreSpecializedTrailingPackTieBreakerResult value");
6011 }
6012
6013 if (!Context.getLangOpts().CPlusPlus20)
6014 return nullptr;
6015
6016 // Match GCC on not implementing [temp.func.order]p6.2.1.
6017
6018 // C++20 [temp.func.order]p6:
6019 // If deduction against the other template succeeds for both transformed
6020 // templates, constraints can be considered as follows:
6021
6022 // C++20 [temp.func.order]p6.1:
6023 // If their template-parameter-lists (possibly including template-parameters
6024 // invented for an abbreviated function template ([dcl.fct])) or function
6025 // parameter lists differ in length, neither template is more specialized
6026 // than the other.
6029 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
6030 return nullptr;
6031
6032 // C++20 [temp.func.order]p6.2.2:
6033 // Otherwise, if the corresponding template-parameters of the
6034 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6035 // function parameters that positionally correspond between the two
6036 // templates are not of the same type, neither template is more specialized
6037 // than the other.
6038 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
6040 return nullptr;
6041
6042 // [dcl.fct]p5:
6043 // Any top-level cv-qualifiers modifying a parameter type are deleted when
6044 // forming the function type.
6045 for (unsigned i = 0; i < NumParams1; ++i)
6046 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
6047 return nullptr;
6048
6049 // C++20 [temp.func.order]p6.3:
6050 // Otherwise, if the context in which the partial ordering is done is
6051 // that of a call to a conversion function and the return types of the
6052 // templates are not the same, then neither template is more specialized
6053 // than the other.
6054 if (TPOC == TPOC_Conversion &&
6055 !Context.hasSameType(FD1->getReturnType(), FD2->getReturnType()))
6056 return nullptr;
6057
6059 FT1->getAssociatedConstraints(AC1);
6060 FT2->getAssociatedConstraints(AC2);
6061 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6062 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
6063 return nullptr;
6064 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
6065 return nullptr;
6066 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6067 return nullptr;
6068 return AtLeastAsConstrained1 ? FT1 : FT2;
6069}
6070
6073 TemplateSpecCandidateSet &FailedCandidates,
6074 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
6075 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
6076 bool Complain, QualType TargetType) {
6077 if (SpecBegin == SpecEnd) {
6078 if (Complain) {
6079 Diag(Loc, NoneDiag);
6080 FailedCandidates.NoteCandidates(*this, Loc);
6081 }
6082 return SpecEnd;
6083 }
6084
6085 if (SpecBegin + 1 == SpecEnd)
6086 return SpecBegin;
6087
6088 // Find the function template that is better than all of the templates it
6089 // has been compared to.
6090 UnresolvedSetIterator Best = SpecBegin;
6091 FunctionTemplateDecl *BestTemplate
6092 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6093 assert(BestTemplate && "Not a function template specialization?");
6094 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6095 FunctionTemplateDecl *Challenger
6096 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6097 assert(Challenger && "Not a function template specialization?");
6098 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6099 Loc, TPOC_Other, 0),
6100 Challenger)) {
6101 Best = I;
6102 BestTemplate = Challenger;
6103 }
6104 }
6105
6106 // Make sure that the "best" function template is more specialized than all
6107 // of the others.
6108 bool Ambiguous = false;
6109 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6110 FunctionTemplateDecl *Challenger
6111 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6112 if (I != Best &&
6113 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6114 Loc, TPOC_Other, 0),
6115 BestTemplate)) {
6116 Ambiguous = true;
6117 break;
6118 }
6119 }
6120
6121 if (!Ambiguous) {
6122 // We found an answer. Return it.
6123 return Best;
6124 }
6125
6126 // Diagnose the ambiguity.
6127 if (Complain) {
6128 Diag(Loc, AmbigDiag);
6129
6130 // FIXME: Can we order the candidates in some sane way?
6131 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6132 PartialDiagnostic PD = CandidateDiag;
6133 const auto *FD = cast<FunctionDecl>(*I);
6135 FD->getPrimaryTemplate()->getTemplateParameters(),
6136 *FD->getTemplateSpecializationArgs());
6137 if (!TargetType.isNull())
6138 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6139 Diag((*I)->getLocation(), PD);
6140 }
6141 }
6142
6143 return SpecEnd;
6144}
6145
6147 FunctionDecl *FD2) {
6148 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6149 "not for function templates");
6150 assert(!FD1->isFunctionTemplateSpecialization() ||
6152 assert(!FD2->isFunctionTemplateSpecialization() ||
6154
6155 FunctionDecl *F1 = FD1;
6156 if (FunctionDecl *P = FD1->getTemplateInstantiationPattern(false))
6157 F1 = P;
6158
6159 FunctionDecl *F2 = FD2;
6160 if (FunctionDecl *P = FD2->getTemplateInstantiationPattern(false))
6161 F2 = P;
6162
6164 F1->getAssociatedConstraints(AC1);
6165 F2->getAssociatedConstraints(AC2);
6166 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6167 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6168 return nullptr;
6169 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6170 return nullptr;
6171 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6172 return nullptr;
6173 return AtLeastAsConstrained1 ? FD1 : FD2;
6174}
6175
6176/// Determine whether one template specialization, P1, is at least as
6177/// specialized than another, P2.
6178///
6179/// \tparam TemplateLikeDecl The kind of P2, which must be a
6180/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6181/// \param T1 The injected-class-name of P1 (faked for a variable template).
6182/// \param T2 The injected-class-name of P2 (faked for a variable template).
6183/// \param Template The primary template of P2, in case it is a partial
6184/// specialization, the same as P2 otherwise.
6185template <typename TemplateLikeDecl>
6187 TemplateLikeDecl *P2,
6189 TemplateDeductionInfo &Info) {
6190 // C++ [temp.class.order]p1:
6191 // For two class template partial specializations, the first is at least as
6192 // specialized as the second if, given the following rewrite to two
6193 // function templates, the first function template is at least as
6194 // specialized as the second according to the ordering rules for function
6195 // templates (14.6.6.2):
6196 // - the first function template has the same template parameters as the
6197 // first partial specialization and has a single function parameter
6198 // whose type is a class template specialization with the template
6199 // arguments of the first partial specialization, and
6200 // - the second function template has the same template parameters as the
6201 // second partial specialization and has a single function parameter
6202 // whose type is a class template specialization with the template
6203 // arguments of the second partial specialization.
6204 //
6205 // Rather than synthesize function templates, we merely perform the
6206 // equivalent partial ordering by performing deduction directly on
6207 // the template arguments of the class template partial
6208 // specializations. This computation is slightly simpler than the
6209 // general problem of function template partial ordering, because
6210 // class template partial specializations are more constrained. We
6211 // know that every template parameter is deducible from the class
6212 // template partial specialization's template arguments, for
6213 // example.
6215
6216 // Determine whether P1 is at least as specialized as P2.
6217 Deduced.resize(P2->getTemplateParameters()->size());
6219 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6220 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6221 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6222 return false;
6223
6224 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6227 Sema::SFINAETrap Trap(S, Info);
6228 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs);
6229 if (Inst.isInvalid())
6230 return false;
6231
6233 Ps = cast<TemplateSpecializationType>(T2)->template_arguments(),
6234 As = cast<TemplateSpecializationType>(T1)->template_arguments();
6235
6238 Result = ::FinishTemplateArgumentDeduction(
6239 S, P2, P2->getTemplateParameters(), Template,
6240 /*IsPartialOrdering=*/true, Ps, As, Deduced, Info,
6241 /*CopyDeducedArgs=*/false);
6242 });
6243 return Result == TemplateDeductionResult::Success && !Trap.hasErrorOccurred();
6244}
6245
6246namespace {
6247// A dummy class to return nullptr instead of P2 when performing "more
6248// specialized than primary" check.
6249struct GetP2 {
6250 template <typename T1, typename T2,
6251 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6252 T2 *operator()(T1 *, T2 *P2) {
6253 return P2;
6254 }
6255 template <typename T1, typename T2,
6256 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6257 T1 *operator()(T1 *, T2 *) {
6258 return nullptr;
6259 }
6260};
6261
6262// The assumption is that two template argument lists have the same size.
6263struct TemplateArgumentListAreEqual {
6264 ASTContext &Ctx;
6265 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6266
6267 template <typename T1, typename T2,
6268 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6269 bool operator()(T1 *PS1, T2 *PS2) {
6270 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6271 Args2 = PS2->getTemplateArgs().asArray();
6272
6273 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6274 // We use profile, instead of structural comparison of the arguments,
6275 // because canonicalization can't do the right thing for dependent
6276 // expressions.
6277 llvm::FoldingSetNodeID IDA, IDB;
6278 Args1[I].Profile(IDA, Ctx);
6279 Args2[I].Profile(IDB, Ctx);
6280 if (IDA != IDB)
6281 return false;
6282 }
6283 return true;
6284 }
6285
6286 template <typename T1, typename T2,
6287 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6288 bool operator()(T1 *Spec, T2 *Primary) {
6289 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6290 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6291
6292 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6293 // We use profile, instead of structural comparison of the arguments,
6294 // because canonicalization can't do the right thing for dependent
6295 // expressions.
6296 llvm::FoldingSetNodeID IDA, IDB;
6297 Args1[I].Profile(IDA, Ctx);
6298 // Unlike the specialization arguments, the injected arguments are not
6299 // always canonical.
6300 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6301 if (IDA != IDB)
6302 return false;
6303 }
6304 return true;
6305 }
6306};
6307} // namespace
6308
6309/// Returns the more specialized template specialization between T1/P1 and
6310/// T2/P2.
6311/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6312/// specialization and T2/P2 is the primary template.
6313/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6314///
6315/// \param T1 the type of the first template partial specialization
6316///
6317/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6318/// template partial specialization; otherwise, the type of the
6319/// primary template.
6320///
6321/// \param P1 the first template partial specialization
6322///
6323/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6324/// partial specialization; otherwise, the primary template.
6325///
6326/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6327/// more specialized, returns nullptr if P1 is not more specialized.
6328/// - otherwise, returns the more specialized template partial
6329/// specialization. If neither partial specialization is more
6330/// specialized, returns NULL.
6331template <typename TemplateLikeDecl, typename PrimaryDel>
6332static TemplateLikeDecl *
6333getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6334 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6335 constexpr bool IsMoreSpecialThanPrimaryCheck =
6336 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6337
6338 TemplateDecl *P2T;
6339 if constexpr (IsMoreSpecialThanPrimaryCheck)
6340 P2T = P2;
6341 else
6342 P2T = P2->getSpecializedTemplate();
6343
6344 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, P2T, Info);
6345 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6346 return nullptr;
6347
6348 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1,
6349 P1->getSpecializedTemplate(), Info);
6350 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6351 return P1;
6352
6353 // C++ [temp.deduct.partial]p10:
6354 // F is more specialized than G if F is at least as specialized as G and G
6355 // is not at least as specialized as F.
6356 if (Better1 != Better2) // We have a clear winner
6357 return Better1 ? P1 : GetP2()(P1, P2);
6358
6359 if (!Better1 && !Better2)
6360 return nullptr;
6361
6366 return P1;
6368 return GetP2()(P1, P2);
6370 break;
6371 }
6372
6373 if (!S.Context.getLangOpts().CPlusPlus20)
6374 return nullptr;
6375
6376 // Match GCC on not implementing [temp.func.order]p6.2.1.
6377
6378 // C++20 [temp.func.order]p6:
6379 // If deduction against the other template succeeds for both transformed
6380 // templates, constraints can be considered as follows:
6381
6382 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6383 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6384 if (TPL1->size() != TPL2->size())
6385 return nullptr;
6386
6387 // C++20 [temp.func.order]p6.2.2:
6388 // Otherwise, if the corresponding template-parameters of the
6389 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6390 // function parameters that positionally correspond between the two
6391 // templates are not of the same type, neither template is more specialized
6392 // than the other.
6393 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6395 return nullptr;
6396
6397 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6398 return nullptr;
6399
6401 P1->getAssociatedConstraints(AC1);
6402 P2->getAssociatedConstraints(AC2);
6403 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6404 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6405 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6406 return nullptr;
6407 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6408 return nullptr;
6409 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6410 return nullptr;
6411 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6412}
6413
6425
6428 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6431
6433 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6434 if (MaybeSpec)
6435 Info.clearSFINAEDiagnostic();
6436 return MaybeSpec;
6437}
6438
6443 // Pretend the variable template specializations are class template
6444 // specializations and form a fake injected class name type for comparison.
6445 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6446 "the partial specializations being compared should specialize"
6447 " the same template.");
6449 QualType PT1 = Context.getCanonicalTemplateSpecializationType(
6451 QualType PT2 = Context.getCanonicalTemplateSpecializationType(
6453
6454 TemplateDeductionInfo Info(Loc);
6455 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6456}
6457
6460 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6461 TemplateName Name(Primary->getCanonicalDecl());
6462
6463 SmallVector<TemplateArgument, 8> PrimaryCanonArgs(
6465 Context.canonicalizeTemplateArguments(PrimaryCanonArgs);
6466
6467 QualType PrimaryT = Context.getCanonicalTemplateSpecializationType(
6468 ElaboratedTypeKeyword::None, Name, PrimaryCanonArgs);
6469 QualType PartialT = Context.getCanonicalTemplateSpecializationType(
6471
6473 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6474 if (MaybeSpec)
6475 Info.clearSFINAEDiagnostic();
6476 return MaybeSpec;
6477}
6478
6481 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
6482 bool PartialOrdering, bool *StrictPackMatch) {
6483 // C++1z [temp.arg.template]p4: (DR 150)
6484 // A template template-parameter P is at least as specialized as a
6485 // template template-argument A if, given the following rewrite to two
6486 // function templates...
6487
6488 // Rather than synthesize function templates, we merely perform the
6489 // equivalent partial ordering by performing deduction directly on
6490 // the template parameter lists of the template template parameters.
6491 //
6493
6497 if (Inst.isInvalid())
6498 return false;
6499
6501
6502 // Given an invented class template X with the template parameter list of
6503 // A (including default arguments):
6504 // - Each function template has a single function parameter whose type is
6505 // a specialization of X with template arguments corresponding to the
6506 // template parameters from the respective function template
6508
6509 // Check P's arguments against A's parameter list. This will fill in default
6510 // template arguments as needed. AArgs are already correct by construction.
6511 // We can't just use CheckTemplateIdType because that will expand alias
6512 // templates.
6514 {
6516 P->getRAngleLoc());
6517 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6518 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6519 // expansions, to form an "as written" argument list.
6520 TemplateArgument Arg = PArgs[I];
6521 if (Arg.getKind() == TemplateArgument::Pack) {
6522 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6523 Arg = *Arg.pack_begin();
6524 }
6526 Arg, QualType(), P->getParam(I)->getLocation()));
6527 }
6528 PArgs.clear();
6529
6530 // C++1z [temp.arg.template]p3:
6531 // If the rewrite produces an invalid type, then P is not at least as
6532 // specialized as A.
6534 /*PartialOrdering=*/false, /*MatchingTTP=*/true);
6535 CTAI.SugaredConverted = std::move(PArgs);
6536 if (CheckTemplateArgumentList(AArg, ArgLoc, PArgList, DefaultArgs,
6537 /*PartialTemplateArgs=*/false, CTAI,
6538 /*UpdateArgsWithConversions=*/true,
6539 /*ConstraintsNotSatisfied=*/nullptr))
6540 return false;
6541 PArgs = std::move(CTAI.SugaredConverted);
6542 if (StrictPackMatch)
6543 *StrictPackMatch |= CTAI.StrictPackMatch;
6544 }
6545
6546 // Determine whether P1 is at least as specialized as P2.
6547 TemplateDeductionInfo Info(ArgLoc, A->getDepth());
6549 Deduced.resize(A->size());
6550
6551 // ... the function template corresponding to P is at least as specialized
6552 // as the function template corresponding to A according to the partial
6553 // ordering rules for function templates.
6554
6555 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6556 // applying the partial ordering rules for function templates on
6557 // the rewritten template template parameters:
6558 // - In a deduced context, the matching of packs versus fixed-size needs to
6559 // be inverted between Ps and As. On non-deduced context, matching needs to
6560 // happen both ways, according to [temp.arg.template]p3, but this is
6561 // currently implemented as a special case elsewhere.
6563 *this, A, AArgs, PArgs, Info, Deduced,
6564 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true,
6566 /*HasDeducedAnyParam=*/nullptr)) {
6568 if (StrictPackMatch && Info.hasStrictPackMatch())
6569 *StrictPackMatch = true;
6570 break;
6571
6573 Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
6574 << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
6576 return false;
6578 Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
6579 << Info.FirstArg << Info.SecondArg;
6580 return false;
6583 diag::err_inconsistent_deduction)
6584 << Info.FirstArg << Info.SecondArg;
6585 return false;
6587 return false;
6588
6589 // None of these should happen for a plain deduction.
6604 llvm_unreachable("Unexpected Result");
6605 }
6606
6609 TDK = ::FinishTemplateArgumentDeduction(
6610 *this, AArg, AArg->getTemplateParameters(), AArg, PartialOrdering,
6611 AArgs, PArgs, Deduced, Info, /*CopyDeducedArgs=*/false);
6612 });
6613 switch (TDK) {
6615 return true;
6616
6617 // It doesn't seem possible to get a non-deduced mismatch when partial
6618 // ordering TTPs, except with an invalid template parameter list which has
6619 // a parameter after a pack.
6621 assert(PArg->isInvalidDecl() && "Unexpected NonDeducedMismatch");
6622 return false;
6623
6624 // Substitution failures should have already been diagnosed.
6628 return false;
6629
6630 // None of these should happen when just converting deduced arguments.
6645 llvm_unreachable("Unexpected Result");
6646 }
6647 llvm_unreachable("Unexpected TDK");
6648}
6649
6650namespace {
6651struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6652 llvm::SmallBitVector &Used;
6653 unsigned Depth;
6654 bool VisitDeclRefTypes = true;
6655
6656 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, unsigned Depth,
6657 bool VisitDeclRefTypes = true)
6658 : Used(Used), Depth(Depth), VisitDeclRefTypes(VisitDeclRefTypes) {}
6659
6660 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6661 if (T->getDepth() == Depth)
6662 Used[T->getIndex()] = true;
6663 return true;
6664 }
6665
6666 bool TraverseTemplateName(TemplateName Template) override {
6667 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6668 Template.getAsTemplateDecl()))
6669 if (TTP->getDepth() == Depth)
6670 Used[TTP->getIndex()] = true;
6672 return true;
6673 }
6674
6675 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6676 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6677 if (NTTP->getDepth() == Depth)
6678 Used[NTTP->getIndex()] = true;
6679 if (VisitDeclRefTypes)
6681 return true;
6682 }
6683
6684 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
6685 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
6686 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
6687 if (TTP->getDepth() == Depth)
6688 Used[TTP->getIndex()] = true;
6689 }
6690 for (auto &TLoc : ULE->template_arguments())
6692 }
6693 return true;
6694 }
6695
6696 bool TraverseSizeOfPackExpr(SizeOfPackExpr *SOPE) override {
6697 return TraverseDecl(SOPE->getPack());
6698 }
6699};
6700}
6701
6702/// Mark the template parameters that are used by the given
6703/// expression.
6704static void
6706 const Expr *E,
6707 bool OnlyDeduced,
6708 unsigned Depth,
6709 llvm::SmallBitVector &Used) {
6710 if (!OnlyDeduced) {
6711 MarkUsedTemplateParameterVisitor(Used, Depth)
6712 .TraverseStmt(const_cast<Expr *>(E));
6713 return;
6714 }
6715
6716 // We can deduce from a pack expansion.
6717 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6718 E = Expansion->getPattern();
6719
6721 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E);
6722 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
6723 if (const auto *TTP = ULE->getTemplateTemplateDecl())
6724 Used[TTP->getIndex()] = true;
6725 for (auto &TLoc : ULE->template_arguments())
6726 MarkUsedTemplateParameters(Ctx, TLoc.getArgument(), OnlyDeduced, Depth,
6727 Used);
6728 return;
6729 }
6730
6731 const NonTypeOrVarTemplateParmDecl NTTP =
6733 if (!NTTP)
6734 return;
6735 if (NTTP.getDepth() == Depth)
6736 Used[NTTP.getIndex()] = true;
6737
6738 // In C++17 mode, additional arguments may be deduced from the type of a
6739 // non-type argument.
6740 if (Ctx.getLangOpts().CPlusPlus17)
6741 MarkUsedTemplateParameters(Ctx, NTTP.getType(), OnlyDeduced, Depth, Used);
6742}
6743
6744/// Mark the template parameters that are used by the given
6745/// nested name specifier.
6747 bool OnlyDeduced, unsigned Depth,
6748 llvm::SmallBitVector &Used) {
6750 return;
6751 MarkUsedTemplateParameters(Ctx, QualType(NNS.getAsType(), 0), OnlyDeduced,
6752 Depth, Used);
6753}
6754
6755/// Mark the template parameters that are used by the given
6756/// template name.
6757static void
6759 TemplateName Name,
6760 bool OnlyDeduced,
6761 unsigned Depth,
6762 llvm::SmallBitVector &Used) {
6763 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6765 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6766 if (TTP->getDepth() == Depth)
6767 Used[TTP->getIndex()] = true;
6768 }
6769 return;
6770 }
6771
6773 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6774 Depth, Used);
6776 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6777 Depth, Used);
6778}
6779
6780/// Mark the template parameters that are used by the given
6781/// type.
6782static void
6784 bool OnlyDeduced,
6785 unsigned Depth,
6786 llvm::SmallBitVector &Used) {
6787 if (T.isNull())
6788 return;
6789
6790 // Non-dependent types have nothing deducible
6791 if (!T->isDependentType())
6792 return;
6793
6794 T = Ctx.getCanonicalType(T);
6795 switch (T->getTypeClass()) {
6796 case Type::Pointer:
6799 OnlyDeduced,
6800 Depth,
6801 Used);
6802 break;
6803
6804 case Type::BlockPointer:
6807 OnlyDeduced,
6808 Depth,
6809 Used);
6810 break;
6811
6812 case Type::LValueReference:
6813 case Type::RValueReference:
6816 OnlyDeduced,
6817 Depth,
6818 Used);
6819 break;
6820
6821 case Type::MemberPointer: {
6822 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6823 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6824 Depth, Used);
6826 QualType(MemPtr->getQualifier().getAsType(), 0),
6827 OnlyDeduced, Depth, Used);
6828 break;
6829 }
6830
6831 case Type::DependentSizedArray:
6833 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6834 OnlyDeduced, Depth, Used);
6835 // Fall through to check the element type
6836 [[fallthrough]];
6837
6838 case Type::ConstantArray:
6839 case Type::IncompleteArray:
6840 case Type::ArrayParameter:
6842 cast<ArrayType>(T)->getElementType(),
6843 OnlyDeduced, Depth, Used);
6844 break;
6845 case Type::Vector:
6846 case Type::ExtVector:
6848 cast<VectorType>(T)->getElementType(),
6849 OnlyDeduced, Depth, Used);
6850 break;
6851
6852 case Type::DependentVector: {
6853 const auto *VecType = cast<DependentVectorType>(T);
6854 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6855 Depth, Used);
6856 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6857 Used);
6858 break;
6859 }
6860 case Type::DependentSizedExtVector: {
6861 const DependentSizedExtVectorType *VecType
6863 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6864 Depth, Used);
6865 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6866 Depth, Used);
6867 break;
6868 }
6869
6870 case Type::DependentAddressSpace: {
6871 const DependentAddressSpaceType *DependentASType =
6873 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6874 OnlyDeduced, Depth, Used);
6876 DependentASType->getAddrSpaceExpr(),
6877 OnlyDeduced, Depth, Used);
6878 break;
6879 }
6880
6881 case Type::ConstantMatrix: {
6882 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6883 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6884 Depth, Used);
6885 break;
6886 }
6887
6888 case Type::DependentSizedMatrix: {
6890 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6891 Depth, Used);
6892 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6893 Used);
6894 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6895 Depth, Used);
6896 break;
6897 }
6898
6899 case Type::FunctionProto: {
6901 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6902 Used);
6903 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6904 // C++17 [temp.deduct.type]p5:
6905 // The non-deduced contexts are: [...]
6906 // -- A function parameter pack that does not occur at the end of the
6907 // parameter-declaration-list.
6908 if (!OnlyDeduced || I + 1 == N ||
6909 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6910 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6911 Depth, Used);
6912 } else {
6913 // FIXME: C++17 [temp.deduct.call]p1:
6914 // When a function parameter pack appears in a non-deduced context,
6915 // the type of that pack is never deduced.
6916 //
6917 // We should also track a set of "never deduced" parameters, and
6918 // subtract that from the list of deduced parameters after marking.
6919 }
6920 }
6921 if (auto *E = Proto->getNoexceptExpr())
6922 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6923 break;
6924 }
6925
6926 case Type::TemplateTypeParm: {
6927 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6928 if (TTP->getDepth() == Depth)
6929 Used[TTP->getIndex()] = true;
6930 break;
6931 }
6932
6933 case Type::SubstTemplateTypeParmPack: {
6934 const SubstTemplateTypeParmPackType *Subst
6936 if (Subst->getReplacedParameter()->getDepth() == Depth)
6937 Used[Subst->getIndex()] = true;
6938 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), OnlyDeduced,
6939 Depth, Used);
6940 break;
6941 }
6942 case Type::SubstBuiltinTemplatePack: {
6943 MarkUsedTemplateParameters(Ctx, cast<SubstPackType>(T)->getArgumentPack(),
6944 OnlyDeduced, Depth, Used);
6945 break;
6946 }
6947
6948 case Type::InjectedClassName:
6950 ->getDecl()
6951 ->getCanonicalTemplateSpecializationType(Ctx);
6952 [[fallthrough]];
6953
6954 case Type::TemplateSpecialization: {
6955 const TemplateSpecializationType *Spec
6957
6958 TemplateName Name = Spec->getTemplateName();
6959 if (OnlyDeduced && Name.getAsDependentTemplateName())
6960 break;
6961
6962 MarkUsedTemplateParameters(Ctx, Name, OnlyDeduced, Depth, Used);
6963
6964 // C++0x [temp.deduct.type]p9:
6965 // If the template argument list of P contains a pack expansion that is
6966 // not the last template argument, the entire template argument list is a
6967 // non-deduced context.
6968 if (OnlyDeduced &&
6969 hasPackExpansionBeforeEnd(Spec->template_arguments()))
6970 break;
6971
6972 for (const auto &Arg : Spec->template_arguments())
6973 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6974 break;
6975 }
6976
6977 case Type::Complex:
6978 if (!OnlyDeduced)
6980 cast<ComplexType>(T)->getElementType(),
6981 OnlyDeduced, Depth, Used);
6982 break;
6983
6984 case Type::Atomic:
6985 if (!OnlyDeduced)
6987 cast<AtomicType>(T)->getValueType(),
6988 OnlyDeduced, Depth, Used);
6989 break;
6990
6991 case Type::DependentName:
6992 if (!OnlyDeduced)
6994 cast<DependentNameType>(T)->getQualifier(),
6995 OnlyDeduced, Depth, Used);
6996 break;
6997
6998 case Type::TypeOf:
6999 if (!OnlyDeduced)
7000 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
7001 OnlyDeduced, Depth, Used);
7002 break;
7003
7004 case Type::TypeOfExpr:
7005 if (!OnlyDeduced)
7007 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
7008 OnlyDeduced, Depth, Used);
7009 break;
7010
7011 case Type::Decltype:
7012 if (!OnlyDeduced)
7014 cast<DecltypeType>(T)->getUnderlyingExpr(),
7015 OnlyDeduced, Depth, Used);
7016 break;
7017
7018 case Type::PackIndexing:
7019 if (!OnlyDeduced) {
7021 OnlyDeduced, Depth, Used);
7022 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
7023 OnlyDeduced, Depth, Used);
7024 }
7025 break;
7026
7027 case Type::UnaryTransform:
7028 if (!OnlyDeduced) {
7029 auto *UTT = cast<UnaryTransformType>(T);
7030 auto Next = UTT->getUnderlyingType();
7031 if (Next.isNull())
7032 Next = UTT->getBaseType();
7033 MarkUsedTemplateParameters(Ctx, Next, OnlyDeduced, Depth, Used);
7034 }
7035 break;
7036
7037 case Type::PackExpansion:
7039 cast<PackExpansionType>(T)->getPattern(),
7040 OnlyDeduced, Depth, Used);
7041 break;
7042
7043 case Type::Auto:
7044 case Type::DeducedTemplateSpecialization:
7046 cast<DeducedType>(T)->getDeducedType(),
7047 OnlyDeduced, Depth, Used);
7048 break;
7049 case Type::DependentBitInt:
7051 cast<DependentBitIntType>(T)->getNumBitsExpr(),
7052 OnlyDeduced, Depth, Used);
7053 break;
7054
7055 case Type::HLSLAttributedResource:
7057 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
7058 Depth, Used);
7059 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
7061 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
7062 OnlyDeduced, Depth, Used);
7063 break;
7064
7065 // None of these types have any template parameters in them.
7066 case Type::Builtin:
7067 case Type::VariableArray:
7068 case Type::FunctionNoProto:
7069 case Type::Record:
7070 case Type::Enum:
7071 case Type::ObjCInterface:
7072 case Type::ObjCObject:
7073 case Type::ObjCObjectPointer:
7074 case Type::UnresolvedUsing:
7075 case Type::Pipe:
7076 case Type::BitInt:
7077 case Type::HLSLInlineSpirv:
7078 case Type::OverflowBehavior:
7079#define TYPE(Class, Base)
7080#define ABSTRACT_TYPE(Class, Base)
7081#define DEPENDENT_TYPE(Class, Base)
7082#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7083#include "clang/AST/TypeNodes.inc"
7084 break;
7085 }
7086}
7087
7088/// Mark the template parameters that are used by this
7089/// template argument.
7090static void
7093 bool OnlyDeduced,
7094 unsigned Depth,
7095 llvm::SmallBitVector &Used) {
7096 switch (TemplateArg.getKind()) {
7102 break;
7103
7105 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
7106 Depth, Used);
7107 break;
7108
7112 TemplateArg.getAsTemplateOrTemplatePattern(),
7113 OnlyDeduced, Depth, Used);
7114 break;
7115
7117 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
7118 Depth, Used);
7119 break;
7120
7122 for (const auto &P : TemplateArg.pack_elements())
7123 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
7124 break;
7125 }
7126}
7127
7128void
7129Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7130 unsigned Depth,
7131 llvm::SmallBitVector &Used) {
7132 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
7133}
7134
7136 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used) {
7137 MarkUsedTemplateParameterVisitor(Used, Depth, /*VisitDeclRefTypes=*/false)
7138 .TraverseStmt(const_cast<Expr *>(E));
7139}
7140
7141void
7143 bool OnlyDeduced, unsigned Depth,
7144 llvm::SmallBitVector &Used) {
7145 // C++0x [temp.deduct.type]p9:
7146 // If the template argument list of P contains a pack expansion that is not
7147 // the last template argument, the entire template argument list is a
7148 // non-deduced context.
7149 if (OnlyDeduced &&
7150 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
7151 return;
7152
7153 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7154 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
7155 Depth, Used);
7156}
7157
7159 unsigned Depth,
7160 llvm::SmallBitVector &Used) {
7161 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7162 ::MarkUsedTemplateParameters(Context, TemplateArgs[I],
7163 /*OnlyDeduced=*/false, Depth, Used);
7164}
7165
7167 ArrayRef<TemplateArgumentLoc> TemplateArgs, unsigned Depth,
7168 llvm::SmallBitVector &Used) {
7169 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7171 /*OnlyDeduced=*/false, Depth, Used);
7172}
7173
7176 llvm::SmallBitVector &Deduced) {
7177 TemplateParameterList *TemplateParams
7178 = FunctionTemplate->getTemplateParameters();
7179 Deduced.clear();
7180 Deduced.resize(TemplateParams->size());
7181
7182 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
7183 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
7184 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
7185 true, TemplateParams->getDepth(), Deduced);
7186}
7187
7190 QualType T) {
7191 if (!T->isDependentType())
7192 return false;
7193
7194 TemplateParameterList *TemplateParams
7195 = FunctionTemplate->getTemplateParameters();
7196 llvm::SmallBitVector Deduced(TemplateParams->size());
7197 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
7198 Deduced);
7199
7200 return Deduced.any();
7201}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Provides definitions for the various language-specific address spaces.
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
FormatToken * Next
The next token in the unwrapped line.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static TemplateDeductionResult DeduceNullPtrTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, NonTypeOrVarTemplateParmDecl NTTP, QualType NullPtrType, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Deduce the value of the given non-type template parameter from the given null pointer template argume...
static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, TemplateDeductionInfo &Info, bool IsDeduced, Sema::CheckTemplateArgumentInfo &CTAI)
Convert the given deduced template argument and add it to the set of fully-converted template argumen...
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static TemplateDeductionResult DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams, const QualType P, QualType A, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(Sema &S, TemplateParameterList *TemplateParams, QualType Param, QualType Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF, PartialOrderingKind POK, bool DeducedFromArrayBound, bool *HasDeducedAnyParam)
Deduce the template arguments by comparing the parameter type and the argument type (C++ [temp....
static TemplateDeductionResult CheckDeductionConsistency(Sema &S, FunctionTemplateDecl *FTD, UnsignedOrNone ArgIdx, QualType P, QualType A, ArrayRef< TemplateArgument > DeducedArgs, bool CheckConsistency)
static PartialOrderingKind degradeCallPartialOrderingKind(PartialOrderingKind POK)
When propagating a partial ordering kind into a NonCall context, this is used to downgrade a 'Call' i...
static MoreSpecializedTrailingPackTieBreakerResult getMoreSpecializedTrailingPackTieBreaker(const TemplateSpecializationType *TST1, const TemplateSpecializationType *TST2)
static TemplateLikeDecl * getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1, PrimaryDel *P2, TemplateDeductionInfo &Info)
Returns the more specialized template specialization between T1/P1 and T2/P2.
static DeducedTemplateArgument checkDeducedTemplateArguments(ASTContext &Context, const DeducedTemplateArgument &X, const DeducedTemplateArgument &Y, bool AggregateCandidateDeduction=false)
Verify that the given, deduced template arguments are compatible.
static const Expr * unwrapExpressionForDeduction(const Expr *E)
static bool isSameDeclaration(Decl *X, Decl *Y)
Determine whether two declaration pointers refer to the same declaration.
static NonTypeOrVarTemplateParmDecl getDeducedNTTParameterFromExpr(const Expr *E, unsigned Depth)
If the given expression is of a form that permits the deduction of a non-type template parameter,...
static TemplateDeductionResult DeduceForEachType(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< QualType > Params, ArrayRef< QualType > Args, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, PartialOrderingKind POK, bool FinishingDeduction, T &&DeductFunc)
static TemplateDeductionResult DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD, TemplateParameterList *TemplateParams, QualType P, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Attempt to deduce the template arguments by checking the base types according to (C++20 [temp....
static bool hasTemplateArgumentForDeduction(ArrayRef< TemplateArgument > &Args, unsigned &ArgIdx)
Determine whether there is a template argument to be used for deduction.
static DeclContext * getAsDeclContextOrEnclosing(Decl *D)
static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, QualType ArgType)
Determine whether the parameter has qualifiers that the argument lacks.
static void MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
static UnsignedOrNone getPackIndexForParam(Sema &S, FunctionTemplateDecl *FunctionTemplate, const MultiLevelTemplateArgumentList &Args, unsigned ParamIdx)
Find the pack index for a particular parameter index in an instantiation of a function template with ...
static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, FunctionDecl *Fn)
Gets the type of a function for template-argument-deducton purposes when it's considered as part of a...
static bool hasPackExpansionBeforeEnd(ArrayRef< TemplateArgument > Args)
Determine whether the given set of template arguments has a pack expansion that is not the last templ...
static bool isSimpleTemplateIdType(QualType T)
Determine whether the given type T is a simple-template-id type.
PartialOrderingKind
The kind of PartialOrdering we're performing template argument deduction for (C++11 [temp....
MoreSpecializedTrailingPackTieBreakerResult
static TemplateParameter makeTemplateParameter(Decl *D)
Helper function to build a TemplateParameter when we don't know its type statically.
static TemplateDeductionResult CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, Sema::OriginalCallArg OriginalArg, QualType DeducedA)
Check whether the deduced argument type for a call to a function template matches the actual argument...
static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType &ParamType, QualType &ArgType, Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform the adjustments to the parameter and argument types described in C++ [temp....
static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType ParamType, QualType ArgType, Expr::Classification ArgClassification, Expr *Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, bool DecomposedParam, unsigned ArgIdx, unsigned TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform template argument deduction per [temp.deduct.call] for a single parameter / argument pair.
static bool isAtLeastAsSpecializedAs(Sema &S, SourceLocation Loc, FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC, ArrayRef< QualType > Args1, ArrayRef< QualType > Args2, bool Args1Offset)
Determine whether the function template FT1 is at least as specialized as FT2.
static QualType GetImplicitObjectParameterType(ASTContext &Context, const CXXMethodDecl *Method, QualType RawType, bool IsOtherRvr)
static TemplateDeductionResult DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, InitListExpr *ILE, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, unsigned ArgIdx, unsigned TDF)
Attempt template argument deduction from an initializer list deemed to be an argument in a function c...
static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD)
Get the index of the first template parameter that was originally from the innermost template-paramet...
PackFold
What directions packs are allowed to match non-packs.
static TemplateDeductionResult ConvertDeducedTemplateArguments(Sema &S, NamedDecl *Template, TemplateParameterList *TemplateParams, bool IsDeduced, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info, Sema::CheckTemplateArgumentInfo &CTAI, LocalInstantiationScope *CurrentInstantiationScope, unsigned NumAlreadyConverted, bool *IsIncomplete)
static QualType ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, Expr *Arg, QualType ParamType, bool ParamWasReference, TemplateSpecCandidateSet *FailedTSC=nullptr)
Apply the deduction rules for overload sets.
static bool IsPossiblyOpaquelyQualifiedType(QualType T)
Determines whether the given type is an opaque type that might be more qualified when instantiated.
static TemplateDeductionResult CheckDeducedArgumentConstraints(Sema &S, NamedDecl *Template, ArrayRef< TemplateArgument > SugaredDeducedArgs, ArrayRef< TemplateArgument > CanonicalDeducedArgs, TemplateDeductionInfo &Info)
static const TemplateSpecializationType * getLastTemplateSpecType(QualType QT)
Deduce the template arguments by comparing the template parameter type (which is a template-id) with ...
static TemplateDeductionResult instantiateExplicitSpecifierDeferred(Sema &S, FunctionDecl *Specialization, const MultiLevelTemplateArgumentList &SubstArgs, TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate, ArrayRef< TemplateArgument > DeducedArgs)
static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type, AutoTypeLoc TypeLoc, QualType Deduced)
static TemplateDeductionResult DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, const NonTypeOrVarTemplateParmDecl NTTP, const DeducedTemplateArgument &NewDeduced, QualType ValueType, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Deduce the value of the given non-type template parameter as the given deduced template argument.
static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T)
static bool hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, QualType T)
static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex)
Determine whether a type denotes a forwarding reference.
static TemplateDeductionResult FinishTemplateArgumentDeduction(Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL, TemplateDecl *Template, bool PartialOrdering, ArrayRef< TemplateArgumentLoc > Ps, ArrayRef< TemplateArgument > As, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info, bool CopyDeducedArgs)
Complete template argument deduction.
static bool isParameterPack(Expr *PackExpression)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TemplateNameKind enum.
Defines the clang::TypeLoc interface and its subclasses.
Allows QualTypes to be sorted and hence used in maps and sets.
static const TemplateArgument & getArgument(const TemplateArgument &A)
C Language Family Type Representation.
const TemplateTemplateParmDecl * getTemplate() const
const NonTypeTemplateParmDecl * getNTTP() const
NonTypeOrVarTemplateParmDecl(const NamedDecl *Template)
TemplateParameter asTemplateParam() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
CanQualType NullPtrTy
const LangOptions & getLangOpts() const
Definition ASTContext.h:952
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
CanQualType BoolTy
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
CanQualType OverloadTy
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedIntTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y, bool IgnoreDeduced=false) const
Determine whether the given template names refer to the same template.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isSameTemplateArgument(const TemplateArgument &Arg1, const TemplateArgument &Arg2) const
Determine whether the given template arguments Arg1 and Arg2 are equivalent.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
TemplateName getDeducedTemplateName(TemplateName Underlying, DefaultArguments DefaultArgs) const
Represents a TemplateName which had some of its default arguments deduced.
QualType getDeducedTemplateSpecializationType(DeducedKind DK, QualType DeducedAsType, ElaboratedTypeKeyword Keyword, TemplateName Template) const
C++17 deduced class template specialization type.
const DependentSizedArrayType * getAsDependentSizedArrayType(QualType T) const
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8283
Pointer to a block type.
Definition TypeBase.h:3592
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2946
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2986
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2721
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition DeclCXX.h:2312
bool isStatic() const
Definition DeclCXX.cpp:2419
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:769
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_range bases()
Definition DeclCXX.h:608
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
Declaration of a class template.
CanQualType getCanonicalInjectedSpecializationType(const ASTContext &Ctx) const
Retrieve the canonical template specialization type of the injected-class-name for this class templat...
CanQualType getCanonicalInjectedSpecializationType(const ASTContext &Ctx) const
Retrieves the canonical injected specialization type for this partial specialization.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3325
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4437
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4456
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4453
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
A POD class for pairing a NamedDecl* with an access specifier.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
ValueDecl * getDecl()
Definition Expr.h:1341
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition Template.h:333
void setDeducedFromArrayBound(bool Deduced)
Specify whether the given non-type template argument was deduced from an array bound.
Definition Template.h:360
bool wasDeducedFromArrayBound() const
For a non-type template argument, determine whether the template argument was deduced from an array b...
Definition Template.h:356
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:2509
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:2521
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4111
QualType getPointeeType() const
Definition TypeBase.h:4123
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4151
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4523
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4277
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
virtual bool TraverseTemplateName(TemplateName Template)
virtual bool TraverseType(QualType T, bool TraverseQualifier=true)
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1931
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition DeclCXX.h:1960
const Expr * getExpr() const
Definition DeclCXX.h:1940
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
This represents one expression.
Definition Expr.h:112
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3082
QualType getType() const
Definition Expr.h:144
ExtVectorType - Extended vector type.
Definition TypeBase.h:4317
Stores a list of template parameters and the associated requires-clause (if any) for a TemplateDecl a...
Represents a function declaration or definition.
Definition Decl.h:2015
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2812
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4207
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3867
QualType getReturnType() const
Definition Decl.h:2860
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2789
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4266
void getAssociatedConstraints(SmallVectorImpl< AssociatedConstraint > &ACs) const
Get the associated-constraints of this function declaration.
Definition Decl.h:2767
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4331
bool isImmediateEscalating() const
Definition Decl.cpp:3313
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4132
size_t param_size() const
Definition Decl.h:2805
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
param_type_iterator param_type_begin() const
Definition TypeBase.h:5801
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition TypeBase.h:5839
unsigned getNumParams() const
Definition TypeBase.h:5635
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5777
Qualifiers getMethodQuals() const
Definition TypeBase.h:5783
QualType getParamType(unsigned i) const
Definition TypeBase.h:5637
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5670
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5761
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5646
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5722
param_type_iterator param_type_end() const
Definition TypeBase.h:5805
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5642
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5791
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
QualType getReturnType() const
Definition TypeBase.h:4893
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Describes an C or C++ initializer list.
Definition Expr.h:5302
unsigned getNumInits() const
Definition Expr.h:5332
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5336
ArrayRef< Expr * > inits()
Definition Expr.h:5352
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3667
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:371
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
void ResetPartiallySubstitutedPack()
Reset the partially-substituted pack when it is no longer of interest.
Definition Template.h:559
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4387
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4401
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3703
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3735
QualType getPointeeType() const
Definition TypeBase.h:3721
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:266
void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final=false)
Replaces the current 'innermost' level with the provided argument list.
Definition Template.h:239
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Class that aids in the construction of nested-name-specifiers along with source-location information ...
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents a pointer to an Objective C object.
Definition TypeBase.h:8049
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3129
bool isVarDeclReference() const
Definition ExprCXX.h:3303
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3281
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3190
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3242
decls_iterator decls_begin() const
Definition ExprCXX.h:3222
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition ExprCXX.h:3319
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3343
bool isConceptReference() const
Definition ExprCXX.h:3292
decls_iterator decls_end() const
Definition ExprCXX.h:3225
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition ExprCXX.h:3338
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4364
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:277
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
A (possibly-)qualified type.
Definition TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8520
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8431
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8557
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8471
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8616
QualType getCanonicalType() const
Definition TypeBase.h:8483
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8525
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8477
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
GC getObjCGCAttr() const
Definition TypeBase.h:519
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
void removeObjCLifetime()
Definition TypeBase.h:551
bool isStrictSupersetOf(Qualifiers Other) const
Determine whether this set of qualifiers is a strict superset of another set of qualifiers,...
Definition Type.cpp:57
bool hasConst() const
Definition TypeBase.h:457
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition TypeBase.h:559
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasAddressSpace() const
Definition TypeBase.h:570
void removeObjCGCAttr()
Definition TypeBase.h:523
void removeAddressSpace()
Definition TypeBase.h:596
bool hasObjCGCAttr() const
Definition TypeBase.h:518
void setCVRQualifiers(unsigned mask)
Definition TypeBase.h:491
bool hasObjCLifetime() const
Definition TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:533
LangAS getAddressSpace() const
Definition TypeBase.h:571
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3685
ArrayRef< TemplateArgument > getInjectedTemplateArgs(const ASTContext &Context) const
Retrieve the "injected" template arguments that correspond to the template parameters of this templat...
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3623
QualType getPointeeType() const
Definition TypeBase.h:3641
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13746
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8523
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
A helper class for building up ExtParameterInfos.
Definition Sema.h:13110
const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams)
Return a pointer (suitable for setting in an ExtProtoInfo) to the ExtParameterInfo array we've built ...
Definition Sema.h:13129
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12542
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12576
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13139
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.
TemplateDeductionResult DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, sema::TemplateDeductionInfo &Info)
Deduce the template arguments of the given template from FromType.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
SemaCUDA & CUDA()
Definition Sema.h:1473
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7000
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
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...
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl< OriginalCallArg > const *OriginalCallArgs, bool PartialOverloading, bool PartialOrdering, bool ForOverloadSetAddressResolution, llvm::function_ref< bool(bool)> CheckNonDependent=[](bool) { return false;})
Finish template argument deduction for a function template, checking the deduced template arguments f...
@ CTAK_DeducedFromArrayBound
The template argument was deduced from an array bound via template argument deduction.
Definition Sema.h:12063
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12055
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12059
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1308
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void MarkUsedTemplateParametersForSubsumptionParameterMapping(const Expr *E, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are named in a given expression.
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ASTContext & getASTContext() const
Definition Sema.h:939
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
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.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg, const DefaultArguments &DefaultArgs, SourceLocation ArgLoc, bool PartialOrdering, bool *StrictPackMatch)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition Sema.h:12260
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.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
const LangOptions & getLangOpts() const
Definition Sema.h:932
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
TemplateDeductionResult SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< QualType > &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info)
Substitute the explicitly-provided template arguments into the given function template according to C...
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
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...
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition Sema.h:12613
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8252
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
bool isSFINAEContext() const
Definition Sema.h:13784
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15555
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters are used in a given expression.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6811
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6780
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
bool IsAtLeastAsConstrained(const NamedDecl *D1, MutableArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, MutableArrayRef< AssociatedConstraint > AC2, bool &Result)
Check whether the given declaration's associated constraints are at least as constrained than another...
void DiagnoseAutoDeductionFailure(const VarDecl *VDecl, const Expr *Init)
TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location)
Get a template argument mapping the given template parameter to itself, e.g.
bool CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD, SourceLocation Loc)
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
bool CheckFunctionTemplateConstraints(SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef< TemplateArgument > TemplateArgs, ConstraintSatisfaction &Satisfaction)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs, bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions=true, bool *ConstraintsNotSatisfied=nullptr)
Check that the given template arguments can be provided to the given template, converting the argumen...
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6488
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition Sema.h:12982
NamedDecl * getPack() const
Retrieve the parameter pack.
Definition ExprCXX.h:4510
Encodes a location in the source.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
A convenient class for passing around template argument information.
void addArgument(const TemplateArgumentLoc &Loc)
A template argument list.
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
Represents a template argument.
QualType getParamTypeForDecl() const
Expr * getAsExpr() const
Retrieve the template argument as an expression.
pack_iterator pack_end() const
Iterator referencing one past the last argument of a template argument pack.
const TemplateArgument * pack_iterator
Iterator that traverses the elements of a template argument pack.
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const
Used to insert TemplateArguments into FoldingSets.
QualType getAsType() const
Retrieve the type for a type template argument.
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
static TemplateArgument getEmptyPack()
unsigned pack_size() const
The number of template arguments in the given template argument pack.
bool structurallyEquals(const TemplateArgument &Other) const
Determines whether two template arguments are superficially the same.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Template
The template argument is a template name that was provided for a template template parameter.
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
@ Pack
The template argument is actually a parameter pack.
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
@ Type
The template argument is a type.
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
The base class of all kinds of template declarations (e.g., class, function, etc.).
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
bool isTypeAlias() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
ArrayRef< TemplateArgument > getInjectedTemplateArgs(const ASTContext &Context)
Get the template argument list of the template parameter list.
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
SourceLocation getRAngleLoc() const
SourceLocation getLAngleLoc() const
ArrayRef< NamedDecl * > asArray()
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
Declaration of a template type parameter.
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, UnsignedOrNone NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
const Type * getTypeForDecl() const
Definition Decl.h:3553
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition TypeLoc.h:165
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition TypeLoc.cpp:169
A container of type source information.
Definition TypeBase.h:8402
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8413
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1866
bool isVoidType() const
Definition TypeBase.h:9034
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:1935
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition TypeBase.h:9010
bool isRValueReferenceType() const
Definition TypeBase.h:8700
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8767
bool isFunctionPointerType() const
Definition TypeBase.h:8735
bool isPointerType() const
Definition TypeBase.h:8668
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9328
bool isReferenceType() const
Definition TypeBase.h:8692
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:754
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2949
bool isLValueReferenceType() const
Definition TypeBase.h:8696
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2832
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3169
bool isMemberPointerType() const
Definition TypeBase.h:8749
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5389
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9177
bool isFunctionType() const
Definition TypeBase.h:8664
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8753
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2971
bool isAnyPointerType() const
Definition TypeBase.h:8676
TypeClass getTypeClass() const
Definition TypeBase.h:2433
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
bool isRecordType() const
Definition TypeBase.h:8795
The iterator over UnresolvedSets.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:926
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1593
Declaration of a variable template.
VarTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Represents a GCC generic vector type.
Definition TypeBase.h:4225
Provides information about an attempted template argument deduction, whose success or failure was des...
void setExplicitArgs(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide an initial template argument list that contains the explicitly-specified arguments.
TemplateArgumentList * takeCanonical()
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
void clearSFINAEDiagnostic()
Discard any SFINAE diagnostics.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
diag_iterator diag_end() const
Returns an iterator at the end of the sequence of suppressed diagnostics.
void reset(TemplateArgumentList *NewDeducedSugared, TemplateArgumentList *NewDeducedCanonical)
Provide a new template argument list that contains the results of template argument deduction.
unsigned getDeducedDepth() const
The depth of template parameters for which deduction is being performed.
diag_iterator diag_begin() const
Returns an iterator at the beginning of the sequence of suppressed diagnostics.
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
__inline void unsigned int _2
The JSON file list parser is used to communicate input to InstallAPI.
@ OO_None
Not an overloaded operator.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
bool isTargetAddressSpace(LangAS AS)
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition Sema.h:799
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1788
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1794
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
NamedDecl * getAsNamedDecl(TemplateParameter P)
bool isPackProducingBuiltinTemplateName(TemplateName N)
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
unsigned toTargetAddressSpace(LangAS AS)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:587
@ Concept
The name was classified as a concept name.
Definition Sema.h:591
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
DeducedKind
Definition TypeBase.h:1798
@ Deduced
The normal deduced case.
Definition TypeBase.h:1805
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1800
@ DeducedAsPack
Same as above, but additionally this represents a case where the deduced entity itself is a pack.
Definition TypeBase.h:1821
@ DeducedAsDependent
This is a special case where the initializer is dependent, so we can't deduce a type yet.
Definition TypeBase.h:1815
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Concept_template
The name refers to a concept.
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
TPOC
The context in which partial ordering of function templates occurs.
Definition Template.h:304
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:310
@ TPOC_Other
Partial ordering of function templates in other contexts, e.g., taking the address of a function temp...
Definition Template.h:315
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:306
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:419
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:414
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:390
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:376
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:412
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:409
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:373
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:393
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:382
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:396
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:406
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:400
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:403
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5977
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
TemplateDeductionFlags
Various flags that control template argument deduction.
@ TDF_None
No template argument deduction flags, which indicates the strictest results for template argument ded...
@ TDF_DerivedClass
Within template argument deduction from a function call, we are matching in a case where we can perfo...
@ TDF_TopLevelParameterTypeList
Whether we are performing template argument deduction for parameters and arguments in a top-level tem...
@ TDF_IgnoreQualifiers
Within template argument deduction from a function call, we are matching in a case where we ignore cv...
@ TDF_ParamWithReferenceType
Within template argument deduction from a function call, we are matching with a parameter type for wh...
@ TDF_SkipNonDependent
Allow non-dependent types to differ, e.g., when performing template argument deduction from a functio...
@ TDF_AllowCompatibleFunctionType
Within template argument deduction from overload resolution per C++ [over.over] allow matching functi...
@ TDF_ArgWithReferenceType
Within template argument deduction for a conversion function, we are matching with an argument type f...
#define true
Definition stdbool.h:25
A pack that we're currently deducing.
SmallVector< DeducedTemplateArgument, 4 > New
DeducedTemplateArgument Saved
DeducedTemplateArgument DeferredDeduction
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5416
Extra information about a function prototype.
Definition TypeBase.h:5442
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5447
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12090
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12086
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12079
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12076
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12076
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13211
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13218
A stack object to be created when performing template instantiation.
Definition Sema.h:13384
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13537
brief A function argument from which we performed template argument
Definition Sema.h:12713
Location information for a TemplateArgument.