clang 24.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 // A pack-index-template-name is not deducible.
251 if (const auto *DTI = dyn_cast<DependentTemplateIdExpr>(E))
252 if (!DTI->getTemplateName().getAsPackIndexingTemplate() &&
253 DTI->getParameter()->getDepth() == Depth)
254 return DTI->getParameter();
255
256 return nullptr;
257}
258
263
264/// Determine whether two declaration pointers refer to the same
265/// declaration.
266static bool isSameDeclaration(Decl *X, Decl *Y) {
267 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
268 X = NX->getUnderlyingDecl();
269 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
270 Y = NY->getUnderlyingDecl();
271
272 return X->getCanonicalDecl() == Y->getCanonicalDecl();
273}
274
275/// Verify that the given, deduced template arguments are compatible.
276///
277/// \returns The deduced template argument, or a NULL template argument if
278/// the deduced template arguments were incompatible.
283 bool AggregateCandidateDeduction = false) {
284 // We have no deduction for one or both of the arguments; they're compatible.
285 if (X.isNull())
286 return Y;
287 if (Y.isNull())
288 return X;
289
290 // If we have two non-type template argument values deduced for the same
291 // parameter, they must both match the type of the parameter, and thus must
292 // match each other's type. As we're only keeping one of them, we must check
293 // for that now. The exception is that if either was deduced from an array
294 // bound, the type is permitted to differ.
295 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
296 QualType XType = X.getNonTypeTemplateArgumentType();
297 if (!XType.isNull()) {
299 if (YType.isNull() || !Context.hasSameType(XType, YType))
301 }
302 }
303
304 switch (X.getKind()) {
306 llvm_unreachable("Non-deduced template arguments handled above");
307
309 // If two template type arguments have the same type, they're compatible.
310 QualType TX = X.getAsType(), TY = Y.getAsType();
311 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
312 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
313 X.wasDeducedFromArrayBound() ||
315
316 // If one of the two arguments was deduced from an array bound, the other
317 // supersedes it.
318 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
319 return X.wasDeducedFromArrayBound() ? Y : X;
320
321 // The arguments are not compatible.
323 }
324
326 // If we deduced a constant in one case and either a dependent expression or
327 // declaration in another case, keep the integral constant.
328 // If both are integral constants with the same value, keep that value.
332 llvm::APSInt::isSameValue(X.getAsIntegral(), Y.getAsIntegral())))
333 return X.wasDeducedFromArrayBound() ? Y : X;
334
335 // All other combinations are incompatible.
337
339 // If we deduced a value and a dependent expression, keep the value.
342 X.structurallyEquals(Y)))
343 return X;
344
345 // All other combinations are incompatible.
347
350 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
351 return X;
352
353 // All other combinations are incompatible.
355
358 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
360 return X;
361
362 // All other combinations are incompatible.
364
367 return checkDeducedTemplateArguments(Context, Y, X);
368
369 // Compare the expressions for equality
370 llvm::FoldingSetNodeID ID1, ID2;
371 X.getAsExpr()->Profile(ID1, Context, true);
372 Y.getAsExpr()->Profile(ID2, Context, true);
373 if (ID1 == ID2)
374 return X.wasDeducedFromArrayBound() ? Y : X;
375
376 // Differing dependent expressions are incompatible.
378 }
379
381 assert(!X.wasDeducedFromArrayBound());
382
383 // If we deduced a declaration and a dependent expression, keep the
384 // declaration.
386 return X;
387
388 // If we deduced a declaration and an integral constant, keep the
389 // integral constant and whichever type did not come from an array
390 // bound.
393 return TemplateArgument(Context, Y.getAsIntegral(),
394 X.getParamTypeForDecl());
395 return Y;
396 }
397
398 // If we deduced two declarations, make sure that they refer to the
399 // same declaration.
401 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
402 return X;
403
404 // All other combinations are incompatible.
406
408 // If we deduced a null pointer and a dependent expression, keep the
409 // null pointer.
411 return TemplateArgument(Context.getCommonSugaredType(
412 X.getNullPtrType(), Y.getAsExpr()->getType()),
413 true);
414
415 // If we deduced a null pointer and an integral constant, keep the
416 // integral constant.
418 return Y;
419
420 // If we deduced two null pointers, they are the same.
422 return TemplateArgument(
423 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
424 true);
425
426 // All other combinations are incompatible.
428
430 if (Y.getKind() != TemplateArgument::Pack ||
431 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
433
436 XA = X.pack_begin(),
437 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
438 XA != XAEnd; ++XA) {
439 if (YA != YAEnd) {
441 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
443 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
445 NewPack.push_back(Merged);
446 ++YA;
447 } else {
448 NewPack.push_back(*XA);
449 }
450 }
451
453 TemplateArgument::CreatePackCopy(Context, NewPack),
454 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
455 }
456 }
457
458 llvm_unreachable("Invalid TemplateArgument Kind!");
459}
460
461/// Deduce the value of the given non-type template parameter
462/// as the given deduced template argument. All non-type template parameter
463/// deduction is funneled through here.
467 const DeducedTemplateArgument &NewDeduced,
468 QualType ValueType, TemplateDeductionInfo &Info,
469 bool PartialOrdering,
471 bool *HasDeducedAnyParam) {
472 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
473 "deducing non-type template argument with wrong depth");
474
476 S.Context, Deduced[NTTP.getIndex()], NewDeduced);
477 if (Result.isNull()) {
478 Info.Param = NTTP.asTemplateParam();
479 Info.FirstArg = Deduced[NTTP.getIndex()];
480 Info.SecondArg = NewDeduced;
482 }
483 Deduced[NTTP.getIndex()] = Result;
484 if (!S.getLangOpts().CPlusPlus17 && !PartialOrdering)
486
487 if (NTTP.isExpandedParameterPack())
488 // FIXME: We may still need to deduce parts of the type here! But we
489 // don't have any way to find which slice of the type to use, and the
490 // type stored on the NTTP itself is nonsense. Perhaps the type of an
491 // expanded NTTP should be a pack expansion type?
493
494 // Get the type of the parameter for deduction. If it's a (dependent) array
495 // or function type, we will not have decayed it yet, so do that now.
496 QualType ParamType = S.Context.getAdjustedParameterType(NTTP.getType());
497 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
498 ParamType = Expansion->getPattern();
499
500 // FIXME: It's not clear how deduction of a parameter of reference
501 // type from an argument (of non-reference type) should be performed.
502 // For now, we just make the argument have same reference type as the
503 // parameter.
504 if (ParamType->isReferenceType() && !ValueType->isReferenceType()) {
505 if (ParamType->isRValueReferenceType())
506 ValueType = S.Context.getRValueReferenceType(ValueType);
507 else
508 ValueType = S.Context.getLValueReferenceType(ValueType);
509 }
510
512 S, TemplateParams, ParamType, ValueType, Info, Deduced,
516 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
517}
518
519/// Deduce the value of the given non-type template parameter
520/// from the given integral constant.
522 Sema &S, TemplateParameterList *TemplateParams,
523 NonTypeOrVarTemplateParmDecl NTTP, const llvm::APSInt &Value,
524 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
526 bool *HasDeducedAnyParam) {
528 S, TemplateParams, NTTP,
530 DeducedFromArrayBound),
531 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
532}
533
534/// Deduce the value of the given non-type template parameter
535/// from the given null pointer template argument type.
539 QualType NullPtrType, TemplateDeductionInfo &Info,
540 bool PartialOrdering,
542 bool *HasDeducedAnyParam) {
545 NTTP.getLocation()),
546 NullPtrType,
547 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
548 : CK_NullToPointer)
549 .get();
551 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
552 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
553}
554
555/// Deduce the value of the given non-type template parameter
556/// from the given type- or value-dependent expression.
557///
558/// \returns true if deduction succeeded, false otherwise.
564 bool *HasDeducedAnyParam) {
566 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
567 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
568}
569
570/// Deduce the value of the given non-type template parameter
571/// from the given declaration.
572///
573/// \returns true if deduction succeeded, false otherwise.
578 bool PartialOrdering,
580 bool *HasDeducedAnyParam) {
583 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
584 PartialOrdering, Deduced, HasDeducedAnyParam);
585}
586
588 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
592 bool *HasDeducedAnyParam) {
593 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
594 if (!ParamDecl) {
595 // The parameter type is dependent and is not a template template parameter,
596 // so there is nothing that we can deduce.
598 }
599
600 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
601 // If we're not deducing at this depth, there's nothing to deduce.
602 if (TempParam->getDepth() != Info.getDeducedDepth())
604
605 ArrayRef<NamedDecl *> Params =
606 ParamDecl->getTemplateParameters()->asArray();
607 unsigned StartPos = 0;
608 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
609 I < E; ++I) {
610 if (Params[I]->isParameterPack()) {
611 StartPos = DefaultArguments.size();
612 break;
613 }
614 StartPos = I + 1;
615 }
616
617 // Provisional resolution for CWG2398: If Arg names a template
618 // specialization, then we deduce a synthesized template name
619 // based on A, but using the TS's extra arguments, relative to P, as
620 // defaults.
621 DeducedTemplateArgument NewDeduced =
624 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
625 : Arg;
626
628 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
629 if (Result.isNull()) {
630 Info.Param = TempParam;
631 Info.FirstArg = Deduced[TempParam->getIndex()];
632 Info.SecondArg = NewDeduced;
634 }
635
636 Deduced[TempParam->getIndex()] = Result;
637 if (HasDeducedAnyParam)
638 *HasDeducedAnyParam = true;
640 }
641
642 // Verify that the two template names are equivalent.
644 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
646
647 // Mismatch of non-dependent template parameter to argument.
648 Info.FirstArg = TemplateArgument(Param);
649 Info.SecondArg = TemplateArgument(Arg);
651}
652
653/// Deduce the template arguments by comparing the template parameter
654/// type (which is a template-id) with the template argument type.
655///
656/// \param S the Sema
657///
658/// \param TemplateParams the template parameters that we are deducing
659///
660/// \param P the parameter type
661///
662/// \param A the argument type
663///
664/// \param Info information about the template argument deduction itself
665///
666/// \param Deduced the deduced template arguments
667///
668/// \returns the result of template argument deduction so far. Note that a
669/// "success" result means that template argument deduction has not yet failed,
670/// but it may still fail, later, for other reasons.
671
672static const TemplateSpecializationType *getLastTemplateSpecType(QualType QT) {
673 const TemplateSpecializationType *LastTST = nullptr;
674 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
675 const TemplateSpecializationType *TST =
676 T->getAs<TemplateSpecializationType>();
677 if (!TST)
678 return LastTST;
679 if (!TST->isSugared())
680 return TST;
681 LastTST = TST;
682 T = TST->desugar().getTypePtr();
683 }
684}
685
688 const QualType P, QualType A,
691 bool *HasDeducedAnyParam) {
692 TemplateName TNP;
695 const TemplateSpecializationType *TP = ::getLastTemplateSpecType(P);
696 TNP = TP->getTemplateName();
697
698 // No deduction for specializations of dependent template names.
701
702 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
703 // arguments.
704 PResolved =
705 TP->castAsCanonical<TemplateSpecializationType>()->template_arguments();
706 } else {
707 const auto *TT = P->castAs<InjectedClassNameType>();
708 TNP = TT->getTemplateName(S.Context);
709 PResolved = TT->getTemplateArgs(S.Context);
710 }
711
712 // If the parameter is an alias template, there is nothing to deduce.
713 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
715 // Pack-producing templates can only be matched after substitution.
718
719 // Check whether the template argument is a dependent template-id.
721 const TemplateSpecializationType *SA = ::getLastTemplateSpecType(A);
722 TemplateName TNA = SA->getTemplateName();
723
724 // If the argument is an alias template, there is nothing to deduce.
725 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
727
728 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
729 // arguments.
731 SA->getCanonicalTypeInternal()
732 ->castAs<TemplateSpecializationType>()
733 ->template_arguments();
734
735 // Perform template argument deduction for the template name.
736 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
737 /*DefaultArguments=*/AResolved,
739 HasDeducedAnyParam);
741 return Result;
742
743 // Perform template argument deduction on each template
744 // argument. Ignore any missing/extra arguments, since they could be
745 // filled in by default arguments.
747 S, TemplateParams, PResolved, AResolved, Info, Deduced,
748 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
749 PackFold::ParameterToArgument, HasDeducedAnyParam);
750 }
751
752 // If the argument type is a class template specialization, we
753 // perform template argument deduction using its template
754 // arguments.
755 const auto *TA = A->getAs<TagType>();
756 TemplateName TNA;
757 if (TA) {
758 // FIXME: Can't use the template arguments from this TST, as they are not
759 // resolved.
760 if (const auto *TST = A->getAsNonAliasTemplateSpecializationType())
761 TNA = TST->getTemplateName();
762 else
763 TNA = TA->getTemplateName(S.Context);
764 }
765 if (TNA.isNull()) {
766 Info.FirstArg = TemplateArgument(P);
767 Info.SecondArg = TemplateArgument(A);
769 }
770
771 ArrayRef<TemplateArgument> AResolved = TA->getTemplateArgs(S.Context);
772 // Perform template argument deduction for the template name.
773 if (auto Result =
774 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
775 /*DefaultArguments=*/AResolved,
776 PartialOrdering, Deduced, HasDeducedAnyParam);
778 return Result;
779
780 // Perform template argument deduction for the template arguments.
782 S, TemplateParams, PResolved, AResolved, Info, Deduced,
783 /*NumberOfArgumentsMustMatch=*/true, PartialOrdering,
784 PackFold::ParameterToArgument, HasDeducedAnyParam);
785}
786
788 assert(T->isCanonicalUnqualified());
789
790 switch (T->getTypeClass()) {
791 case Type::TypeOfExpr:
792 case Type::TypeOf:
793 case Type::DependentName:
794 case Type::Decltype:
795 case Type::PackIndexing:
796 case Type::UnresolvedUsing:
797 case Type::TemplateTypeParm:
798 case Type::Auto:
799 return true;
800
801 case Type::ConstantArray:
802 case Type::IncompleteArray:
803 case Type::VariableArray:
804 case Type::DependentSizedArray:
806 cast<ArrayType>(T)->getElementType().getTypePtr());
807
808 default:
809 return false;
810 }
811}
812
813/// Determines whether the given type is an opaque type that
814/// might be more qualified when instantiated.
817 T->getCanonicalTypeInternal().getTypePtr());
818}
819
820/// Helper function to build a TemplateParameter when we don't
821/// know its type statically.
823 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
824 return TemplateParameter(TTP);
825 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
826 return TemplateParameter(NTTP);
827
829}
830
831/// A pack that we're currently deducing.
833 // The index of the pack.
834 unsigned Index;
835
836 // The old value of the pack before we started deducing it.
838
839 // A deferred value of this pack from an inner deduction, that couldn't be
840 // deduced because this deduction hadn't happened yet.
842
843 // The new value of the pack.
845
846 // The outer deduction for this pack, if any.
847 DeducedPack *Outer = nullptr;
848
849 DeducedPack(unsigned Index) : Index(Index) {}
850};
851
852namespace {
853
854/// A scope in which we're performing pack deduction.
855class PackDeductionScope {
856public:
857 /// Prepare to deduce the packs named within Pattern.
858 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
859 /// just checking a previous deduction of the pack.
860 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
863 bool DeducePackIfNotAlreadyDeduced = false,
864 bool FinishingDeduction = false)
865 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
866 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
867 FinishingDeduction(FinishingDeduction) {
868 unsigned NumNamedPacks = addPacks(Pattern);
869 finishConstruction(NumNamedPacks);
870 }
871
872 /// Prepare to directly deduce arguments of the parameter with index \p Index.
873 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
874 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
875 TemplateDeductionInfo &Info, unsigned Index)
876 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
877 addPack(Index);
878 finishConstruction(1);
879 }
880
881private:
882 void addPack(unsigned Index) {
883 // Save the deduced template argument for the parameter pack expanded
884 // by this pack expansion, then clear out the deduction.
885 DeducedFromEarlierParameter = !Deduced[Index].isNull();
886 DeducedPack Pack(Index);
887 if (!FinishingDeduction) {
888 Pack.Saved = Deduced[Index];
889 Deduced[Index] = TemplateArgument();
890 }
891
892 // FIXME: What if we encounter multiple packs with different numbers of
893 // pre-expanded expansions? (This should already have been diagnosed
894 // during substitution.)
895 if (UnsignedOrNone ExpandedPackExpansions =
896 getExpandedPackSize(TemplateParams->getParam(Index)))
897 FixedNumExpansions = ExpandedPackExpansions;
898
899 Packs.push_back(Pack);
900 }
901
902 unsigned addPacks(TemplateArgument Pattern) {
903 // Compute the set of template parameter indices that correspond to
904 // parameter packs expanded by the pack expansion.
905 llvm::SmallBitVector SawIndices(TemplateParams->size());
906 llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
907
908 auto AddPack = [&](unsigned Index) {
909 if (SawIndices[Index])
910 return;
911 SawIndices[Index] = true;
912 addPack(Index);
913
914 // Deducing a parameter pack that is a pack expansion also constrains the
915 // packs appearing in that parameter to have the same deduced arity. Also,
916 // in C++17 onwards, deducing a non-type template parameter deduces its
917 // type, so we need to collect the pending deduced values for those packs.
918 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
919 TemplateParams->getParam(Index))) {
920 if (!NTTP->isExpandedParameterPack())
921 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
922 // context, however it is not yet resolved.
923 if (auto *Expansion = dyn_cast<PackExpansionType>(
924 S.Context.getUnconstrainedType(NTTP->getType())))
925 ExtraDeductions.push_back(Expansion->getPattern());
926 }
927 // FIXME: Also collect the unexpanded packs in any type and template
928 // parameter packs that are pack expansions.
929 };
930
931 auto Collect = [&](TemplateArgument Pattern) {
932 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
933 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
934 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
935 unsigned Depth, Index;
936
937 // Function parameter packs cannot be deduced.
938 if (isa_and_present<ParmVarDecl>(
939 dyn_cast<NamedDecl *>(Unexpanded[I].first)))
940 continue;
941 if (auto DI = getDepthAndIndex(Unexpanded[I]))
942 std::tie(Depth, Index) = *DI;
943 else
944 continue;
945
946 if (Depth == Info.getDeducedDepth())
947 AddPack(Index);
948 }
949 };
950
951 // Look for unexpanded packs in the pattern.
952 Collect(Pattern);
953
954 unsigned NumNamedPacks = Packs.size();
955
956 // Also look for unexpanded packs that are indirectly deduced by deducing
957 // the sizes of the packs in this pattern.
958 while (!ExtraDeductions.empty())
959 Collect(ExtraDeductions.pop_back_val());
960
961 return NumNamedPacks;
962 }
963
964 void finishConstruction(unsigned NumNamedPacks) {
965 // Dig out the partially-substituted pack, if there is one.
966 const TemplateArgument *PartialPackArgs = nullptr;
967 unsigned NumPartialPackArgs = 0;
968 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
969 if (auto *Scope = S.CurrentInstantiationScope)
970 if (auto *Partial = Scope->getPartiallySubstitutedPack(
971 &PartialPackArgs, &NumPartialPackArgs))
972 PartialPackDepthIndex = getDepthAndIndex(Partial);
973
974 // This pack expansion will have been partially or fully expanded if
975 // it only names explicitly-specified parameter packs (including the
976 // partially-substituted one, if any).
977 bool IsExpanded = true;
978 for (unsigned I = 0; I != NumNamedPacks; ++I) {
979 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
980 IsExpanded = false;
981 IsPartiallyExpanded = false;
982 break;
983 }
984 if (PartialPackDepthIndex ==
985 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
986 IsPartiallyExpanded = true;
987 }
988 }
989
990 // Skip over the pack elements that were expanded into separate arguments.
991 // If we partially expanded, this is the number of partial arguments.
992 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
993 // https://github.com/llvm/llvm-project/issues/100095
994 if (IsPartiallyExpanded)
995 PackElements += NumPartialPackArgs;
996 else if (IsExpanded && FixedNumExpansions)
997 PackElements += *FixedNumExpansions;
998
999 for (auto &Pack : Packs) {
1000 if (Info.PendingDeducedPacks.size() > Pack.Index)
1001 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
1002 else
1003 Info.PendingDeducedPacks.resize(Pack.Index + 1);
1004 Info.PendingDeducedPacks[Pack.Index] = &Pack;
1005
1006 if (PartialPackDepthIndex ==
1007 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
1008 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
1009 }
1010 }
1011 }
1012
1013public:
1014 ~PackDeductionScope() {
1015 for (auto &Pack : Packs)
1016 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
1017 }
1018
1019 // Return the size of the saved packs if all of them has the same size.
1020 UnsignedOrNone getSavedPackSizeIfAllEqual() const {
1021 unsigned PackSize = Packs[0].Saved.pack_size();
1022
1023 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
1024 return P.Saved.pack_size() == PackSize;
1025 }))
1026 return PackSize;
1027 return std::nullopt;
1028 }
1029
1030 /// Determine whether this pack has already been deduced from a previous
1031 /// argument.
1032 bool isDeducedFromEarlierParameter() const {
1033 return DeducedFromEarlierParameter;
1034 }
1035
1036 /// Determine whether this pack has already been partially expanded into a
1037 /// sequence of (prior) function parameters / template arguments.
1038 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
1039
1040 /// Determine whether this pack expansion scope has a known, fixed arity.
1041 /// This happens if it involves a pack from an outer template that has
1042 /// (notionally) already been expanded.
1043 bool hasFixedArity() { return static_cast<bool>(FixedNumExpansions); }
1044
1045 /// Determine whether the next element of the argument is still part of this
1046 /// pack. This is the case unless the pack is already expanded to a fixed
1047 /// length.
1048 bool hasNextElement() {
1049 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1050 }
1051
1052 /// Move to deducing the next element in each pack that is being deduced.
1053 void nextPackElement() {
1054 // Capture the deduced template arguments for each parameter pack expanded
1055 // by this pack expansion, add them to the list of arguments we've deduced
1056 // for that pack, then clear out the deduced argument.
1057 if (!FinishingDeduction) {
1058 for (auto &Pack : Packs) {
1059 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1060 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1061 while (Pack.New.size() < PackElements)
1062 Pack.New.push_back(DeducedTemplateArgument());
1063 if (Pack.New.size() == PackElements)
1064 Pack.New.push_back(DeducedArg);
1065 else
1066 Pack.New[PackElements] = DeducedArg;
1067 DeducedArg = Pack.New.size() > PackElements + 1
1068 ? Pack.New[PackElements + 1]
1069 : DeducedTemplateArgument();
1070 }
1071 }
1072 }
1073 ++PackElements;
1074 }
1075
1076 /// Finish template argument deduction for a set of argument packs,
1077 /// producing the argument packs and checking for consistency with prior
1078 /// deductions.
1079 TemplateDeductionResult finish() {
1080 if (FinishingDeduction)
1081 return TemplateDeductionResult::Success;
1082 // Build argument packs for each of the parameter packs expanded by this
1083 // pack expansion.
1084 for (auto &Pack : Packs) {
1085 // Put back the old value for this pack.
1086 if (!FinishingDeduction)
1087 Deduced[Pack.Index] = Pack.Saved;
1088
1089 // Always make sure the size of this pack is correct, even if we didn't
1090 // deduce any values for it.
1091 //
1092 // FIXME: This isn't required by the normative wording, but substitution
1093 // and post-substitution checking will always fail if the arity of any
1094 // pack is not equal to the number of elements we processed. (Either that
1095 // or something else has gone *very* wrong.) We're permitted to skip any
1096 // hard errors from those follow-on steps by the intent (but not the
1097 // wording) of C++ [temp.inst]p8:
1098 //
1099 // If the function selected by overload resolution can be determined
1100 // without instantiating a class template definition, it is unspecified
1101 // whether that instantiation actually takes place
1102 Pack.New.resize(PackElements);
1103
1104 // Build or find a new value for this pack.
1105 DeducedTemplateArgument NewPack;
1106 if (Pack.New.empty()) {
1107 // If we deduced an empty argument pack, create it now.
1108 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
1109 } else {
1110 TemplateArgument *ArgumentPack =
1111 new (S.Context) TemplateArgument[Pack.New.size()];
1112 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1113 NewPack = DeducedTemplateArgument(
1114 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1115 // FIXME: This is wrong, it's possible that some pack elements are
1116 // deduced from an array bound and others are not:
1117 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1118 // g({1, 2, 3}, {{}, {}});
1119 // ... should deduce T = {int, size_t (from array bound)}.
1120 Pack.New[0].wasDeducedFromArrayBound());
1121 }
1122
1123 // Pick where we're going to put the merged pack.
1124 DeducedTemplateArgument *Loc;
1125 if (Pack.Outer) {
1126 if (Pack.Outer->DeferredDeduction.isNull()) {
1127 // Defer checking this pack until we have a complete pack to compare
1128 // it against.
1129 Pack.Outer->DeferredDeduction = NewPack;
1130 continue;
1131 }
1132 Loc = &Pack.Outer->DeferredDeduction;
1133 } else {
1134 Loc = &Deduced[Pack.Index];
1135 }
1136
1137 // Check the new pack matches any previous value.
1138 DeducedTemplateArgument OldPack = *Loc;
1139 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
1140 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1141
1142 Info.AggregateDeductionCandidateHasMismatchedArity =
1143 OldPack.getKind() == TemplateArgument::Pack &&
1144 NewPack.getKind() == TemplateArgument::Pack &&
1145 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1146
1147 // If we deferred a deduction of this pack, check that one now too.
1148 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1149 OldPack = Result;
1150 NewPack = Pack.DeferredDeduction;
1151 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1152 }
1153
1154 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1155 if (Result.isNull()) {
1156 Info.Param = makeTemplateParameter(Param);
1157 Info.FirstArg = OldPack;
1158 Info.SecondArg = NewPack;
1159 return TemplateDeductionResult::Inconsistent;
1160 }
1161
1162 // If we have a pre-expanded pack and we didn't deduce enough elements
1163 // for it, fail deduction.
1164 if (UnsignedOrNone Expansions = getExpandedPackSize(Param)) {
1165 if (*Expansions != PackElements) {
1166 Info.Param = makeTemplateParameter(Param);
1167 Info.FirstArg = Result;
1168 return TemplateDeductionResult::IncompletePack;
1169 }
1170 }
1171
1172 *Loc = Result;
1173 }
1174
1175 return TemplateDeductionResult::Success;
1176 }
1177
1178private:
1179 Sema &S;
1180 TemplateParameterList *TemplateParams;
1181 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
1182 TemplateDeductionInfo &Info;
1183 unsigned PackElements = 0;
1184 bool IsPartiallyExpanded = false;
1185 bool DeducePackIfNotAlreadyDeduced = false;
1186 bool DeducedFromEarlierParameter = false;
1187 bool FinishingDeduction = false;
1188 /// The number of expansions, if we have a fully-expanded pack in this scope.
1189 UnsignedOrNone FixedNumExpansions = std::nullopt;
1190
1191 SmallVector<DeducedPack, 2> Packs;
1192};
1193
1194} // namespace
1195
1196template <class T>
1198 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1201 bool FinishingDeduction, T &&DeductFunc) {
1202 // C++0x [temp.deduct.type]p10:
1203 // Similarly, if P has a form that contains (T), then each parameter type
1204 // Pi of the respective parameter-type- list of P is compared with the
1205 // corresponding parameter type Ai of the corresponding parameter-type-list
1206 // of A. [...]
1207 unsigned ArgIdx = 0, ParamIdx = 0;
1208 for (; ParamIdx != Params.size(); ++ParamIdx) {
1209 // Check argument types.
1210 const PackExpansionType *Expansion
1211 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1212 if (!Expansion) {
1213 // Simple case: compare the parameter and argument types at this point.
1214
1215 // Make sure we have an argument.
1216 if (ArgIdx >= Args.size())
1218
1219 if (isa<PackExpansionType>(Args[ArgIdx])) {
1220 // C++0x [temp.deduct.type]p22:
1221 // If the original function parameter associated with A is a function
1222 // parameter pack and the function parameter associated with P is not
1223 // a function parameter pack, then template argument deduction fails.
1225 }
1226
1228 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1229 Params[ParamIdx].getUnqualifiedType(),
1230 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1232 return Result;
1233
1234 ++ArgIdx;
1235 continue;
1236 }
1237
1238 // C++0x [temp.deduct.type]p10:
1239 // If the parameter-declaration corresponding to Pi is a function
1240 // parameter pack, then the type of its declarator- id is compared with
1241 // each remaining parameter type in the parameter-type-list of A. Each
1242 // comparison deduces template arguments for subsequent positions in the
1243 // template parameter packs expanded by the function parameter pack.
1244
1245 QualType Pattern = Expansion->getPattern();
1246 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1247 /*DeducePackIfNotAlreadyDeduced=*/false,
1248 FinishingDeduction);
1249
1250 // A pack scope with fixed arity is not really a pack any more, so is not
1251 // a non-deduced context.
1252 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1253 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1254 // Deduce template arguments from the pattern.
1255 if (TemplateDeductionResult Result = DeductFunc(
1256 S, TemplateParams, ParamIdx, ArgIdx,
1257 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1258 Info, Deduced, POK);
1260 return Result;
1261 PackScope.nextPackElement();
1262 }
1263 } else {
1264 // C++0x [temp.deduct.type]p5:
1265 // The non-deduced contexts are:
1266 // - A function parameter pack that does not occur at the end of the
1267 // parameter-declaration-clause.
1268 //
1269 // FIXME: There is no wording to say what we should do in this case. We
1270 // choose to resolve this by applying the same rule that is applied for a
1271 // function call: that is, deduce all contained packs to their
1272 // explicitly-specified values (or to <> if there is no such value).
1273 //
1274 // This is seemingly-arbitrarily different from the case of a template-id
1275 // with a non-trailing pack-expansion in its arguments, which renders the
1276 // entire template-argument-list a non-deduced context.
1277
1278 // If the parameter type contains an explicitly-specified pack that we
1279 // could not expand, skip the number of parameters notionally created
1280 // by the expansion.
1281 UnsignedOrNone NumExpansions = Expansion->getNumExpansions();
1282 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1283 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1284 ++I, ++ArgIdx)
1285 PackScope.nextPackElement();
1286 }
1287 }
1288
1289 // Build argument packs for each of the parameter packs expanded by this
1290 // pack expansion.
1291 if (auto Result = PackScope.finish();
1293 return Result;
1294 }
1295
1296 // DR692, DR1395
1297 // C++0x [temp.deduct.type]p10:
1298 // If the parameter-declaration corresponding to P_i ...
1299 // During partial ordering, if Ai was originally a function parameter pack:
1300 // - if P does not contain a function parameter type corresponding to Ai then
1301 // Ai is ignored;
1302 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1303 isa<PackExpansionType>(Args[ArgIdx]))
1305
1306 // Make sure we don't have any extra arguments.
1307 if (ArgIdx < Args.size())
1309
1311}
1312
1313/// Deduce the template arguments by comparing the list of parameter
1314/// types to the list of argument types, as in the parameter-type-lists of
1315/// function types (C++ [temp.deduct.type]p10).
1316///
1317/// \param S The semantic analysis object within which we are deducing
1318///
1319/// \param TemplateParams The template parameters that we are deducing
1320///
1321/// \param Params The list of parameter types
1322///
1323/// \param Args The list of argument types
1324///
1325/// \param Info information about the template argument deduction itself
1326///
1327/// \param Deduced the deduced template arguments
1328///
1329/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1330/// how template argument deduction is performed.
1331///
1332/// \param PartialOrdering If true, we are performing template argument
1333/// deduction for during partial ordering for a call
1334/// (C++0x [temp.deduct.partial]).
1335///
1336/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1337/// whether any template parameter was deduced.
1338///
1339/// \param HasDeducedParam If set, the bit vector will be used to represent
1340/// which template parameters were deduced, in order.
1341///
1342/// \returns the result of template argument deduction so far. Note that a
1343/// "success" result means that template argument deduction has not yet failed,
1344/// but it may still fail, later, for other reasons.
1346 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1349 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1350 llvm::SmallBitVector *HasDeducedParam) {
1351 return ::DeduceForEachType(
1352 S, TemplateParams, Params, Args, Info, Deduced, POK,
1353 /*FinishingDeduction=*/false,
1354 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1355 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1357 PartialOrderingKind POK) {
1358 bool HasDeducedAnyParamCopy = false;
1360 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1361 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1362 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1363 *HasDeducedAnyParam = true;
1364 if (HasDeducedParam && HasDeducedAnyParamCopy)
1365 (*HasDeducedParam)[ParamIdx] = true;
1366 return TDR;
1367 });
1368}
1369
1370/// Determine whether the parameter has qualifiers that the argument
1371/// lacks. Put another way, determine whether there is no way to add
1372/// a deduced set of qualifiers to the ParamType that would result in
1373/// its qualifiers matching those of the ArgType.
1375 QualType ArgType) {
1376 Qualifiers ParamQs = ParamType.getQualifiers();
1377 Qualifiers ArgQs = ArgType.getQualifiers();
1378
1379 if (ParamQs == ArgQs)
1380 return false;
1381
1382 // Mismatched (but not missing) Objective-C GC attributes.
1383 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1384 ParamQs.hasObjCGCAttr())
1385 return true;
1386
1387 // Mismatched (but not missing) address spaces.
1388 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1389 ParamQs.hasAddressSpace())
1390 return true;
1391
1392 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1393 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1394 ParamQs.hasObjCLifetime())
1395 return true;
1396
1397 // CVR qualifiers inconsistent or a superset.
1398 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1399}
1400
1402 const FunctionType *PF = P->getAs<FunctionType>(),
1403 *AF = A->getAs<FunctionType>();
1404
1405 // Just compare if not functions.
1406 if (!PF || !AF)
1407 return Context.hasSameType(P, A);
1408
1409 // Noreturn and noexcept adjustment.
1410 if (QualType AdjustedParam; TryFunctionConversion(P, A, AdjustedParam))
1411 P = AdjustedParam;
1412
1413 // FIXME: Compatible calling conventions.
1414 return Context.hasSameFunctionTypeIgnoringExceptionSpec(P, A);
1415}
1416
1417/// Get the index of the first template parameter that was originally from the
1418/// innermost template-parameter-list. This is 0 except when we concatenate
1419/// the template parameter lists of a class template and a constructor template
1420/// when forming an implicit deduction guide.
1422 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1423 if (!Guide || !Guide->isImplicit())
1424 return 0;
1425 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1426}
1427
1428/// Determine whether a type denotes a forwarding reference.
1429static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1430 // C++1z [temp.deduct.call]p3:
1431 // A forwarding reference is an rvalue reference to a cv-unqualified
1432 // template parameter that does not represent a template parameter of a
1433 // class template.
1434 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1435 if (ParamRef->getPointeeType().getQualifiers())
1436 return false;
1437 auto *TypeParm =
1438 ParamRef->getPointeeType()->getAsCanonical<TemplateTypeParmType>();
1439 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1440 }
1441 return false;
1442}
1443
1444/// Attempt to deduce the template arguments by checking the base types
1445/// according to (C++20 [temp.deduct.call] p4b3.
1446///
1447/// \param S the semantic analysis object within which we are deducing.
1448///
1449/// \param RD the top level record object we are deducing against.
1450///
1451/// \param TemplateParams the template parameters that we are deducing.
1452///
1453/// \param P the template specialization parameter type.
1454///
1455/// \param Info information about the template argument deduction itself.
1456///
1457/// \param Deduced the deduced template arguments.
1458///
1459/// \returns the result of template argument deduction with the bases. "invalid"
1460/// means no matches, "success" found a single item, and the
1461/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1464 TemplateParameterList *TemplateParams, QualType P,
1467 bool *HasDeducedAnyParam) {
1468 // C++14 [temp.deduct.call] p4b3:
1469 // If P is a class and P has the form simple-template-id, then the
1470 // transformed A can be a derived class of the deduced A. Likewise if
1471 // P is a pointer to a class of the form simple-template-id, the
1472 // transformed A can be a pointer to a derived class pointed to by the
1473 // deduced A. However, if there is a class C that is a (direct or
1474 // indirect) base class of D and derived (directly or indirectly) from a
1475 // class B and that would be a valid deduced A, the deduced A cannot be
1476 // B or pointer to B, respectively.
1477 //
1478 // These alternatives are considered only if type deduction would
1479 // otherwise fail. If they yield more than one possible deduced A, the
1480 // type deduction fails.
1481
1482 // Use a breadth-first search through the bases to collect the set of
1483 // successful matches. Visited contains the set of nodes we have already
1484 // visited, while ToVisit is our stack of records that we still need to
1485 // visit. Matches contains a list of matches that have yet to be
1486 // disqualified.
1489 // We iterate over this later, so we have to use MapVector to ensure
1490 // determinism.
1491 struct MatchValue {
1493 bool HasDeducedAnyParam;
1494 };
1495 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1496
1497 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1498 for (const auto &Base : RD->bases()) {
1499 QualType T = Base.getType();
1500 assert(T->isRecordType() && "Base class that isn't a record?");
1501 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1502 ToVisit.push_back(T);
1503 }
1504 };
1505
1506 // Set up the loop by adding all the bases.
1507 AddBases(RD);
1508
1509 // Search each path of bases until we either run into a successful match
1510 // (where all bases of it are invalid), or we run out of bases.
1511 while (!ToVisit.empty()) {
1512 QualType NextT = ToVisit.pop_back_val();
1513
1515 Deduced.end());
1517 bool HasDeducedAnyParamCopy = false;
1519 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1520 &HasDeducedAnyParamCopy);
1521
1522 // If this was a successful deduction, add it to the list of matches,
1523 // otherwise we need to continue searching its bases.
1524 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1526 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1527 else
1528 AddBases(RD);
1529 }
1530
1531 // At this point, 'Matches' contains a list of seemingly valid bases, however
1532 // in the event that we have more than 1 match, it is possible that the base
1533 // of one of the matches might be disqualified for being a base of another
1534 // valid match. We can count on cyclical instantiations being invalid to
1535 // simplify the disqualifications. That is, if A & B are both matches, and B
1536 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1537 if (Matches.size() > 1) {
1538 Visited.clear();
1539 for (const auto &Match : Matches)
1540 AddBases(Match.first);
1541
1542 // We can give up once we have a single item (or have run out of things to
1543 // search) since cyclical inheritance isn't valid.
1544 while (Matches.size() > 1 && !ToVisit.empty()) {
1545 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1546 Matches.erase(RD);
1547
1548 // Always add all bases, since the inheritance tree can contain
1549 // disqualifications for multiple matches.
1550 AddBases(RD);
1551 }
1552 }
1553
1554 if (Matches.empty())
1556 if (Matches.size() > 1)
1558
1559 std::swap(Matches.front().second.Deduced, Deduced);
1560 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1561 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1562 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1564}
1565
1566/// When propagating a partial ordering kind into a NonCall context,
1567/// this is used to downgrade a 'Call' into a 'NonCall', so that
1568/// the kind still reflects whether we are in a partial ordering context.
1573
1574/// Deduce the template arguments by comparing the parameter type and
1575/// the argument type (C++ [temp.deduct.type]).
1576///
1577/// \param S the semantic analysis object within which we are deducing
1578///
1579/// \param TemplateParams the template parameters that we are deducing
1580///
1581/// \param P the parameter type
1582///
1583/// \param A the argument type
1584///
1585/// \param Info information about the template argument deduction itself
1586///
1587/// \param Deduced the deduced template arguments
1588///
1589/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1590/// how template argument deduction is performed.
1591///
1592/// \param PartialOrdering Whether we're performing template argument deduction
1593/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1594///
1595/// \returns the result of template argument deduction so far. Note that a
1596/// "success" result means that template argument deduction has not yet failed,
1597/// but it may still fail, later, for other reasons.
1599 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1602 PartialOrderingKind POK, bool DeducedFromArrayBound,
1603 bool *HasDeducedAnyParam) {
1604
1605 // If the argument type is a pack expansion, look at its pattern.
1606 // This isn't explicitly called out
1607 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1608 A = AExp->getPattern();
1610
1611 if (POK == PartialOrderingKind::Call) {
1612 // C++11 [temp.deduct.partial]p5:
1613 // Before the partial ordering is done, certain transformations are
1614 // performed on the types used for partial ordering:
1615 // - If P is a reference type, P is replaced by the type referred to.
1616 const ReferenceType *PRef = P->getAs<ReferenceType>();
1617 if (PRef)
1618 P = PRef->getPointeeType();
1619
1620 // - If A is a reference type, A is replaced by the type referred to.
1621 const ReferenceType *ARef = A->getAs<ReferenceType>();
1622 if (ARef)
1623 A = A->getPointeeType();
1624
1625 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1626 // C++11 [temp.deduct.partial]p9:
1627 // If, for a given type, deduction succeeds in both directions (i.e.,
1628 // the types are identical after the transformations above) and both
1629 // P and A were reference types [...]:
1630 // - if [one type] was an lvalue reference and [the other type] was
1631 // not, [the other type] is not considered to be at least as
1632 // specialized as [the first type]
1633 // - if [one type] is more cv-qualified than [the other type],
1634 // [the other type] is not considered to be at least as specialized
1635 // as [the first type]
1636 // Objective-C ARC adds:
1637 // - [one type] has non-trivial lifetime, [the other type] has
1638 // __unsafe_unretained lifetime, and the types are otherwise
1639 // identical
1640 //
1641 // A is "considered to be at least as specialized" as P iff deduction
1642 // succeeds, so we model this as a deduction failure. Note that
1643 // [the first type] is P and [the other type] is A here; the standard
1644 // gets this backwards.
1645 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1646 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1647 PQuals.isStrictSupersetOf(AQuals) ||
1648 (PQuals.hasNonTrivialObjCLifetime() &&
1649 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1650 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1651 Info.FirstArg = TemplateArgument(P);
1652 Info.SecondArg = TemplateArgument(A);
1654 }
1655 }
1656 Qualifiers DiscardedQuals;
1657 // C++11 [temp.deduct.partial]p7:
1658 // Remove any top-level cv-qualifiers:
1659 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1660 // version of P.
1661 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1662 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1663 // version of A.
1664 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1665 } else {
1666 // C++0x [temp.deduct.call]p4 bullet 1:
1667 // - If the original P is a reference type, the deduced A (i.e., the type
1668 // referred to by the reference) can be more cv-qualified than the
1669 // transformed A.
1670 if (TDF & TDF_ParamWithReferenceType) {
1671 Qualifiers Quals;
1672 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1674 P = S.Context.getQualifiedType(UnqualP, Quals);
1675 }
1676
1677 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1678 // C++0x [temp.deduct.type]p10:
1679 // If P and A are function types that originated from deduction when
1680 // taking the address of a function template (14.8.2.2) or when deducing
1681 // template arguments from a function declaration (14.8.2.6) and Pi and
1682 // Ai are parameters of the top-level parameter-type-list of P and A,
1683 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1684 // is an lvalue reference, in
1685 // which case the type of Pi is changed to be the template parameter
1686 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1687 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1688 // deduced as X&. - end note ]
1690 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1692 P = P->getPointeeType();
1693 }
1694 }
1695
1696 // C++ [temp.deduct.type]p9:
1697 // A template type argument T, a template template argument TT or a
1698 // template non-type argument i can be deduced if P and A have one of
1699 // the following forms:
1700 //
1701 // T
1702 // cv-list T
1703 if (const auto *TTP = P->getAsCanonical<TemplateTypeParmType>()) {
1704 // Just skip any attempts to deduce from a placeholder type or a parameter
1705 // at a different depth.
1706 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1708
1709 unsigned Index = TTP->getIndex();
1710
1711 // If the argument type is an array type, move the qualifiers up to the
1712 // top level, so they can be matched with the qualifiers on the parameter.
1713 if (A->isArrayType()) {
1714 Qualifiers Quals;
1715 A = S.Context.getUnqualifiedArrayType(A, Quals);
1716 if (Quals)
1717 A = S.Context.getQualifiedType(A, Quals);
1718 }
1719
1720 // The argument type can not be less qualified than the parameter
1721 // type.
1722 if (!(TDF & TDF_IgnoreQualifiers) &&
1724 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1725 Info.FirstArg = TemplateArgument(P);
1726 Info.SecondArg = TemplateArgument(A);
1728 }
1729
1730 // Do not match a function type with a cv-qualified type.
1731 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1732 if (A->isFunctionType() && P.hasQualifiers())
1734
1735 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1736 "saw template type parameter with wrong depth");
1737 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1738 "Unresolved overloaded function");
1739 QualType DeducedType = A;
1740
1741 // Remove any qualifiers on the parameter from the deduced type.
1742 // We checked the qualifiers for consistency above.
1743 Qualifiers DeducedQs = DeducedType.getQualifiers();
1744 Qualifiers ParamQs = P.getQualifiers();
1745 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1746 if (ParamQs.hasObjCGCAttr())
1747 DeducedQs.removeObjCGCAttr();
1748 if (ParamQs.hasAddressSpace())
1749 DeducedQs.removeAddressSpace();
1750 if (ParamQs.hasObjCLifetime())
1751 DeducedQs.removeObjCLifetime();
1752
1753 // Objective-C ARC:
1754 // If template deduction would produce a lifetime qualifier on a type
1755 // that is not a lifetime type, template argument deduction fails.
1756 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1757 !DeducedType->isDependentType()) {
1758 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1759 Info.FirstArg = TemplateArgument(P);
1760 Info.SecondArg = TemplateArgument(A);
1762 }
1763
1764 // Objective-C ARC:
1765 // If template deduction would produce an argument type with lifetime type
1766 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1767 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1768 !DeducedQs.hasObjCLifetime())
1770
1771 DeducedType =
1772 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1773
1774 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1776 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1777 if (Result.isNull()) {
1778 // We can also get inconsistencies when matching NTTP type.
1779 switch (NamedDecl *Param = TemplateParams->getParam(Index);
1780 Param->getKind()) {
1781 case Decl::TemplateTypeParm:
1782 Info.Param = cast<TemplateTypeParmDecl>(Param);
1783 break;
1784 case Decl::NonTypeTemplateParm:
1786 break;
1787 case Decl::TemplateTemplateParm:
1789 break;
1790 default:
1791 llvm_unreachable("unexpected kind");
1792 }
1793 Info.FirstArg = Deduced[Index];
1794 Info.SecondArg = NewDeduced;
1796 }
1797
1798 Deduced[Index] = Result;
1799 if (HasDeducedAnyParam)
1800 *HasDeducedAnyParam = true;
1802 }
1803
1804 // Set up the template argument deduction information for a failure.
1805 Info.FirstArg = TemplateArgument(P);
1806 Info.SecondArg = TemplateArgument(A);
1807
1808 // If the parameter is an already-substituted template parameter
1809 // pack, do nothing: we don't know which of its arguments to look
1810 // at, so we have to wait until all of the parameter packs in this
1811 // expansion have arguments.
1812 if (P->getAs<SubstTemplateTypeParmPackType>())
1814
1815 // Check the cv-qualifiers on the parameter and argument types.
1816 if (!(TDF & TDF_IgnoreQualifiers)) {
1817 if (TDF & TDF_ParamWithReferenceType) {
1820 } else if (TDF & TDF_ArgWithReferenceType) {
1821 // C++ [temp.deduct.conv]p4:
1822 // If the original A is a reference type, A can be more cv-qualified
1823 // than the deduced A
1825 S.getASTContext()))
1827
1828 // Strip out all extra qualifiers from the argument to figure out the
1829 // type we're converting to, prior to the qualification conversion.
1830 Qualifiers Quals;
1831 A = S.Context.getUnqualifiedArrayType(A, Quals);
1833 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1834 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1836 }
1837 }
1838
1839 // If the parameter type is not dependent, there is nothing to deduce.
1840 if (!P->isDependentType()) {
1841 if (TDF & TDF_SkipNonDependent)
1844 : S.Context.hasSameType(P, A))
1849 if (!(TDF & TDF_IgnoreQualifiers))
1851 // Otherwise, when ignoring qualifiers, the types not having the same
1852 // unqualified type does not mean they do not match, so in this case we
1853 // must keep going and analyze with a non-dependent parameter type.
1854 }
1855
1856 switch (P.getCanonicalType()->getTypeClass()) {
1857 // Non-canonical types cannot appear here.
1858#define NON_CANONICAL_TYPE(Class, Base) \
1859 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1860#define TYPE(Class, Base)
1861#include "clang/AST/TypeNodes.inc"
1862
1863 case Type::TemplateTypeParm:
1864 case Type::SubstTemplateTypeParmPack:
1865 case Type::SubstBuiltinTemplatePack:
1866 llvm_unreachable("Type nodes handled above");
1867
1868 case Type::Auto:
1869 // C++23 [temp.deduct.funcaddr]/3:
1870 // A placeholder type in the return type of a function template is a
1871 // non-deduced context.
1872 // There's no corresponding wording for [temp.deduct.decl], but we treat
1873 // it the same to match other compilers.
1874 if (P->isDependentType())
1876 [[fallthrough]];
1877 case Type::Builtin:
1878 case Type::VariableArray:
1879 case Type::Vector:
1880 case Type::FunctionNoProto:
1881 case Type::Record:
1882 case Type::Enum:
1883 case Type::ObjCObject:
1884 case Type::ObjCInterface:
1885 case Type::ObjCObjectPointer:
1886 case Type::BitInt:
1887 return (TDF & TDF_SkipNonDependent) ||
1888 ((TDF & TDF_IgnoreQualifiers)
1890 : S.Context.hasSameType(P, A))
1893
1894 // _Complex T [placeholder extension]
1895 case Type::Complex: {
1896 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1897 if (!CA)
1900 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1902 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1903 }
1904
1905 // _Atomic T [extension]
1906 case Type::Atomic: {
1907 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1908 if (!AA)
1911 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1913 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1914 }
1915
1916 // T *
1917 case Type::Pointer: {
1918 QualType PointeeType;
1919 if (const auto *PA = A->getAs<PointerType>()) {
1920 PointeeType = PA->getPointeeType();
1921 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1922 PointeeType = PA->getPointeeType();
1923 } else {
1925 }
1927 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1928 PointeeType, Info, Deduced,
1931 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1932 }
1933
1934 // T &
1935 case Type::LValueReference: {
1936 const auto *RP = P->castAs<LValueReferenceType>(),
1937 *RA = A->getAs<LValueReferenceType>();
1938 if (!RA)
1940
1942 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1944 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1945 }
1946
1947 // T && [C++0x]
1948 case Type::RValueReference: {
1949 const auto *RP = P->castAs<RValueReferenceType>(),
1950 *RA = A->getAs<RValueReferenceType>();
1951 if (!RA)
1953
1955 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1957 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1958 }
1959
1960 // T [] (implied, but not stated explicitly)
1961 case Type::IncompleteArray: {
1962 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1963 if (!IAA)
1965
1966 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1967 assert(IAP && "Template parameter not of incomplete array type");
1968
1970 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1973 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1974 }
1975
1976 // T [integer-constant]
1977 case Type::ConstantArray: {
1978 const auto *CAA = S.Context.getAsConstantArrayType(A),
1979 *CAP = S.Context.getAsConstantArrayType(P);
1980 assert(CAP);
1981 if (!CAA || CAA->getSize() != CAP->getSize())
1983
1985 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1988 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1989 }
1990
1991 // type [i]
1992 case Type::DependentSizedArray: {
1993 const auto *AA = S.Context.getAsArrayType(A);
1994 if (!AA)
1996
1997 // Check the element type of the arrays
1998 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1999 assert(DAP);
2001 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
2002 Info, Deduced, TDF & TDF_IgnoreQualifiers,
2004 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2006 return Result;
2007
2008 // Determine the array bound is something we can deduce.
2010 getDeducedNTTParameterFromExpr(Info, DAP->getSizeExpr());
2011 if (!NTTP)
2013
2014 // We can perform template argument deduction for the given non-type
2015 // template parameter.
2016 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2017 "saw non-type template parameter with wrong depth");
2018 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
2019 llvm::APSInt Size(CAA->getSize());
2021 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
2022 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2023 Deduced, HasDeducedAnyParam);
2024 }
2025 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
2026 if (DAA->getSizeExpr())
2028 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
2029 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2030
2031 // Incomplete type does not match a dependently-sized array type
2033 }
2034
2035 // type(*)(T)
2036 // T(*)()
2037 // T(*)(T)
2038 case Type::FunctionProto: {
2039 const auto *FPP = P->castAs<FunctionProtoType>(),
2040 *FPA = A->getAs<FunctionProtoType>();
2041 if (!FPA)
2043
2044 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
2045 FPP->getRefQualifier() != FPA->getRefQualifier() ||
2046 FPP->isVariadic() != FPA->isVariadic())
2048
2049 // Check return types.
2051 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
2053 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2055 return Result;
2056
2057 // Check parameter types.
2059 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
2061 HasDeducedAnyParam,
2062 /*HasDeducedParam=*/nullptr);
2064 return Result;
2065
2068
2069 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
2070 // deducing through the noexcept-specifier if it's part of the canonical
2071 // type. libstdc++ relies on this.
2072 Expr *NoexceptExpr = FPP->getNoexceptExpr();
2074 NoexceptExpr ? getDeducedNTTParameterFromExpr(Info, NoexceptExpr)
2075 : nullptr) {
2076 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2077 "saw non-type template parameter with wrong depth");
2078
2079 llvm::APSInt Noexcept(1);
2080 switch (FPA->canThrow()) {
2081 case CT_Cannot:
2082 Noexcept = 1;
2083 [[fallthrough]];
2084
2085 case CT_Can:
2086 // We give E in noexcept(E) the "deduced from array bound" treatment.
2087 // FIXME: Should we?
2089 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2090 /*DeducedFromArrayBound=*/true, Info,
2091 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2092
2093 case CT_Dependent:
2094 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2096 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2097 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2098 // Can't deduce anything from throw(T...).
2099 break;
2100 }
2101 }
2102 // FIXME: Detect non-deduced exception specification mismatches?
2103 //
2104 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2105 // top-level differences in noexcept-specifications.
2106
2108 }
2109
2110 case Type::InjectedClassName:
2111 // Treat a template's injected-class-name as if the template
2112 // specialization type had been used.
2113
2114 // template-name<T> (where template-name refers to a class template)
2115 // template-name<i>
2116 // TT<T>
2117 // TT<i>
2118 // TT<>
2119 case Type::TemplateSpecialization: {
2120 // When Arg cannot be a derived class, we can just try to deduce template
2121 // arguments from the template-id.
2122 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2123 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2125 Deduced, HasDeducedAnyParam);
2126
2128 Deduced.end());
2129
2131 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2132 Deduced, HasDeducedAnyParam);
2134 return Result;
2135
2136 // We cannot inspect base classes as part of deduction when the type
2137 // is incomplete, so either instantiate any templates necessary to
2138 // complete the type, or skip over it if it cannot be completed.
2139 if (!S.isCompleteType(Info.getLocation(), A))
2140 return Result;
2141
2142 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2143 if (RD->isInvalidDecl())
2144 return Result;
2145
2146 // Reset the incorrectly deduced argument from above.
2147 Deduced = DeducedOrig;
2148
2149 // Check bases according to C++14 [temp.deduct.call] p4b3:
2150 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2152 Deduced, HasDeducedAnyParam);
2154 : Result;
2155 }
2156
2157 // T type::*
2158 // T T::*
2159 // T (type::*)()
2160 // type (T::*)()
2161 // type (type::*)(T)
2162 // type (T::*)(T)
2163 // T (type::*)(T)
2164 // T (T::*)()
2165 // T (T::*)(T)
2166 case Type::MemberPointer: {
2167 const auto *MPP = P->castAs<MemberPointerType>(),
2168 *MPA = A->getAs<MemberPointerType>();
2169 if (!MPA)
2171
2172 QualType PPT = MPP->getPointeeType();
2173 if (PPT->isFunctionType())
2174 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2175 /*IsCtorOrDtor=*/false, Info.getLocation());
2176 QualType APT = MPA->getPointeeType();
2177 if (APT->isFunctionType())
2178 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2179 /*IsCtorOrDtor=*/false, Info.getLocation());
2180
2181 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2183 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2185 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2187 return Result;
2188
2189 QualType TP =
2190 MPP->isSugared()
2191 ? S.Context.getCanonicalTagType(MPP->getMostRecentCXXRecordDecl())
2192 : QualType(MPP->getQualifier().getAsType(), 0);
2193 assert(!TP.isNull() && "member pointer with non-type class");
2194
2195 QualType TA =
2196 MPA->isSugared()
2197 ? S.Context.getCanonicalTagType(MPA->getMostRecentCXXRecordDecl())
2198 : QualType(MPA->getQualifier().getAsType(), 0)
2200 assert(!TA.isNull() && "member pointer with non-type class");
2201
2203 S, TemplateParams, TP, TA, Info, Deduced, SubTDF,
2205 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2206 }
2207
2208 // (clang extension)
2209 //
2210 // type(^)(T)
2211 // T(^)()
2212 // T(^)(T)
2213 case Type::BlockPointer: {
2214 const auto *BPP = P->castAs<BlockPointerType>(),
2215 *BPA = A->getAs<BlockPointerType>();
2216 if (!BPA)
2219 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2221 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2222 }
2223
2224 // (clang extension)
2225 //
2226 // T __attribute__(((ext_vector_type(<integral constant>))))
2227 case Type::ExtVector: {
2228 const auto *VP = P->castAs<ExtVectorType>();
2229 QualType ElementType;
2230 if (const auto *VA = A->getAs<ExtVectorType>()) {
2231 // Make sure that the vectors have the same number of elements.
2232 if (VP->getNumElements() != VA->getNumElements())
2234 ElementType = VA->getElementType();
2235 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2236 // We can't check the number of elements, since the argument has a
2237 // dependent number of elements. This can only occur during partial
2238 // ordering.
2239 ElementType = VA->getElementType();
2240 } else {
2242 }
2243 // Perform deduction on the element types.
2245 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2247 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2248 }
2249
2250 case Type::DependentVector: {
2251 const auto *VP = P->castAs<DependentVectorType>();
2252
2253 if (const auto *VA = A->getAs<VectorType>()) {
2254 // Perform deduction on the element types.
2256 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2257 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2258 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2260 return Result;
2261
2262 // Perform deduction on the vector size, if we can.
2264 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2265 if (!NTTP)
2267
2268 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2269 ArgSize = VA->getNumElements();
2270 // Note that we use the "array bound" rules here; just like in that
2271 // case, we don't have any particular type for the vector size, but
2272 // we can provide one if necessary.
2274 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2275 Info, POK != PartialOrderingKind::None, Deduced,
2276 HasDeducedAnyParam);
2277 }
2278
2279 if (const auto *VA = A->getAs<DependentVectorType>()) {
2280 // Perform deduction on the element types.
2282 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2283 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2284 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2286 return Result;
2287
2288 // Perform deduction on the vector size, if we can.
2290 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2291 if (!NTTP)
2293
2295 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2296 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2297 }
2298
2300 }
2301
2302 // (clang extension)
2303 //
2304 // T __attribute__(((ext_vector_type(N))))
2305 case Type::DependentSizedExtVector: {
2306 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2307
2308 if (const auto *VA = A->getAs<ExtVectorType>()) {
2309 // Perform deduction on the element types.
2311 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2312 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2313 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2315 return Result;
2316
2317 // Perform deduction on the vector size, if we can.
2319 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2320 if (!NTTP)
2322
2323 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2324 ArgSize = VA->getNumElements();
2325 // Note that we use the "array bound" rules here; just like in that
2326 // case, we don't have any particular type for the vector size, but
2327 // we can provide one if necessary.
2329 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2330 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2331 }
2332
2333 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2334 // Perform deduction on the element types.
2336 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2337 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2338 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2340 return Result;
2341
2342 // Perform deduction on the vector size, if we can.
2344 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2345 if (!NTTP)
2347
2349 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2350 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2351 }
2352
2354 }
2355
2356 // (clang extension)
2357 //
2358 // T __attribute__((matrix_type(<integral constant>,
2359 // <integral constant>)))
2360 case Type::ConstantMatrix: {
2361 const auto *MP = P->castAs<ConstantMatrixType>(),
2362 *MA = A->getAs<ConstantMatrixType>();
2363 if (!MA)
2365
2366 // Check that the dimensions are the same
2367 if (MP->getNumRows() != MA->getNumRows() ||
2368 MP->getNumColumns() != MA->getNumColumns()) {
2370 }
2371 // Perform deduction on element types.
2373 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2375 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2376 }
2377
2378 case Type::DependentSizedMatrix: {
2379 const auto *MP = P->castAs<DependentSizedMatrixType>();
2380 const auto *MA = A->getAs<MatrixType>();
2381 if (!MA)
2383
2384 // Check the element type of the matrixes.
2386 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2387 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2388 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2390 return Result;
2391
2392 // Try to deduce a matrix dimension.
2393 auto DeduceMatrixArg =
2394 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2395 Expr *ParamExpr, const MatrixType *A,
2396 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2397 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2398 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2399 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2400 if (!ParamExpr->isValueDependent()) {
2401 std::optional<llvm::APSInt> ParamConst =
2402 ParamExpr->getIntegerConstantExpr(S.Context);
2403 if (!ParamConst)
2405
2406 if (ACM) {
2407 if ((ACM->*GetArgDimension)() == *ParamConst)
2410 }
2411
2412 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2413 if (std::optional<llvm::APSInt> ArgConst =
2414 ArgExpr->getIntegerConstantExpr(S.Context))
2415 if (*ArgConst == *ParamConst)
2418 }
2419
2421 getDeducedNTTParameterFromExpr(Info, ParamExpr);
2422 if (!NTTP)
2424
2425 if (ACM) {
2426 llvm::APSInt ArgConst(
2428 ArgConst = (ACM->*GetArgDimension)();
2430 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2431 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2432 Deduced, HasDeducedAnyParam);
2433 }
2434
2436 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2437 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2438 };
2439
2440 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2444 return Result;
2445
2446 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2449 }
2450
2451 // (clang extension)
2452 //
2453 // T __attribute__(((address_space(N))))
2454 case Type::DependentAddressSpace: {
2455 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2456
2457 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2458 // Perform deduction on the pointer type.
2460 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2461 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2462 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2464 return Result;
2465
2466 // Perform deduction on the address space, if we can.
2468 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2469 if (!NTTP)
2471
2473 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2474 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2475 }
2476
2478 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2479 false);
2480 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2481
2482 // Perform deduction on the pointer types.
2484 S, TemplateParams, ASP->getPointeeType(),
2485 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2487 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2489 return Result;
2490
2491 // Perform deduction on the address space, if we can.
2493 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2494 if (!NTTP)
2496
2498 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2499 Info, POK != PartialOrderingKind::None, Deduced,
2500 HasDeducedAnyParam);
2501 }
2502
2504 }
2505 case Type::DependentBitInt: {
2506 const auto *IP = P->castAs<DependentBitIntType>();
2507
2508 if (const auto *IA = A->getAs<BitIntType>()) {
2509 if (IP->isUnsigned() != IA->isUnsigned())
2511
2513 getDeducedNTTParameterFromExpr(Info, IP->getNumBitsExpr());
2514 if (!NTTP)
2516
2517 // Deduce the size parameter of _BitInt as std::size_t
2519 llvm::APSInt ArgSize(S.Context.getTypeSize(T), /*IsUnsigned=*/true);
2520 ArgSize = IA->getNumBits();
2521
2523 S, TemplateParams, NTTP, ArgSize, T, true, Info,
2524 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2525 }
2526
2527 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2528 if (IP->isUnsigned() != IA->isUnsigned())
2531 }
2532
2534 }
2535
2536 case Type::TypeOfExpr:
2537 case Type::TypeOf:
2538 case Type::DependentName:
2539 case Type::UnresolvedUsing:
2540 case Type::Decltype:
2541 case Type::UnaryTransform:
2542 case Type::DeducedTemplateSpecialization:
2543 case Type::PackExpansion:
2544 case Type::Pipe:
2545 case Type::ArrayParameter:
2546 case Type::HLSLAttributedResource:
2547 case Type::HLSLInlineSpirv:
2548 case Type::OverflowBehavior:
2549 // No template argument deduction for these types
2551
2552 case Type::PackIndexing: {
2553 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2554 if (PIT->hasSelectedType()) {
2556 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2558 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2559 }
2561 }
2562 }
2563
2564 llvm_unreachable("Invalid Type Class!");
2565}
2566
2572 bool *HasDeducedAnyParam) {
2573 // If the template argument is a pack expansion, perform template argument
2574 // deduction against the pattern of that expansion. This only occurs during
2575 // partial ordering.
2576 if (A.isPackExpansion())
2578
2579 switch (P.getKind()) {
2581 llvm_unreachable("Null template argument in parameter list");
2582
2586 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2589 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2590 Info.FirstArg = P;
2591 Info.SecondArg = A;
2593
2595 // PartialOrdering does not matter here, since template specializations are
2596 // not being deduced.
2599 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2600 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2601 HasDeducedAnyParam);
2602 Info.FirstArg = P;
2603 Info.SecondArg = A;
2605
2607 llvm_unreachable("caller should handle pack expansions");
2608
2613
2614 Info.FirstArg = P;
2615 Info.SecondArg = A;
2617
2619 // 'nullptr' has only one possible value, so it always matches.
2622 Info.FirstArg = P;
2623 Info.SecondArg = A;
2625
2628 if (llvm::APSInt::isSameValue(P.getAsIntegral(), A.getAsIntegral()))
2630 }
2631 Info.FirstArg = P;
2632 Info.SecondArg = A;
2634
2636 // FIXME: structural equality will also compare types,
2637 // but they should match iff they have the same value.
2639 A.structurallyEquals(P))
2641
2642 Info.FirstArg = P;
2643 Info.SecondArg = A;
2645
2649 switch (A.getKind()) {
2651 // The type of the value is the type of the expression as written.
2653 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2655 PartialOrdering, Deduced, HasDeducedAnyParam);
2656 }
2660 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2662 HasDeducedAnyParam);
2663
2666 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2667 Deduced, HasDeducedAnyParam);
2668
2671 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2672 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2673
2679 Info.FirstArg = P;
2680 Info.SecondArg = A;
2682 }
2683 llvm_unreachable("Unknown template argument kind");
2684 }
2685 // Can't deduce anything, but that's okay.
2688 llvm_unreachable("Argument packs should be expanded by the caller!");
2689 }
2690
2691 llvm_unreachable("Invalid TemplateArgument Kind!");
2692}
2693
2694/// Determine whether there is a template argument to be used for
2695/// deduction.
2696///
2697/// This routine "expands" argument packs in-place, overriding its input
2698/// parameters so that \c Args[ArgIdx] will be the available template argument.
2699///
2700/// \returns true if there is another template argument (which will be at
2701/// \c Args[ArgIdx]), false otherwise.
2703 unsigned &ArgIdx) {
2704 if (ArgIdx == Args.size())
2705 return false;
2706
2707 const TemplateArgument &Arg = Args[ArgIdx];
2708 if (Arg.getKind() != TemplateArgument::Pack)
2709 return true;
2710
2711 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2712 Args = Arg.pack_elements();
2713 ArgIdx = 0;
2714 return ArgIdx < Args.size();
2715}
2716
2717/// Determine whether the given set of template arguments has a pack
2718/// expansion that is not the last template argument.
2720 bool FoundPackExpansion = false;
2721 for (const auto &A : Args) {
2722 if (FoundPackExpansion)
2723 return true;
2724
2725 if (A.getKind() == TemplateArgument::Pack)
2726 return hasPackExpansionBeforeEnd(A.pack_elements());
2727
2728 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2729 // templates, it should not be treated as a pack expansion.
2730 if (A.isPackExpansion())
2731 FoundPackExpansion = true;
2732 }
2733
2734 return false;
2735}
2736
2743 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2744 PackFold PackFold, bool *HasDeducedAnyParam) {
2745 bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
2747 FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
2749
2750 // C++0x [temp.deduct.type]p9:
2751 // If the template argument list of P contains a pack expansion that is not
2752 // the last template argument, the entire template argument list is a
2753 // non-deduced context.
2754 if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
2756
2757 // C++0x [temp.deduct.type]p9:
2758 // If P has a form that contains <T> or <i>, then each argument Pi of the
2759 // respective template argument list P is compared with the corresponding
2760 // argument Ai of the corresponding template argument list of A.
2761 for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
2763 return !FoldPackParameter && hasTemplateArgumentForDeduction(As, ArgIdx)
2766
2767 if (!Ps[ParamIdx].isPackExpansion()) {
2768 // The simple case: deduce template arguments by matching Pi and Ai.
2769
2770 // Check whether we have enough arguments.
2771 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2772 return !FoldPackArgument && NumberOfArgumentsMustMatch
2775
2776 if (As[ArgIdx].isPackExpansion()) {
2777 // C++1z [temp.deduct.type]p9:
2778 // During partial ordering, if Ai was originally a pack expansion
2779 // [and] Pi is not a pack expansion, template argument deduction
2780 // fails.
2781 if (!FoldPackArgument)
2783
2784 TemplateArgument Pattern = As[ArgIdx].getPackExpansionPattern();
2785 for (;;) {
2786 // Deduce template parameters from the pattern.
2788 S, TemplateParams, Ps[ParamIdx], Pattern, Info,
2789 PartialOrdering, Deduced, HasDeducedAnyParam);
2791 return Result;
2792
2793 ++ParamIdx;
2796 if (Ps[ParamIdx].isPackExpansion())
2797 break;
2798 }
2799 } else {
2800 // Perform deduction for this Pi/Ai pair.
2802 S, TemplateParams, Ps[ParamIdx], As[ArgIdx], Info,
2803 PartialOrdering, Deduced, HasDeducedAnyParam);
2805 return Result;
2806
2807 ++ArgIdx;
2808 ++ParamIdx;
2809 continue;
2810 }
2811 }
2812
2813 // The parameter is a pack expansion.
2814
2815 // C++0x [temp.deduct.type]p9:
2816 // If Pi is a pack expansion, then the pattern of Pi is compared with
2817 // each remaining argument in the template argument list of A. Each
2818 // comparison deduces template arguments for subsequent positions in the
2819 // template parameter packs expanded by Pi.
2820 TemplateArgument Pattern = Ps[ParamIdx].getPackExpansionPattern();
2821
2822 // Prepare to deduce the packs within the pattern.
2823 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2824
2825 // Keep track of the deduced template arguments for each parameter pack
2826 // expanded by this pack expansion (the outer index) and for each
2827 // template argument (the inner SmallVectors).
2828 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2829 PackScope.hasNextElement();
2830 ++ArgIdx) {
2831 if (!As[ArgIdx].isPackExpansion()) {
2832 if (!FoldPackParameter)
2834 if (FoldPackArgument)
2835 Info.setStrictPackMatch();
2836 }
2837 // Deduce template arguments from the pattern.
2839 S, TemplateParams, Pattern, As[ArgIdx], Info, PartialOrdering,
2840 Deduced, HasDeducedAnyParam);
2842 return Result;
2843
2844 PackScope.nextPackElement();
2845 }
2846
2847 // Build argument packs for each of the parameter packs expanded by this
2848 // pack expansion.
2849 return PackScope.finish();
2850 }
2851}
2852
2857 bool NumberOfArgumentsMustMatch) {
2858 return ::DeduceTemplateArguments(
2859 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2860 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2861 /*HasDeducedAnyParam=*/nullptr);
2862}
2863
2866 QualType NTTPType, SourceLocation Loc) {
2867 switch (Arg.getKind()) {
2869 llvm_unreachable("Can't get a NULL template argument here");
2870
2872 return TemplateArgumentLoc(
2873 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2874
2876 if (NTTPType.isNull())
2877 NTTPType = Arg.getParamTypeForDecl();
2878 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2879 .getAs<Expr>();
2880 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2881 }
2882
2884 if (NTTPType.isNull())
2885 NTTPType = Arg.getNullPtrType();
2886 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2887 .getAs<Expr>();
2888 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2889 E);
2890 }
2891
2895 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2896 }
2897
2902 Builder.MakeTrivial(Context, Template.getQualifier(), Loc);
2903 return TemplateArgumentLoc(
2904 Context, Arg, Loc, Builder.getWithLocInContext(Context), Loc,
2905 /*EllipsisLoc=*/Arg.getKind() == TemplateArgument::TemplateExpansion
2906 ? Loc
2907 : SourceLocation());
2908 }
2909
2911 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2912
2915 }
2916
2917 llvm_unreachable("Invalid TemplateArgument Kind!");
2918}
2919
2922 SourceLocation Location) {
2924 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2925}
2926
2927/// Convert the given deduced template argument and add it to the set of
2928/// fully-converted template arguments.
2929static bool
2932 TemplateDeductionInfo &Info, bool IsDeduced,
2934 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2935 unsigned ArgumentPackIndex) {
2936 // Convert the deduced template argument into a template
2937 // argument that we can check, almost as if the user had written
2938 // the template argument explicitly.
2939 TemplateArgumentLoc ArgLoc =
2941
2942 SaveAndRestore _1(CTAI.MatchingTTP, false);
2943 SaveAndRestore _2(CTAI.StrictPackMatch, false);
2944 // Check the template argument, converting it as necessary.
2945 auto Res = S.CheckTemplateArgument(
2946 Param, ArgLoc, Template, Template->getLocation(),
2947 Template->getSourceRange().getEnd(), ArgumentPackIndex, CTAI,
2948 IsDeduced
2952 if (CTAI.StrictPackMatch)
2953 Info.setStrictPackMatch();
2954 return Res;
2955 };
2956
2957 if (Arg.getKind() == TemplateArgument::Pack) {
2958 // This is a template argument pack, so check each of its arguments against
2959 // the template parameter.
2960 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2961 CanonicalPackedArgsBuilder;
2962 for (const auto &P : Arg.pack_elements()) {
2963 // When converting the deduced template argument, append it to the
2964 // general output list. We need to do this so that the template argument
2965 // checking logic has all of the prior template arguments available.
2966 DeducedTemplateArgument InnerArg(P);
2968 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2969 "deduced nested pack");
2970 if (P.isNull()) {
2971 // We deduced arguments for some elements of this pack, but not for
2972 // all of them. This happens if we get a conditionally-non-deduced
2973 // context in a pack expansion (such as an overload set in one of the
2974 // arguments).
2975 S.Diag(Param->getLocation(),
2976 diag::err_template_arg_deduced_incomplete_pack)
2977 << Arg << Param;
2978 return true;
2979 }
2980 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2981 return true;
2982
2983 // Move the converted template argument into our argument pack.
2984 SugaredPackedArgsBuilder.push_back(CTAI.SugaredConverted.pop_back_val());
2985 CanonicalPackedArgsBuilder.push_back(
2986 CTAI.CanonicalConverted.pop_back_val());
2987 }
2988
2989 // If the pack is empty, we still need to substitute into the parameter
2990 // itself, in case that substitution fails.
2991 if (SugaredPackedArgsBuilder.empty()) {
2994 /*Final=*/true);
2995 Sema::ArgPackSubstIndexRAII OnlySubstNonPackExpansion(S, std::nullopt);
2996
2997 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2998 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2999 NTTP, CTAI.SugaredConverted,
3000 Template->getSourceRange());
3001 if (Inst.isInvalid() ||
3002 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
3003 NTTP->getDeclName()).isNull())
3004 return true;
3005 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3006 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3007 TTP, CTAI.SugaredConverted,
3008 Template->getSourceRange());
3009 if (Inst.isInvalid() ||
3010 !S.SubstTemplateParams(TTP->getTemplateParameters(), S.CurContext,
3011 Args))
3012 return true;
3013 }
3014 // For type parameters, no substitution is ever required.
3015 }
3016
3017 // Create the resulting argument pack.
3018 CTAI.SugaredConverted.push_back(
3019 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
3021 S.Context, CanonicalPackedArgsBuilder));
3022 return false;
3023 }
3024
3025 return ConvertArg(Arg, 0);
3026}
3027
3028/// \param IsIncomplete When used, we only consider template parameters that
3029/// were deduced, disregarding any default arguments. After the function
3030/// finishes, the object pointed at will contain a value indicating if the
3031/// conversion was actually incomplete.
3033 Sema &S, NamedDecl *Template, TemplateParameterList *TemplateParams,
3036 LocalInstantiationScope *CurrentInstantiationScope,
3037 unsigned NumAlreadyConverted, bool *IsIncomplete) {
3038 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3039 NamedDecl *Param = TemplateParams->getParam(I);
3040
3041 // C++0x [temp.arg.explicit]p3:
3042 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3043 // be deduced to an empty sequence of template arguments.
3044 // FIXME: Where did the word "trailing" come from?
3045 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3046 if (auto Result =
3047 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3049 return Result;
3050 }
3051
3052 if (!Deduced[I].isNull()) {
3053 if (I < NumAlreadyConverted) {
3054 // We may have had explicitly-specified template arguments for a
3055 // template parameter pack (that may or may not have been extended
3056 // via additional deduced arguments).
3057 if (Param->isParameterPack() && CurrentInstantiationScope &&
3058 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3059 // Forget the partially-substituted pack; its substitution is now
3060 // complete.
3061 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3062 // We still need to check the argument in case it was extended by
3063 // deduction.
3064 } else {
3065 // We have already fully type-checked and converted this
3066 // argument, because it was explicitly-specified. Just record the
3067 // presence of this argument.
3068 CTAI.SugaredConverted.push_back(Deduced[I]);
3069 CTAI.CanonicalConverted.push_back(
3071 continue;
3072 }
3073 }
3074
3075 // We may have deduced this argument, so it still needs to be
3076 // checked and converted.
3077 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3078 IsDeduced, CTAI)) {
3079 Info.Param = makeTemplateParameter(Param);
3080 // FIXME: These template arguments are temporary. Free them!
3081 Info.reset(
3084 CTAI.CanonicalConverted));
3086 }
3087
3088 continue;
3089 }
3090
3091 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3092 // template parameters to remain not deduced. As a provisional fix for a
3093 // core issue that does not exist yet, which may be related to CWG2160, only
3094 // consider template parameters that were deduced, disregarding any default
3095 // arguments.
3096 if (IsIncomplete) {
3097 *IsIncomplete = true;
3098 CTAI.SugaredConverted.push_back({});
3099 CTAI.CanonicalConverted.push_back({});
3100 continue;
3101 }
3102
3103 // Substitute into the default template argument, if available.
3104 bool HasDefaultArg = false;
3105 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3106 if (!TD) {
3110 }
3111
3112 TemplateArgumentLoc DefArg;
3113 {
3114 Qualifiers ThisTypeQuals;
3115 CXXRecordDecl *ThisContext = nullptr;
3116 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3117 if (Rec->isLambda())
3118 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3119 ThisContext = Method->getParent();
3120 ThisTypeQuals = Method->getMethodQualifiers();
3121 }
3122
3123 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3124 S.getLangOpts().CPlusPlus17);
3125
3127 TD, /*TemplateKWLoc=*/SourceLocation(), TD->getLocation(),
3128 TD->getSourceRange().getEnd(), Param, CTAI.SugaredConverted,
3129 CTAI.CanonicalConverted, HasDefaultArg);
3130 }
3131
3132 // If there was no default argument, deduction is incomplete.
3133 if (DefArg.getArgument().isNull()) {
3134 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3135 Info.reset(
3138
3141 }
3142
3143 SaveAndRestore _1(CTAI.PartialOrdering, false);
3144 SaveAndRestore _2(CTAI.MatchingTTP, false);
3145 SaveAndRestore _3(CTAI.StrictPackMatch, false);
3146 // Check whether we can actually use the default argument.
3148 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3149 /*ArgumentPackIndex=*/0, CTAI, Sema::CTAK_Specified)) {
3150 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3151 // FIXME: These template arguments are temporary. Free them!
3152 Info.reset(
3156 }
3157
3158 // If we get here, we successfully used the default template argument.
3159 }
3160
3162}
3163
3165 if (auto *DC = dyn_cast<DeclContext>(D))
3166 return DC;
3167 return D->getDeclContext();
3168}
3169
3170template<typename T> struct IsPartialSpecialization {
3171 static constexpr bool value = false;
3172};
3173template<>
3177template<>
3179 static constexpr bool value = true;
3180};
3181
3184 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3185 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3186 TemplateDeductionInfo &Info) {
3187 llvm::SmallVector<AssociatedConstraint, 3> AssociatedConstraints;
3188 bool DeducedArgsNeedReplacement = false;
3189 if (auto *TD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Template)) {
3190 TD->getAssociatedConstraints(AssociatedConstraints);
3191 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3192 } else if (auto *TD =
3193 dyn_cast<VarTemplatePartialSpecializationDecl>(Template)) {
3194 TD->getAssociatedConstraints(AssociatedConstraints);
3195 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3196 } else {
3197 cast<TemplateDecl>(Template)->getAssociatedConstraints(
3198 AssociatedConstraints);
3199 }
3200
3201 std::optional<ArrayRef<TemplateArgument>> Innermost;
3202 // If we don't need to replace the deduced template arguments,
3203 // we can add them immediately as the inner-most argument list.
3204 if (!DeducedArgsNeedReplacement)
3205 Innermost = SugaredDeducedArgs;
3206
3208 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3209 /*RelativeToPrimary=*/true, /*Pattern=*/
3210 nullptr, /*ForConstraintInstantiation=*/true);
3211
3212 // getTemplateInstantiationArgs picks up the non-deduced version of the
3213 // template args when this is a variable template partial specialization and
3214 // not class-scope explicit specialization, so replace with Deduced Args
3215 // instead of adding to inner-most.
3216 if (!Innermost)
3217 MLTAL.replaceInnermostTemplateArguments(Template, SugaredDeducedArgs);
3218
3219 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3220 Info.getLocation(),
3223 Info.reset(
3224 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3225 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3227 }
3229}
3230
3234 TemplateDeductionInfo &Info) {
3235 TemplateParameterList *TPL = Template->getTemplateParameters();
3236 TemplateArgumentListInfo InstArgs(TPL->getLAngleLoc(), TPL->getRAngleLoc());
3237 if (S.SubstTemplateArguments(Ps, MLTAL, InstArgs)) {
3238 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3239 if (ParamIdx >= TPL->size())
3240 ParamIdx = TPL->size() - 1;
3241
3242 Decl *Param = TPL->getParam(ParamIdx);
3243 Info.Param = makeTemplateParameter(Param);
3244 Info.FirstArg = Ps[ArgIdx].getArgument();
3246 }
3247
3250 if (S.CheckTemplateArgumentList(Template, Template->getLocation(), InstArgs,
3251 /*DefaultArgs=*/{}, false, InstCTAI,
3252 /*UpdateArgsWithConversions=*/true,
3257
3258 // Check that we produced the correct argument list.
3260 AsStack{As};
3261 for (;;) {
3262 auto take = [](SmallVectorImpl<ArrayRef<TemplateArgument>> &Stack)
3264 while (!Stack.empty()) {
3265 auto &Xs = Stack.back();
3266 if (Xs.empty()) {
3267 Stack.pop_back();
3268 continue;
3269 }
3270 auto &X = Xs.front();
3271 if (X.getKind() == TemplateArgument::Pack) {
3272 Stack.emplace_back(X.getPackAsArray());
3273 Xs = Xs.drop_front();
3274 continue;
3275 }
3276 assert(!X.isNull());
3277 return {Xs, X};
3278 }
3279 static constexpr ArrayRef<TemplateArgument> None;
3280 return {const_cast<ArrayRef<TemplateArgument> &>(None),
3282 };
3283 auto [Ps, P] = take(PsStack);
3284 auto [As, A] = take(AsStack);
3285 if (P.isNull() && A.isNull())
3286 break;
3287 TemplateArgument PP = P.isPackExpansion() ? P.getPackExpansionPattern() : P,
3288 PA = A.isPackExpansion() ? A.getPackExpansionPattern() : A;
3289 if (!S.Context.isSameTemplateArgument(PP, PA)) {
3290 if (!P.isPackExpansion() && !A.isPackExpansion()) {
3292 (AsStack.empty() ? As.end() : AsStack.back().begin()) -
3293 As.begin()));
3294 Info.FirstArg = P;
3295 Info.SecondArg = A;
3297 }
3298 if (P.isPackExpansion()) {
3299 Ps = Ps.drop_front();
3300 continue;
3301 }
3302 if (A.isPackExpansion()) {
3303 As = As.drop_front();
3304 continue;
3305 }
3306 }
3307 Ps = Ps.drop_front(P.isPackExpansion() ? 0 : 1);
3308 As = As.drop_front(A.isPackExpansion() && !P.isPackExpansion() ? 0 : 1);
3309 }
3310 assert(PsStack.empty());
3311 assert(AsStack.empty());
3313}
3314
3315/// Complete template argument deduction.
3317 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3321 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3322 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Entity));
3323
3324 // C++ [temp.deduct.type]p2:
3325 // [...] or if any template argument remains neither deduced nor
3326 // explicitly specified, template argument deduction fails.
3329 S, Entity, EntityTPL, /*IsDeduced=*/PartialOrdering, Deduced, Info,
3330 CTAI,
3331 /*CurrentInstantiationScope=*/nullptr,
3332 /*NumAlreadyConverted=*/0U, /*IsIncomplete=*/nullptr);
3334 return Result;
3335
3336 if (CopyDeducedArgs) {
3337 // Form the template argument list from the deduced template arguments.
3338 TemplateArgumentList *SugaredDeducedArgumentList =
3340 TemplateArgumentList *CanonicalDeducedArgumentList =
3342 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3343 }
3344
3346 /*Final=*/true);
3347 MLTAL.addOuterRetainedLevels(Template->getTemplateParameters()->getDepth());
3348 if (auto Result =
3349 CheckDeducedTemplateArgumentList(S, Template, Ps, As, MLTAL, Info);
3351 return Result;
3352
3353 if (!PartialOrdering) {
3355 S, Entity, CTAI.SugaredConverted, CTAI.CanonicalConverted, Info);
3357 return Result;
3358 }
3359
3361}
3363 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3367 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3368 TemplateParameterList *TPL = Template->getTemplateParameters();
3369 SmallVector<TemplateArgumentLoc, 8> PsLoc(Ps.size());
3370 for (unsigned I = 0, N = Ps.size(); I != N; ++I)
3371 PsLoc[I] = S.getTrivialTemplateArgumentLoc(Ps[I], QualType(),
3372 TPL->getParam(I)->getLocation());
3373 return FinishTemplateArgumentDeduction(S, Entity, EntityTPL, Template,
3374 PartialOrdering, PsLoc, As, Deduced,
3375 Info, CopyDeducedArgs);
3376}
3377
3378/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3379/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3380/// the three implementations.
3382 Sema &S, TemplateDecl *TD,
3384 TemplateDeductionInfo &Info) {
3386
3387 // C++ [temp.deduct.type]p2:
3388 // [...] or if any template argument remains neither deduced nor
3389 // explicitly specified, template argument deduction fails.
3392 S, TD, TD->getTemplateParameters(), /*IsDeduced=*/false, Deduced,
3393 Info, CTAI,
3394 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3395 /*IsIncomplete=*/nullptr);
3397 return Result;
3398
3399 return ::CheckDeducedArgumentConstraints(S, TD, CTAI.SugaredConverted,
3400 CTAI.CanonicalConverted, Info);
3401}
3402
3403/// Perform template argument deduction to determine whether the given template
3404/// arguments match the given class or variable template partial specialization
3405/// per C++ [temp.class.spec.match].
3406template <typename T>
3407static std::enable_if_t<IsPartialSpecialization<T>::value,
3410 ArrayRef<TemplateArgument> TemplateArgs,
3411 TemplateDeductionInfo &Info) {
3412 if (Partial->isInvalidDecl())
3414
3415 // C++ [temp.class.spec.match]p2:
3416 // A partial specialization matches a given actual template
3417 // argument list if the template arguments of the partial
3418 // specialization can be deduced from the actual template argument
3419 // list (14.8.2).
3420
3421 // Unevaluated SFINAE context.
3424 Sema::SFINAETrap Trap(S, Info);
3425
3426 // This deduction has no relation to any outer instantiation we might be
3427 // performing.
3428 LocalInstantiationScope InstantiationScope(S);
3429
3431 Deduced.resize(Partial->getTemplateParameters()->size());
3433 S, Partial->getTemplateParameters(),
3434 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3435 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3437 /*HasDeducedAnyParam=*/nullptr);
3439 return Result;
3440
3441 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3442 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs);
3443 if (Inst.isInvalid())
3445
3448 Result = ::FinishTemplateArgumentDeduction(
3449 S, Partial, Partial->getTemplateParameters(),
3450 Partial->getSpecializedTemplate(),
3451 /*IsPartialOrdering=*/false,
3452 Partial->getTemplateArgsAsWritten()->arguments(), TemplateArgs, Deduced,
3453 Info, /*CopyDeducedArgs=*/true);
3454 });
3455
3457 return Result;
3458
3459 if (Trap.hasErrorOccurred())
3461
3463}
3464
3467 ArrayRef<TemplateArgument> TemplateArgs,
3468 TemplateDeductionInfo &Info) {
3469 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3470}
3473 ArrayRef<TemplateArgument> TemplateArgs,
3474 TemplateDeductionInfo &Info) {
3475 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3476}
3477
3481 if (TD->isInvalidDecl())
3483
3484 QualType PType;
3485 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3486 // Use the InjectedClassNameType.
3487 PType = Context.getCanonicalTagType(CTD->getTemplatedDecl());
3488 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3489 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3490 } else {
3491 assert(false && "Expected a class or alias template");
3492 }
3493
3494 // Unevaluated SFINAE context.
3497 SFINAETrap Trap(*this, Info);
3498
3499 // This deduction has no relation to any outer instantiation we might be
3500 // performing.
3501 LocalInstantiationScope InstantiationScope(*this);
3502
3504 TD->getTemplateParameters()->size());
3507 if (auto DeducedResult = DeduceTemplateArguments(
3508 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3509 DeducedResult != TemplateDeductionResult::Success) {
3510 return DeducedResult;
3511 }
3512
3513 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3514 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs);
3515 if (Inst.isInvalid())
3517
3520 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3521 });
3522
3524 return Result;
3525
3526 if (Trap.hasErrorOccurred())
3528
3530}
3531
3532/// Determine whether the given type T is a simple-template-id type.
3534 if (const TemplateSpecializationType *Spec
3535 = T->getAs<TemplateSpecializationType>())
3536 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3537
3538 // C++17 [temp.local]p2:
3539 // the injected-class-name [...] is equivalent to the template-name followed
3540 // by the template-arguments of the class template specialization or partial
3541 // specialization enclosed in <>
3542 // ... which means it's equivalent to a simple-template-id.
3543 //
3544 // This only arises during class template argument deduction for a copy
3545 // deduction candidate, where it permits slicing.
3546 if (isa<InjectedClassNameType>(T.getCanonicalType()))
3547 return true;
3548
3549 return false;
3550}
3551
3554 TemplateArgumentListInfo &ExplicitTemplateArgs,
3557 TemplateDeductionInfo &Info) {
3558 assert(isSFINAEContext());
3559 assert(isUnevaluatedContext());
3560
3561 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3562 TemplateParameterList *TemplateParams
3563 = FunctionTemplate->getTemplateParameters();
3564
3565 if (ExplicitTemplateArgs.size() == 0) {
3566 // No arguments to substitute; just copy over the parameter types and
3567 // fill in the function type.
3568 for (auto *P : Function->parameters())
3569 ParamTypes.push_back(P->getType());
3570
3571 if (FunctionType)
3572 *FunctionType = Function->getType();
3574 }
3575
3576 // C++ [temp.arg.explicit]p3:
3577 // Template arguments that are present shall be specified in the
3578 // declaration order of their corresponding template-parameters. The
3579 // template argument list shall not specify more template-arguments than
3580 // there are corresponding template-parameters.
3581
3582 // Enter a new template instantiation context where we check the
3583 // explicitly-specified template arguments against this function template,
3584 // and then substitute them into the function parameter types.
3587 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3589 if (Inst.isInvalid())
3591
3594 ExplicitTemplateArgs, /*DefaultArgs=*/{},
3595 /*PartialTemplateArgs=*/true, CTAI,
3596 /*UpdateArgsWithConversions=*/false)) {
3597 unsigned Index = CTAI.SugaredConverted.size();
3598 if (Index >= TemplateParams->size())
3600 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3602 }
3603
3604 // Form the template argument list from the explicitly-specified
3605 // template arguments.
3606 TemplateArgumentList *SugaredExplicitArgumentList =
3608 TemplateArgumentList *CanonicalExplicitArgumentList =
3610 Info.setExplicitArgs(SugaredExplicitArgumentList,
3611 CanonicalExplicitArgumentList);
3612
3613 // Template argument deduction and the final substitution should be
3614 // done in the context of the templated declaration. Explicit
3615 // argument substitution, on the other hand, needs to happen in the
3616 // calling context.
3617 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3618
3619 // If we deduced template arguments for a template parameter pack,
3620 // note that the template argument pack is partially substituted and record
3621 // the explicit template arguments. They'll be used as part of deduction
3622 // for this template parameter pack.
3623 unsigned PartiallySubstitutedPackIndex = -1u;
3624 if (!CTAI.SugaredConverted.empty()) {
3625 const TemplateArgument &Arg = CTAI.SugaredConverted.back();
3626 if (Arg.getKind() == TemplateArgument::Pack) {
3627 auto *Param = TemplateParams->getParam(CTAI.SugaredConverted.size() - 1);
3628 // If this is a fully-saturated fixed-size pack, it should be
3629 // fully-substituted, not partially-substituted.
3630 UnsignedOrNone Expansions = getExpandedPackSize(Param);
3631 if (!Expansions || Arg.pack_size() < *Expansions) {
3632 PartiallySubstitutedPackIndex = CTAI.SugaredConverted.size() - 1;
3633 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3634 Param, Arg.pack_begin(), Arg.pack_size());
3635 }
3636 }
3637 }
3638
3639 const FunctionProtoType *Proto
3640 = Function->getType()->getAs<FunctionProtoType>();
3641 assert(Proto && "Function template does not have a prototype?");
3642
3643 // Isolate our substituted parameters from our caller.
3644 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3645
3646 ExtParameterInfoBuilder ExtParamInfos;
3647
3649 SugaredExplicitArgumentList->asArray(),
3650 /*Final=*/true);
3651
3652 // Instantiate the types of each of the function parameters given the
3653 // explicitly-specified template arguments. If the function has a trailing
3654 // return type, substitute it after the arguments to ensure we substitute
3655 // in lexical order.
3656 if (Proto->hasTrailingReturn()) {
3657 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3658 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3659 /*params=*/nullptr, ExtParamInfos))
3661 }
3662
3663 // Instantiate the return type.
3664 QualType ResultType;
3665 {
3666 // C++11 [expr.prim.general]p3:
3667 // If a declaration declares a member function or member function
3668 // template of a class X, the expression this is a prvalue of type
3669 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3670 // and the end of the function-definition, member-declarator, or
3671 // declarator.
3672 Qualifiers ThisTypeQuals;
3673 CXXRecordDecl *ThisContext = nullptr;
3674 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3675 ThisContext = Method->getParent();
3676 ThisTypeQuals = Method->getMethodQualifiers();
3677 }
3678
3679 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3681
3682 ResultType =
3683 SubstType(Proto->getReturnType(), MLTAL,
3684 Function->getTypeSpecStartLoc(), Function->getDeclName());
3685 if (ResultType.isNull())
3687 // CUDA: Kernel function must have 'void' return type.
3688 if (getLangOpts().CUDA)
3689 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3690 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3691 << Function->getType() << Function->getSourceRange();
3693 }
3694 }
3695
3696 // Instantiate the types of each of the function parameters given the
3697 // explicitly-specified template arguments if we didn't do so earlier.
3698 if (!Proto->hasTrailingReturn() &&
3699 SubstParmTypes(Function->getLocation(), Function->parameters(),
3700 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3701 /*params*/ nullptr, ExtParamInfos))
3703
3704 if (FunctionType) {
3705 auto EPI = Proto->getExtProtoInfo();
3706 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3707 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3708 Function->getLocation(),
3709 Function->getDeclName(),
3710 EPI);
3711 if (FunctionType->isNull())
3713 }
3714
3715 // C++ [temp.arg.explicit]p2:
3716 // Trailing template arguments that can be deduced (14.8.2) may be
3717 // omitted from the list of explicit template-arguments. If all of the
3718 // template arguments can be deduced, they may all be omitted; in this
3719 // case, the empty template argument list <> itself may also be omitted.
3720 //
3721 // Take all of the explicitly-specified arguments and put them into
3722 // the set of deduced template arguments. The partially-substituted
3723 // parameter pack, however, will be set to NULL since the deduction
3724 // mechanism handles the partially-substituted argument pack directly.
3725 Deduced.reserve(TemplateParams->size());
3726 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3727 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3728 if (I == PartiallySubstitutedPackIndex)
3729 Deduced.push_back(DeducedTemplateArgument());
3730 else
3731 Deduced.push_back(Arg);
3732 }
3733
3735}
3736
3737/// Check whether the deduced argument type for a call to a function
3738/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3741 Sema::OriginalCallArg OriginalArg,
3742 QualType DeducedA) {
3743 ASTContext &Context = S.Context;
3744
3745 auto Failed = [&]() -> TemplateDeductionResult {
3746 Info.FirstArg = TemplateArgument(DeducedA);
3747 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3748 Info.CallArgIndex = OriginalArg.ArgIdx;
3749 return OriginalArg.DecomposedParam
3752 };
3753
3754 QualType A = OriginalArg.OriginalArgType;
3755 QualType OriginalParamType = OriginalArg.OriginalParamType;
3756
3757 // Check for type equality (top-level cv-qualifiers and _Atomic are ignored,
3758 // since _Atomic is treated as a qualifier).
3759 if (Context.hasSameType(A.getAtomicUnqualifiedType(),
3760 DeducedA.getAtomicUnqualifiedType()))
3762
3763 // Strip off references on the argument types; they aren't needed for
3764 // the following checks.
3765 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3766 DeducedA = DeducedARef->getPointeeType();
3767 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3768 A = ARef->getPointeeType();
3769
3770 // C++ [temp.deduct.call]p4:
3771 // [...] However, there are three cases that allow a difference:
3772 // - If the original P is a reference type, the deduced A (i.e., the
3773 // type referred to by the reference) can be more cv-qualified than
3774 // the transformed A.
3775 if (const ReferenceType *OriginalParamRef
3776 = OriginalParamType->getAs<ReferenceType>()) {
3777 // We don't want to keep the reference around any more.
3778 OriginalParamType = OriginalParamRef->getPointeeType();
3779
3780 // FIXME: Resolve core issue (no number yet): if the original P is a
3781 // reference type and the transformed A is function type "noexcept F",
3782 // the deduced A can be F.
3783 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA))
3785
3786 Qualifiers AQuals = A.getQualifiers();
3787 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3788
3789 // Under Objective-C++ ARC, the deduced type may have implicitly
3790 // been given strong or (when dealing with a const reference)
3791 // unsafe_unretained lifetime. If so, update the original
3792 // qualifiers to include this lifetime.
3793 if (S.getLangOpts().ObjCAutoRefCount &&
3794 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3796 (DeducedAQuals.hasConst() &&
3797 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3798 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3799 }
3800
3801 if (AQuals == DeducedAQuals) {
3802 // Qualifiers match; there's nothing to do.
3803 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3804 return Failed();
3805 } else {
3806 // Qualifiers are compatible, so have the argument type adopt the
3807 // deduced argument type's qualifiers as if we had performed the
3808 // qualification conversion.
3809 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3810 }
3811 }
3812
3813 // - The transformed A can be another pointer or pointer to member
3814 // type that can be converted to the deduced A via a function pointer
3815 // conversion and/or a qualification conversion.
3816 //
3817 // Also allow conversions which merely strip __attribute__((noreturn)) from
3818 // function types (recursively).
3819 bool ObjCLifetimeConversion = false;
3820 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3821 (S.IsQualificationConversion(A, DeducedA, false,
3822 ObjCLifetimeConversion) ||
3823 S.IsFunctionConversion(A, DeducedA)))
3825
3826 // - If P is a class and P has the form simple-template-id, then the
3827 // transformed A can be a derived class of the deduced A. [...]
3828 // [...] Likewise, if P is a pointer to a class of the form
3829 // simple-template-id, the transformed A can be a pointer to a
3830 // derived class pointed to by the deduced A.
3831 if (const PointerType *OriginalParamPtr
3832 = OriginalParamType->getAs<PointerType>()) {
3833 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3834 if (const PointerType *APtr = A->getAs<PointerType>()) {
3835 if (A->getPointeeType()->isRecordType()) {
3836 OriginalParamType = OriginalParamPtr->getPointeeType();
3837 DeducedA = DeducedAPtr->getPointeeType();
3838 A = APtr->getPointeeType();
3839 }
3840 }
3841 }
3842 }
3843
3844 if (Context.hasSameUnqualifiedType(A, DeducedA))
3846
3847 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3848 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3850
3851 return Failed();
3852}
3853
3854/// Find the pack index for a particular parameter index in an instantiation of
3855/// a function template with specific arguments.
3856///
3857/// \return The pack index for whichever pack produced this parameter, or -1
3858/// if this was not produced by a parameter. Intended to be used as the
3859/// ArgumentPackSubstitutionIndex for further substitutions.
3860// FIXME: We should track this in OriginalCallArgs so we don't need to
3861// reconstruct it here.
3862static UnsignedOrNone
3865 unsigned ParamIdx) {
3866 unsigned Idx = 0;
3867 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3868 if (PD->isParameterPack()) {
3869 UnsignedOrNone NumArgs =
3870 S.getNumArgumentsInExpansion(PD->getType(), Args);
3871 unsigned NumExpansions = NumArgs ? *NumArgs : 1;
3872 if (Idx + NumExpansions > ParamIdx)
3873 return ParamIdx - Idx;
3874 Idx += NumExpansions;
3875 } else {
3876 if (Idx == ParamIdx)
3877 return std::nullopt; // Not a pack expansion
3878 ++Idx;
3879 }
3880 }
3881
3882 llvm_unreachable("parameter index would not be produced from template");
3883}
3884
3885// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3886// we'll try to instantiate and update its explicit specifier after constraint
3887// checking.
3890 const MultiLevelTemplateArgumentList &SubstArgs,
3892 ArrayRef<TemplateArgument> DeducedArgs) {
3893 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3894 return isa<CXXConstructorDecl>(D)
3895 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3896 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3897 };
3898 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3900 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3901 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3902 };
3903
3904 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3905 Expr *ExplicitExpr = ES.getExpr();
3906 if (!ExplicitExpr)
3908 if (!ExplicitExpr->isValueDependent())
3910
3911 // By this point, FinishTemplateArgumentDeduction will have been reverted back
3912 // to a regular non-SFINAE template instantiation context, so setup a new
3913 // SFINAE context.
3915 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3917 if (Inst.isInvalid())
3919 Sema::SFINAETrap Trap(S, Info);
3920 const ExplicitSpecifier InstantiatedES =
3921 S.instantiateExplicitSpecifier(SubstArgs, ES);
3922 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3923 Specialization->setInvalidDecl(true);
3925 }
3926 SetExplicitSpecifier(Specialization, InstantiatedES);
3928}
3929
3933 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3935 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3936 bool PartialOverloading, bool PartialOrdering,
3937 bool ForOverloadSetAddressResolution,
3938 llvm::function_ref<bool(bool)> CheckNonDependent) {
3939 // Enter a new template instantiation context while we instantiate the
3940 // actual function declaration.
3941 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3943 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3945 if (Inst.isInvalid())
3947
3948 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3949
3950 // C++ [temp.deduct.type]p2:
3951 // [...] or if any template argument remains neither deduced nor
3952 // explicitly specified, template argument deduction fails.
3953 bool IsIncomplete = false;
3956 *this, FunctionTemplate, FunctionTemplate->getTemplateParameters(),
3957 /*IsDeduced=*/true, Deduced, Info, CTAI, CurrentInstantiationScope,
3958 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
3960 return Result;
3961
3962 // Form the template argument list from the deduced template arguments.
3963 TemplateArgumentList *SugaredDeducedArgumentList =
3965 TemplateArgumentList *CanonicalDeducedArgumentList =
3967 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3968
3969 // Substitute the deduced template arguments into the function template
3970 // declaration to produce the function template specialization.
3971 DeclContext *Owner = FunctionTemplate->getDeclContext();
3972 if (FunctionTemplate->getFriendObjectKind())
3973 Owner = FunctionTemplate->getLexicalDeclContext();
3974 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3975
3976 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/true))
3978
3979 // C++20 [temp.deduct.general]p5: [CWG2369]
3980 // If the function template has associated constraints, those constraints
3981 // are checked for satisfaction. If the constraints are not satisfied, type
3982 // deduction fails.
3983 //
3984 // FIXME: We haven't implemented CWG2369 for lambdas yet, because we need
3985 // to figure out how to instantiate lambda captures to the scope without
3986 // first instantiating the lambda.
3987 bool IsLambda = isLambdaCallOperator(FD) || isLambdaConversionOperator(FD);
3988 if (!IsLambda && !IsIncomplete) {
3990 Info.getLocation(),
3991 FunctionTemplate->getCanonicalDecl()->getTemplatedDecl(),
3997 }
3998 }
3999 // C++ [temp.deduct.call]p10: [CWG1391]
4000 // If deduction succeeds for all parameters that contain
4001 // template-parameters that participate in template argument deduction,
4002 // and all template arguments are explicitly specified, deduced, or
4003 // obtained from default template arguments, remaining parameters are then
4004 // compared with the corresponding arguments. For each remaining parameter
4005 // P with a type that was non-dependent before substitution of any
4006 // explicitly-specified template arguments, if the corresponding argument
4007 // A cannot be implicitly converted to P, deduction fails.
4008 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/false))
4010
4012 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
4013 /*Final=*/false);
4014 Specialization = cast_or_null<FunctionDecl>(
4015 SubstDecl(FD, Owner, SubstArgs));
4016 if (!Specialization || Specialization->isInvalidDecl())
4018
4019 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
4021
4022 // If the template argument list is owned by the function template
4023 // specialization, release it.
4024 if (Specialization->getTemplateSpecializationArgs() ==
4025 CanonicalDeducedArgumentList)
4026 Info.takeCanonical();
4027
4028 // C++2a [temp.deduct]p5
4029 // [...] When all template arguments have been deduced [...] all uses of
4030 // template parameters [...] are replaced with the corresponding deduced
4031 // or default argument values.
4032 // [...] If the function template has associated constraints
4033 // ([temp.constr.decl]), those constraints are checked for satisfaction
4034 // ([temp.constr.constr]). If the constraints are not satisfied, type
4035 // deduction fails.
4036 if (IsLambda && !IsIncomplete) {
4044 }
4045 }
4046
4047 // We skipped the instantiation of the explicit-specifier during the
4048 // substitution of `FD` before. So, we try to instantiate it back if
4049 // `Specialization` is either a constructor or a conversion function.
4053 Info, FunctionTemplate,
4054 DeducedArgs)) {
4056 }
4057 }
4058
4059 if (OriginalCallArgs) {
4060 // C++ [temp.deduct.call]p4:
4061 // In general, the deduction process attempts to find template argument
4062 // values that will make the deduced A identical to A (after the type A
4063 // is transformed as described above). [...]
4064 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4065 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4066 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4067
4068 auto ParamIdx = OriginalArg.ArgIdx;
4069 unsigned ExplicitOffset =
4070 (Specialization->hasCXXExplicitFunctionObjectParameter() &&
4071 !ForOverloadSetAddressResolution)
4072 ? 1
4073 : 0;
4074 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4075 // FIXME: This presumably means a pack ended up smaller than we
4076 // expected while deducing. Should this not result in deduction
4077 // failure? Can it even happen?
4078 continue;
4079
4080 QualType DeducedA;
4081 if (!OriginalArg.DecomposedParam) {
4082 // P is one of the function parameters, just look up its substituted
4083 // type.
4084 DeducedA =
4085 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4086 } else {
4087 // P is a decomposed element of a parameter corresponding to a
4088 // braced-init-list argument. Substitute back into P to find the
4089 // deduced A.
4090 QualType &CacheEntry =
4091 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4092 if (CacheEntry.isNull()) {
4094 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4095 ParamIdx));
4096 CacheEntry =
4097 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4098 Specialization->getTypeSpecStartLoc(),
4099 Specialization->getDeclName());
4100 }
4101 DeducedA = CacheEntry;
4102 }
4103
4104 if (auto TDK =
4105 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4107 return TDK;
4108 }
4109 }
4110
4111 // If we suppressed any diagnostics while performing template argument
4112 // deduction, and if we haven't already instantiated this declaration,
4113 // keep track of these diagnostics. They'll be emitted if this specialization
4114 // is actually used.
4115 if (Info.diag_begin() != Info.diag_end()) {
4116 auto [Pos, Inserted] =
4117 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4118 if (Inserted)
4119 Pos->second.append(Info.diag_begin(), Info.diag_end());
4120 }
4121
4123}
4124
4128 if (!FailedTSC)
4129 return;
4130
4131 Decl *TemplatedDecl = TD->getTemplatedDecl();
4132 for (TemplateSpecCandidate &Candidate : *FailedTSC) {
4133 if (Candidate.Specialization &&
4134 declaresSameEntity(Candidate.Specialization, TemplatedDecl))
4135 return;
4136 }
4137
4138 FailedTSC->addCandidate().set(
4139 DeclAccessPair::make(TD, AS_public), TemplatedDecl,
4141}
4142
4144 FriendTemplateDecl *FTD, ClassTemplateDecl *PatternCTD,
4146 ArrayRef<TemplateArgument> PatternArgs,
4147 ArrayRef<TemplateArgument> CandidateArgs, SourceLocation Loc,
4148 TemplateSpecCandidateSet *FailedTSC,
4149 MultiLevelTemplateArgumentList &DeducedArgs) {
4152 ContextRAII SavedContext(*this, FTD->getDeclContext());
4153 LocalInstantiationScope InstantiationScope(*this);
4154 InstantiatingTemplate Inst(*this, Loc, FTD);
4155 if (Inst.isInvalid()) {
4156 TemplateDeductionInfo Info(Loc);
4158 *this, PatternCTD, Info, TemplateDeductionResult::InstantiationDepth,
4159 FailedTSC);
4160 return false;
4161 }
4162
4164 DeducedArgLists.reserve(TPLs.size());
4165 for (TemplateParameterList *Params : TPLs) {
4166 TemplateDeductionInfo Info(Loc, Params->getDepth());
4167 SFINAETrap Trap(*this, Info);
4170 Params, PatternArgs, CandidateArgs, Info, Deduced,
4171 /*NumberOfArgumentsMustMatch=*/false);
4172
4174 bool IsIncomplete = false;
4177 *this, PatternCTD, Params, /*IsDeduced=*/false, Deduced, Info, CTAI,
4178 &InstantiationScope, /*NumAlreadyConverted=*/0, &IsIncomplete);
4179 if (Result == TemplateDeductionResult::Success && IsIncomplete) {
4180 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
4181 if (!Deduced[I].isNull())
4182 continue;
4183 Info.Param = makeTemplateParameter(Params->getParam(I));
4184 break;
4185 }
4186 Info.reset(
4190 }
4194 AddFriendTemplateDeductionCandidate(*this, PatternCTD, Info, Result,
4195 FailedTSC);
4196 return false;
4197 }
4198
4199 DeducedArgLists.push_back(
4201 }
4202
4203 for (TemplateArgumentList *Args : llvm::reverse(DeducedArgLists))
4204 DeducedArgs.addOuterTemplateArguments(FTD, Args->asArray(),
4205 /*Final=*/true);
4206 if (!TPLs.empty())
4207 DeducedArgs.addOuterRetainedLevels(TPLs.front()->getDepth());
4208
4209 if (DeducedArgs.isAnyArgInstantiationDependent() &&
4210 llvm::any_of(TPLs, [](TemplateParameterList *Params) {
4211 return Params->hasAssociatedConstraints();
4212 }))
4213 return false;
4214
4216 PatternArgLocs.reserve(PatternArgs.size());
4217 for (const TemplateArgument &Arg : PatternArgs)
4218 PatternArgLocs.push_back(
4220
4221 {
4222 TemplateDeductionInfo Info(Loc);
4223 SFINAETrap Trap(*this, Info);
4225 *this, CandidateCTD, PatternArgLocs, CandidateArgs, DeducedArgs, Info);
4229 AddFriendTemplateDeductionCandidate(*this, PatternCTD, Info, Result,
4230 FailedTSC);
4231 return false;
4232 }
4233 }
4234
4235 for (TemplateParameterList *Params : TPLs) {
4237 Params->getAssociatedConstraints(Constraints);
4238 if (Constraints.empty())
4239 continue;
4240
4241 TemplateDeductionInfo Info(Loc, Params->getDepth());
4242 SFINAETrap Trap(*this, Info);
4243 if (CheckConstraintSatisfaction(PatternCTD, Constraints, DeducedArgs,
4244 SourceRange(Loc),
4247 Trap.hasErrorOccurred()) {
4248 SmallVector<TemplateArgument, 4> CanonicalCandidateArgs;
4249 CanonicalCandidateArgs.reserve(CandidateArgs.size());
4250 for (const TemplateArgument &Arg : CandidateArgs)
4251 CanonicalCandidateArgs.push_back(
4252 Context.getCanonicalTemplateArgument(Arg));
4253 Info.reset(
4255 TemplateArgumentList::CreateCopy(Context, CanonicalCandidateArgs));
4257 *this, PatternCTD, Info,
4259 return false;
4260 }
4261 }
4262
4263 return true;
4264}
4265
4266/// Gets the type of a function for template-argument-deducton
4267/// purposes when it's considered as part of an overload set.
4269 FunctionDecl *Fn) {
4270 // We may need to deduce the return type of the function now.
4271 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4272 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4273 return {};
4274
4275 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4276 if (Method->isImplicitObjectMemberFunction()) {
4277 // An instance method that's referenced in a form that doesn't
4278 // look like a member pointer is just invalid.
4279 if (!R.HasFormOfMemberPointer)
4280 return {};
4281
4283 Fn->getType(), /*Qualifier=*/std::nullopt, Method->getParent());
4284 }
4285
4286 if (!R.IsAddressOfOperand) return Fn->getType();
4287 return S.Context.getPointerType(Fn->getType());
4288}
4289
4290/// Apply the deduction rules for overload sets.
4291///
4292/// \return the null type if this argument should be treated as an
4293/// undeduced context
4294static QualType
4296 Expr *Arg, QualType ParamType,
4297 bool ParamWasReference,
4298 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4299
4301
4302 OverloadExpr *Ovl = R.Expression;
4303
4304 // C++0x [temp.deduct.call]p4
4305 unsigned TDF = 0;
4306 if (ParamWasReference)
4308 if (R.IsAddressOfOperand)
4309 TDF |= TDF_IgnoreQualifiers;
4310
4311 // C++0x [temp.deduct.call]p6:
4312 // When P is a function type, pointer to function type, or pointer
4313 // to member function type:
4314
4315 if (!ParamType->isFunctionType() &&
4316 !ParamType->isFunctionPointerType() &&
4317 !ParamType->isMemberFunctionPointerType()) {
4318 if (Ovl->hasExplicitTemplateArgs()) {
4319 // But we can still look for an explicit specialization.
4320 if (FunctionDecl *ExplicitSpec =
4322 Ovl, /*Complain=*/false,
4323 /*Found=*/nullptr, FailedTSC,
4324 /*ForTypeDeduction=*/true))
4325 return GetTypeOfFunction(S, R, ExplicitSpec);
4326 }
4327
4328 DeclAccessPair DAP;
4329 if (FunctionDecl *Viable =
4331 return GetTypeOfFunction(S, R, Viable);
4332
4333 return {};
4334 }
4335
4336 // Gather the explicit template arguments, if any.
4337 TemplateArgumentListInfo ExplicitTemplateArgs;
4338 if (Ovl->hasExplicitTemplateArgs())
4339 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4341 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4342 E = Ovl->decls_end(); I != E; ++I) {
4343 NamedDecl *D = (*I)->getUnderlyingDecl();
4344
4345 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4346 // - If the argument is an overload set containing one or more
4347 // function templates, the parameter is treated as a
4348 // non-deduced context.
4349 if (!Ovl->hasExplicitTemplateArgs())
4350 return {};
4351
4352 // Otherwise, see if we can resolve a function type
4353 FunctionDecl *Specialization = nullptr;
4354 TemplateDeductionInfo Info(Ovl->getNameLoc());
4355 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4358 continue;
4359
4360 D = Specialization;
4361 }
4362
4364 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4365 if (ArgType.isNull()) continue;
4366
4367 // Function-to-pointer conversion.
4368 if (!ParamWasReference && ParamType->isPointerType() &&
4369 ArgType->isFunctionType())
4370 ArgType = S.Context.getPointerType(ArgType);
4371
4372 // - If the argument is an overload set (not containing function
4373 // templates), trial argument deduction is attempted using each
4374 // of the members of the set. If deduction succeeds for only one
4375 // of the overload set members, that member is used as the
4376 // argument value for the deduction. If deduction succeeds for
4377 // more than one member of the overload set the parameter is
4378 // treated as a non-deduced context.
4379
4380 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4381 // Type deduction is done independently for each P/A pair, and
4382 // the deduced template argument values are then combined.
4383 // So we do not reject deductions which were made elsewhere.
4385 Deduced(TemplateParams->size());
4386 TemplateDeductionInfo Info(Ovl->getNameLoc());
4388 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4389 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4390 /*HasDeducedAnyParam=*/nullptr);
4392 continue;
4393 // C++ [temp.deduct.call]p6:
4394 // [...] If all successful deductions yield the same deduced A, that
4395 // deduced A is the result of deduction; otherwise, the parameter is
4396 // treated as a non-deduced context. [...]
4397 if (!Match.isNull() && !S.isSameOrCompatibleFunctionType(Match, ArgType))
4398 return {};
4399 Match = ArgType;
4400 }
4401
4402 return Match;
4403}
4404
4405/// Perform the adjustments to the parameter and argument types
4406/// described in C++ [temp.deduct.call].
4407///
4408/// \returns true if the caller should not attempt to perform any template
4409/// argument deduction based on this P/A pair because the argument is an
4410/// overloaded function set that could not be resolved.
4412 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4413 QualType &ParamType, QualType &ArgType,
4414 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4415 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4416 // C++0x [temp.deduct.call]p3:
4417 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4418 // are ignored for type deduction.
4419 if (ParamType.hasQualifiers())
4420 ParamType = ParamType.getUnqualifiedType();
4421
4422 // [...] If P is a reference type, the type referred to by P is
4423 // used for type deduction.
4424 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4425 if (ParamRefType)
4426 ParamType = ParamRefType->getPointeeType();
4427
4428 // Overload sets usually make this parameter an undeduced context,
4429 // but there are sometimes special circumstances. Typically
4430 // involving a template-id-expr.
4431 if (ArgType == S.Context.OverloadTy) {
4432 assert(Arg && "expected a non-null arg expression");
4433 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4434 ParamRefType != nullptr, FailedTSC);
4435 if (ArgType.isNull())
4436 return true;
4437 }
4438
4439 if (ParamRefType) {
4440 // If the argument has incomplete array type, try to complete its type.
4441 if (ArgType->isIncompleteArrayType()) {
4442 assert(Arg && "expected a non-null arg expression");
4443 ArgType = S.getCompletedType(Arg);
4444 }
4445
4446 // C++1z [temp.deduct.call]p3:
4447 // If P is a forwarding reference and the argument is an lvalue, the type
4448 // "lvalue reference to A" is used in place of A for type deduction.
4449 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4450 ArgClassification.isLValue()) {
4451 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4452 ArgType = S.Context.getAddrSpaceQualType(
4454 ArgType = S.Context.getLValueReferenceType(ArgType);
4455 }
4456 } else {
4457 // C++ [temp.deduct.call]p2:
4458 // If P is not a reference type:
4459 // - If A is an array type, the pointer type produced by the
4460 // array-to-pointer standard conversion (4.2) is used in place of
4461 // A for type deduction; otherwise,
4462 // - If A is a function type, the pointer type produced by the
4463 // function-to-pointer standard conversion (4.3) is used in place
4464 // of A for type deduction; otherwise,
4465 if (ArgType->canDecayToPointerType())
4466 ArgType = S.Context.getDecayedType(ArgType);
4467 else {
4468 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4469 // type are ignored for type deduction.
4470 ArgType = ArgType.getUnqualifiedType();
4471 }
4472 }
4473
4474 // C++0x [temp.deduct.call]p4:
4475 // In general, the deduction process attempts to find template argument
4476 // values that will make the deduced A identical to A (after the type A
4477 // is transformed as described above). [...]
4479
4480 // - If the original P is a reference type, the deduced A (i.e., the
4481 // type referred to by the reference) can be more cv-qualified than
4482 // the transformed A.
4483 if (ParamRefType)
4485 // - The transformed A can be another pointer or pointer to member
4486 // type that can be converted to the deduced A via a qualification
4487 // conversion (4.4).
4488 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4489 ArgType->isObjCObjectPointerType())
4490 TDF |= TDF_IgnoreQualifiers;
4491 // - If P is a class and P has the form simple-template-id, then the
4492 // transformed A can be a derived class of the deduced A. Likewise,
4493 // if P is a pointer to a class of the form simple-template-id, the
4494 // transformed A can be a pointer to a derived class pointed to by
4495 // the deduced A.
4496 if (isSimpleTemplateIdType(ParamType) ||
4497 (ParamType->getAs<PointerType>() &&
4499 ParamType->castAs<PointerType>()->getPointeeType())))
4500 TDF |= TDF_DerivedClass;
4501
4502 return false;
4503}
4504
4505static bool
4507 QualType T);
4508
4510 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4511 QualType ParamType, QualType ArgType,
4512 Expr::Classification ArgClassification, Expr *Arg,
4516 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4517 TemplateSpecCandidateSet *FailedTSC = nullptr);
4518
4519/// Attempt template argument deduction from an initializer list
4520/// deemed to be an argument in a function call.
4522 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4525 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4526 unsigned TDF) {
4527 // C++ [temp.deduct.call]p1: (CWG 1591)
4528 // If removing references and cv-qualifiers from P gives
4529 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4530 // a non-empty initializer list, then deduction is performed instead for
4531 // each element of the initializer list, taking P0 as a function template
4532 // parameter type and the initializer element as its argument
4533 //
4534 // We've already removed references and cv-qualifiers here.
4535 if (!ILE->getNumInits())
4537
4538 QualType ElTy;
4539 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4540 if (ArrTy)
4541 ElTy = ArrTy->getElementType();
4542 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4543 // Otherwise, an initializer list argument causes the parameter to be
4544 // considered a non-deduced context
4546 }
4547
4548 // Resolving a core issue: a braced-init-list containing any designators is
4549 // a non-deduced context.
4550 for (Expr *E : ILE->inits())
4553
4554 // Deduction only needs to be done for dependent types.
4555 if (ElTy->isDependentType()) {
4556 for (Expr *E : ILE->inits()) {
4558 S, TemplateParams, 0, ElTy, E->getType(),
4559 E->Classify(S.getASTContext()), E, Info, Deduced,
4560 OriginalCallArgs, true, ArgIdx, TDF);
4562 return Result;
4563 }
4564 }
4565
4566 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4567 // from the length of the initializer list.
4568 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4569 // Determine the array bound is something we can deduce.
4571 Info, DependentArrTy->getSizeExpr())) {
4572 // We can perform template argument deduction for the given non-type
4573 // template parameter.
4574 // C++ [temp.deduct.type]p13:
4575 // The type of N in the type T[N] is std::size_t.
4577 llvm::APInt Size(S.Context.getIntWidth(T),
4580 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4581 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4582 /*HasDeducedAnyParam=*/nullptr);
4584 return Result;
4585 }
4586 }
4587
4589}
4590
4591/// Perform template argument deduction per [temp.deduct.call] for a
4592/// single parameter / argument pair.
4594 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4595 QualType ParamType, QualType ArgType,
4596 Expr::Classification ArgClassification, Expr *Arg,
4600 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4601 TemplateSpecCandidateSet *FailedTSC) {
4602
4603 QualType OrigParamType = ParamType;
4604
4605 // If P is a reference type [...]
4606 // If P is a cv-qualified type [...]
4608 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4609 ArgClassification, Arg, TDF, FailedTSC))
4611
4612 // If [...] the argument is a non-empty initializer list [...]
4613 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4614 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4615 Deduced, OriginalCallArgs, ArgIdx, TDF);
4616
4617 // [...] the deduction process attempts to find template argument values
4618 // that will make the deduced A identical to A
4619 //
4620 // Keep track of the argument type and corresponding parameter index,
4621 // so we can check for compatibility between the deduced A and A.
4622 if (Arg)
4623 OriginalCallArgs.push_back(
4624 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4626 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4627 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4628 /*HasDeducedAnyParam=*/nullptr);
4629}
4630
4633 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4635 bool PartialOverloading, bool AggregateDeductionCandidate,
4636 bool PartialOrdering, QualType ObjectType,
4637 Expr::Classification ObjectClassification,
4638 bool ForOverloadSetAddressResolution,
4639 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent) {
4640 if (FunctionTemplate->isInvalidDecl())
4642
4643 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4644 unsigned NumParams = Function->getNumParams();
4645 bool HasExplicitObject = false;
4646 int ExplicitObjectOffset = 0;
4647
4648 // [C++26] [over.call.func]p3
4649 // If the primary-expression is the address of an overload set,
4650 // the argument list is the same as the expression-list in the call.
4651 // Otherwise, the argument list is the expression-list in the call augmented
4652 // by the addition of an implied object argument as in a qualified function
4653 // call.
4654 if (!ForOverloadSetAddressResolution &&
4655 Function->hasCXXExplicitFunctionObjectParameter()) {
4656 HasExplicitObject = true;
4657 ExplicitObjectOffset = 1;
4658 }
4659
4660 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4661
4662 // C++ [temp.deduct.call]p1:
4663 // Template argument deduction is done by comparing each function template
4664 // parameter type (call it P) with the type of the corresponding argument
4665 // of the call (call it A) as described below.
4666 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4667 !PartialOverloading)
4669 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4670 PartialOverloading)) {
4671 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4672 if (Proto->isTemplateVariadic())
4673 /* Do nothing */;
4674 else if (!Proto->isVariadic())
4676 }
4677
4680 Sema::SFINAETrap Trap(*this, Info);
4681
4682 // The types of the parameters from which we will perform template argument
4683 // deduction.
4684 LocalInstantiationScope InstScope(*this);
4685 TemplateParameterList *TemplateParams
4686 = FunctionTemplate->getTemplateParameters();
4688 SmallVector<QualType, 8> ParamTypes;
4689 unsigned NumExplicitlySpecified = 0;
4690 if (ExplicitTemplateArgs) {
4693 Result = SubstituteExplicitTemplateArguments(
4694 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4695 Info);
4696 });
4698 return Result;
4699 if (Trap.hasErrorOccurred())
4701
4702 NumExplicitlySpecified = Deduced.size();
4703 } else {
4704 // Just fill in the parameter types from the function declaration.
4705 for (unsigned I = 0; I != NumParams; ++I)
4706 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4707 }
4708
4709 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4710
4711 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4712 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4713 bool ExplicitObjectArgument) {
4714 // C++ [demp.deduct.call]p1: (DR1391)
4715 // Template argument deduction is done by comparing each function template
4716 // parameter that contains template-parameters that participate in
4717 // template argument deduction ...
4718 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4720
4721 if (ExplicitObjectArgument) {
4722 // ... with the type of the corresponding argument
4724 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4725 ObjectClassification,
4726 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4727 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4728 }
4729
4730 // ... with the type of the corresponding argument
4732 *this, TemplateParams, FirstInnerIndex, ParamType,
4733 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4734 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4735 ArgIdx, /*TDF*/ 0);
4736 };
4737
4738 // Deduce template arguments from the function parameters.
4739 Deduced.resize(TemplateParams->size());
4740 SmallVector<QualType, 8> ParamTypesForArgChecking;
4741 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4742 ParamIdx != NumParamTypes; ++ParamIdx) {
4743 QualType ParamType = ParamTypes[ParamIdx];
4744
4745 const PackExpansionType *ParamExpansion =
4746 dyn_cast<PackExpansionType>(ParamType);
4747 if (!ParamExpansion) {
4748 // Simple case: matching a function parameter to a function argument.
4749 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4750 break;
4751
4752 ParamTypesForArgChecking.push_back(ParamType);
4753
4754 if (ParamIdx == 0 && HasExplicitObject) {
4755 if (ObjectType.isNull())
4757
4758 if (auto Result = DeduceCallArgument(ParamType, 0,
4759 /*ExplicitObjectArgument=*/true);
4761 return Result;
4762 continue;
4763 }
4764
4765 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4766 /*ExplicitObjectArgument=*/false);
4768 return Result;
4769
4770 continue;
4771 }
4772
4773 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4774
4775 QualType ParamPattern = ParamExpansion->getPattern();
4776 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4777 ParamPattern,
4778 AggregateDeductionCandidate && IsTrailingPack);
4779
4780 // C++0x [temp.deduct.call]p1:
4781 // For a function parameter pack that occurs at the end of the
4782 // parameter-declaration-list, the type A of each remaining argument of
4783 // the call is compared with the type P of the declarator-id of the
4784 // function parameter pack. Each comparison deduces template arguments
4785 // for subsequent positions in the template parameter packs expanded by
4786 // the function parameter pack. When a function parameter pack appears
4787 // in a non-deduced context [not at the end of the list], the type of
4788 // that parameter pack is never deduced.
4789 //
4790 // FIXME: The above rule allows the size of the parameter pack to change
4791 // after we skip it (in the non-deduced case). That makes no sense, so
4792 // we instead notionally deduce the pack against N arguments, where N is
4793 // the length of the explicitly-specified pack if it's expanded by the
4794 // parameter pack and 0 otherwise, and we treat each deduction as a
4795 // non-deduced context.
4796 if (IsTrailingPack || PackScope.hasFixedArity()) {
4797 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4798 PackScope.nextPackElement(), ++ArgIdx) {
4799 ParamTypesForArgChecking.push_back(ParamPattern);
4800 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4801 /*ExplicitObjectArgument=*/false);
4803 return Result;
4804 }
4805 } else {
4806 // If the parameter type contains an explicitly-specified pack that we
4807 // could not expand, skip the number of parameters notionally created
4808 // by the expansion.
4809 UnsignedOrNone NumExpansions = ParamExpansion->getNumExpansions();
4810 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4811 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4812 ++I, ++ArgIdx) {
4813 ParamTypesForArgChecking.push_back(ParamPattern);
4814 // FIXME: Should we add OriginalCallArgs for these? What if the
4815 // corresponding argument is a list?
4816 PackScope.nextPackElement();
4817 }
4818 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4819 PackScope.isDeducedFromEarlierParameter()) {
4820 // [temp.deduct.general#3]
4821 // When all template arguments have been deduced
4822 // or obtained from default template arguments, all uses of template
4823 // parameters in the template parameter list of the template are
4824 // replaced with the corresponding deduced or default argument values
4825 //
4826 // If we have a trailing parameter pack, that has been deduced
4827 // previously we substitute the pack here in a similar fashion as
4828 // above with the trailing parameter packs. The main difference here is
4829 // that, in this case we are not processing all of the remaining
4830 // arguments. We are only process as many arguments as we have in
4831 // the already deduced parameter.
4832 UnsignedOrNone ArgPosAfterSubstitution =
4833 PackScope.getSavedPackSizeIfAllEqual();
4834 if (!ArgPosAfterSubstitution)
4835 continue;
4836
4837 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4838 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4839 ParamTypesForArgChecking.push_back(ParamPattern);
4840 if (auto Result =
4841 DeduceCallArgument(ParamPattern, ArgIdx,
4842 /*ExplicitObjectArgument=*/false);
4844 return Result;
4845
4846 PackScope.nextPackElement();
4847 }
4848 }
4849 }
4850
4851 // Build argument packs for each of the parameter packs expanded by this
4852 // pack expansion.
4853 if (auto Result = PackScope.finish();
4855 return Result;
4856 }
4857
4858 // Capture the context in which the function call is made. This is the context
4859 // that is needed when the accessibility of template arguments is checked.
4860 DeclContext *CallingCtx = CurContext;
4861
4864 Result = FinishTemplateArgumentDeduction(
4865 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4866 &OriginalCallArgs, PartialOverloading, PartialOrdering,
4867 ForOverloadSetAddressResolution,
4868 [&, CallingCtx](bool OnlyInitializeNonUserDefinedConversions) {
4869 ContextRAII SavedContext(*this, CallingCtx);
4870 return CheckNonDependent(ParamTypesForArgChecking,
4871 OnlyInitializeNonUserDefinedConversions);
4872 });
4873 });
4874 if (Trap.hasErrorOccurred()) {
4875 if (Specialization)
4876 Specialization->setInvalidDecl(true);
4878 }
4879 return Result;
4880}
4881
4884 bool AdjustExceptionSpec) {
4885 if (ArgFunctionType.isNull())
4886 return ArgFunctionType;
4887
4888 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4889 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4890 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4891 bool Rebuild = false;
4892
4893 CallingConv CC = FunctionTypeP->getCallConv();
4894 if (EPI.ExtInfo.getCC() != CC) {
4895 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4896 Rebuild = true;
4897 }
4898
4899 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4900 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4901 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4902 Rebuild = true;
4903 }
4904
4905 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4906 ArgFunctionTypeP->hasExceptionSpec())) {
4907 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4908 Rebuild = true;
4909 }
4910
4911 if (!Rebuild)
4912 return ArgFunctionType;
4913
4914 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4915 ArgFunctionTypeP->getParamTypes(), EPI);
4916}
4917
4920 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4922 bool IsAddressOfFunction) {
4923 if (FunctionTemplate->isInvalidDecl())
4925
4926 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4927 TemplateParameterList *TemplateParams
4928 = FunctionTemplate->getTemplateParameters();
4929 QualType FunctionType = Function->getType();
4930
4933
4934 // Unevaluated SFINAE context.
4937 SFINAETrap Trap(*this, Info);
4938
4939 // Substitute any explicit template arguments.
4940 LocalInstantiationScope InstScope(*this);
4942 unsigned NumExplicitlySpecified = 0;
4943 SmallVector<QualType, 4> ParamTypes;
4944 if (ExplicitTemplateArgs) {
4947 Result = SubstituteExplicitTemplateArguments(
4948 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4949 &FunctionType, Info);
4950 });
4952 return Result;
4953 if (Trap.hasErrorOccurred())
4955
4956 NumExplicitlySpecified = Deduced.size();
4957 }
4958
4959 // When taking the address of a function, we require convertibility of
4960 // the resulting function type. Otherwise, we allow arbitrary mismatches
4961 // of calling convention and noreturn.
4962 if (!IsAddressOfFunction)
4963 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4964 /*AdjustExceptionSpec*/false);
4965
4966 Deduced.resize(TemplateParams->size());
4967
4968 // If the function has a deduced return type, substitute it for a dependent
4969 // type so that we treat it as a non-deduced context in what follows.
4970 bool HasDeducedReturnType = false;
4971 if (getLangOpts().CPlusPlus14 &&
4972 Function->getReturnType()->getContainedAutoType()) {
4974 HasDeducedReturnType = true;
4975 }
4976
4977 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4978 unsigned TDF =
4980 // Deduce template arguments from the function type.
4982 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4983 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4984 /*HasDeducedAnyParam=*/nullptr);
4986 return Result;
4987 // Substituting the function type can instantiate the trailing return type,
4988 // so handle the same immediate-context substitution failure here.
4989 if (Trap.hasErrorOccurred())
4991 }
4992
4995 Result = FinishTemplateArgumentDeduction(
4996 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4997 /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false,
4998 /*PartialOrdering=*/true, IsAddressOfFunction);
4999 });
5000 // Taking the address of a function template forms its function type, and
5001 // substituting into that type can require instantiating a trailing return
5002 // type whose expression selects a deleted function. That is a deduction
5003 // failure, not a hard error:
5004 //
5005 // C++ [temp.deduct.funcaddr]p1:
5006 // [...] If there is a target, the function template's function type and
5007 // the target type are used as the types of P and A, and the deduction is
5008 // done as described in [temp.deduct.type].
5009 //
5010 // C++ [temp.deduct.general]p7:
5011 // [...] The substitution occurs in all types and expressions that are
5012 // used in the deduction substitution loci. The expressions include [...]
5013 // general expressions (i.e., non-constant expressions) inside sizeof,
5014 // decltype, and other contexts that allow non-constant expressions. [...]
5015 //
5016 // C++ [dcl.fct.def.delete]p2:
5017 // A construct that designates a deleted function implicitly or
5018 // explicitly, other than to declare it [...], is ill-formed.
5019 // [Note: [...] It applies even for references in expressions that are not
5020 // potentially evaluated. - end note]
5021 //
5022 // C++ [temp.deduct.general]p8:
5023 // If a substitution results in an invalid type or expression, type
5024 // deduction fails. [...] Invalid types and expressions can result in a
5025 // deduction failure only in the immediate context of the deduction
5026 // substitution loci. [...]
5027 //
5028 // This substitution is in that immediate context, so treat diagnostics
5029 // recorded by the SFINAE trap as deduction failure instead of replaying
5030 // them as hard errors.
5031 if (Trap.hasErrorOccurred()) {
5032 if (Specialization)
5033 Specialization->setInvalidDecl(true);
5035 }
5037 return Result;
5038
5039 // If the function has a deduced return type, deduce it now, so we can check
5040 // that the deduced function type matches the requested type.
5041 if (HasDeducedReturnType && IsAddressOfFunction &&
5042 Specialization->getReturnType()->isUndeducedType() &&
5045
5046 // [C++26][expr.const]/p17
5047 // An expression or conversion is immediate-escalating if it is not initially
5048 // in an immediate function context and it is [...]
5049 // a potentially-evaluated id-expression that denotes an immediate function.
5050 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
5051 Specialization->isImmediateEscalating() && PotentiallyEvaluated &&
5053 Info.getLocation()))
5055
5056 // Adjust the exception specification of the argument to match the
5057 // substituted and resolved type we just formed. (Calling convention and
5058 // noreturn can't be dependent, so we don't actually need this for them
5059 // right now.)
5060 QualType SpecializationType = Specialization->getType();
5061 if (!IsAddressOfFunction) {
5062 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
5063 /*AdjustExceptionSpec*/true);
5064
5065 // Revert placeholder types in the return type back to undeduced types so
5066 // that the comparison below compares the declared return types.
5067 if (HasDeducedReturnType) {
5068 SpecializationType = SubstAutoType(SpecializationType, QualType());
5069 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
5070 }
5071 }
5072
5073 // If the requested function type does not match the actual type of the
5074 // specialization with respect to arguments of compatible pointer to function
5075 // types, template argument deduction fails.
5076 if (!ArgFunctionType.isNull()) {
5077 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
5078 SpecializationType, ArgFunctionType)
5079 : !Context.hasSameFunctionTypeIgnoringExceptionSpec(
5080 SpecializationType, ArgFunctionType)) {
5081 Info.FirstArg = TemplateArgument(SpecializationType);
5082 Info.SecondArg = TemplateArgument(ArgFunctionType);
5084 }
5085 }
5086
5088}
5089
5091 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
5092 Expr::Classification ObjectClassification, QualType A,
5094 if (ConversionTemplate->isInvalidDecl())
5096
5097 CXXConversionDecl *ConversionGeneric
5098 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
5099
5100 QualType P = ConversionGeneric->getConversionType();
5101 bool IsReferenceP = P->isReferenceType();
5102 bool IsReferenceA = A->isReferenceType();
5103
5104 // C++0x [temp.deduct.conv]p2:
5105 // If P is a reference type, the type referred to by P is used for
5106 // type deduction.
5107 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
5108 P = PRef->getPointeeType();
5109
5110 // C++0x [temp.deduct.conv]p4:
5111 // [...] If A is a reference type, the type referred to by A is used
5112 // for type deduction.
5113 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
5114 A = ARef->getPointeeType();
5115 // We work around a defect in the standard here: cv-qualifiers are also
5116 // removed from P and A in this case, unless P was a reference type. This
5117 // seems to mostly match what other compilers are doing.
5118 if (!IsReferenceP) {
5119 A = A.getUnqualifiedType();
5120 P = P.getUnqualifiedType();
5121 }
5122
5123 // C++ [temp.deduct.conv]p3:
5124 //
5125 // If A is not a reference type:
5126 } else {
5127 assert(!A->isReferenceType() && "Reference types were handled above");
5128
5129 // - If P is an array type, the pointer type produced by the
5130 // array-to-pointer standard conversion (4.2) is used in place
5131 // of P for type deduction; otherwise,
5132 if (P->isArrayType())
5133 P = Context.getArrayDecayedType(P);
5134 // - If P is a function type, the pointer type produced by the
5135 // function-to-pointer standard conversion (4.3) is used in
5136 // place of P for type deduction; otherwise,
5137 else if (P->isFunctionType())
5138 P = Context.getPointerType(P);
5139 // - If P is a cv-qualified type, the top level cv-qualifiers of
5140 // P's type are ignored for type deduction.
5141 else
5142 P = P.getUnqualifiedType();
5143
5144 // C++0x [temp.deduct.conv]p4:
5145 // If A is a cv-qualified type, the top level cv-qualifiers of A's
5146 // type are ignored for type deduction. If A is a reference type, the type
5147 // referred to by A is used for type deduction.
5148 A = A.getUnqualifiedType();
5149 }
5150
5151 // Unevaluated SFINAE context.
5154 SFINAETrap Trap(*this, Info);
5155
5156 // C++ [temp.deduct.conv]p1:
5157 // Template argument deduction is done by comparing the return
5158 // type of the template conversion function (call it P) with the
5159 // type that is required as the result of the conversion (call it
5160 // A) as described in 14.8.2.4.
5161 TemplateParameterList *TemplateParams
5162 = ConversionTemplate->getTemplateParameters();
5164 Deduced.resize(TemplateParams->size());
5165
5166 // C++0x [temp.deduct.conv]p4:
5167 // In general, the deduction process attempts to find template
5168 // argument values that will make the deduced A identical to
5169 // A. However, there are two cases that allow a difference:
5170 unsigned TDF = 0;
5171 // - If the original A is a reference type, A can be more
5172 // cv-qualified than the deduced A (i.e., the type referred to
5173 // by the reference)
5174 if (IsReferenceA)
5176 // - The deduced A can be another pointer or pointer to member
5177 // type that can be converted to A via a qualification
5178 // conversion.
5179 //
5180 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
5181 // both P and A are pointers or member pointers. In this case, we
5182 // just ignore cv-qualifiers completely).
5183 if ((P->isPointerType() && A->isPointerType()) ||
5185 TDF |= TDF_IgnoreQualifiers;
5186
5188 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
5189 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
5192 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
5193 ParamType, ObjectType, ObjectClassification,
5194 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
5195 /*Decomposed*/ false, 0, /*TDF*/ 0);
5197 return Result;
5198 }
5199
5201 *this, TemplateParams, P, A, Info, Deduced, TDF,
5202 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5203 /*HasDeducedAnyParam=*/nullptr);
5205 return Result;
5206
5207 // Create an Instantiation Scope for finalizing the operator.
5208 LocalInstantiationScope InstScope(*this);
5209 // Finish template argument deduction.
5210 FunctionDecl *ConversionSpecialized = nullptr;
5213 Result = FinishTemplateArgumentDeduction(
5214 ConversionTemplate, Deduced, 0, ConversionSpecialized, Info,
5215 &OriginalCallArgs, /*PartialOverloading=*/false,
5216 /*PartialOrdering=*/false, /*ForOverloadSetAddressResolution*/ false);
5217 });
5218 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
5219 return Result;
5220}
5221
5224 TemplateArgumentListInfo *ExplicitTemplateArgs,
5227 bool IsAddressOfFunction) {
5228 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5229 QualType(), Specialization, Info,
5230 IsAddressOfFunction);
5231}
5232
5233namespace {
5234 struct DependentAuto { bool IsPack; };
5235
5236 /// Substitute the 'auto' specifier or deduced template specialization type
5237 /// specifier within a type for a given replacement type.
5238 class SubstituteDeducedTypeTransform :
5239 public TreeTransform<SubstituteDeducedTypeTransform> {
5240 DeducedKind DK;
5241 QualType Replacement;
5242 bool UseTypeSugar;
5244
5245 public:
5246 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5247 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5248 DK(DA.IsPack ? DeducedKind::DeducedAsPack
5250 UseTypeSugar(true) {}
5251
5252 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5253 bool UseTypeSugar = true)
5254 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5255 DK(Replacement.isNull() ? DeducedKind::Undeduced
5256 : DeducedKind::Deduced),
5257 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {
5258 assert((!Replacement.isNull() || UseTypeSugar) &&
5259 "An undeduced auto type is never type sugar");
5260 }
5261
5262 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5263 assert(isa<TemplateTypeParmType>(Replacement) &&
5264 "unexpected unsugared replacement kind");
5265 QualType Result = Replacement;
5266 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
5267 NewTL.setNameLoc(TL.getNameLoc());
5268 return Result;
5269 }
5270
5271 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5272 // If we're building the type pattern to deduce against, don't wrap the
5273 // substituted type in an AutoType. Certain template deduction rules
5274 // apply only when a template type parameter appears directly (and not if
5275 // the parameter is found through desugaring). For instance:
5276 // auto &&lref = lvalue;
5277 // must transform into "rvalue reference to T" not "rvalue reference to
5278 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5279 //
5280 // FIXME: Is this still necessary?
5281 if (!UseTypeSugar)
5282 return TransformDesugared(TLB, TL);
5283
5284 QualType Result = SemaRef.Context.getAutoType(
5285 DK, Replacement, TL.getTypePtr()->getKeyword(),
5286 TL.getTypePtr()->getTypeConstraintConcept(),
5287 TL.getTypePtr()->getTypeConstraintArguments());
5288 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5289 NewTL.copy(TL);
5290 return Result;
5291 }
5292
5293 QualType TransformDeducedTemplateSpecializationType(
5294 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5295 if (!UseTypeSugar)
5296 return TransformDesugared(TLB, TL);
5297
5299 DK, Replacement, TL.getTypePtr()->getKeyword(),
5300 TL.getTypePtr()->getTemplateName());
5301 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5302 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5303 NewTL.setNameLoc(TL.getNameLoc());
5304 NewTL.setQualifierLoc(TL.getQualifierLoc());
5305 return Result;
5306 }
5307
5308 QualType TransformAtomicType(TypeLocBuilder &TLB, AtomicTypeLoc TL) {
5309 // When building the function parameter for placeholder type deduction
5310 // (Replacement is the invented template parameter), dig through _Atomic
5311 // around an auto placeholder so deduction matches the non-atomic
5312 // argument. The _Atomic wrapper is re-applied by the final substitution
5313 // pass, which uses a concrete Replacement and falls through to the
5314 // default transform.
5315 //
5316 // This handles only the simple case where _Atomic wraps auto directly
5317 // (e.g. _Atomic(auto)), which is what the C standard currently permits.
5318 // If more complex forms such as _Atomic(auto*) are ever allowed, the
5319 // correct fix would be to treat _Atomic as a qualifier inside
5320 // DeduceTemplateArgumentsByTypeMatch instead.
5321 if (isa_and_nonnull<TemplateTypeParmType>(Replacement) &&
5323 return getDerived().TransformType(TLB, TL.getValueLoc());
5324 return inherited::TransformAtomicType(TLB, TL);
5325 }
5326
5327 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5328 // Lambdas never need to be transformed.
5329 return E;
5330 }
5331 bool TransformExceptionSpec(SourceLocation Loc,
5332 FunctionProtoType::ExceptionSpecInfo &ESI,
5333 SmallVectorImpl<QualType> &Exceptions,
5334 bool &Changed) {
5335 if (ESI.Type == EST_Uninstantiated) {
5336 ESI.instantiate();
5337 Changed = true;
5338 }
5339 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5340 }
5341
5342 QualType Apply(TypeLoc TL) {
5343 // Create some scratch storage for the transformed type locations.
5344 // FIXME: We're just going to throw this information away. Don't build it.
5345 TypeLocBuilder TLB;
5346 TLB.reserve(TL.getFullDataSize());
5347 return TransformType(TLB, TL);
5348 }
5349 };
5350
5351} // namespace
5352
5353static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
5355 QualType Deduced) {
5356 ConstraintSatisfaction Satisfaction;
5358 cast<ConceptDecl>(Type.getTypeConstraintConcept().getAsTemplateDecl());
5359 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5360 TypeLoc.getRAngleLoc());
5361 TemplateArgs.addArgument(
5364 Deduced, TypeLoc.getNameLoc())));
5365 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5366 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5367
5369 if (S.CheckTemplateArgumentList(Concept, TypeLoc.getNameLoc(), TemplateArgs,
5370 /*DefaultArgs=*/{},
5371 /*PartialTemplateArgs=*/false, CTAI))
5372 return true;
5374 /*Final=*/true);
5376 Concept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
5377 TypeLoc.getLocalSourceRange(), Satisfaction))
5378 return true;
5379 if (!Satisfaction.IsSatisfied) {
5380 std::string Buf;
5381 llvm::raw_string_ostream OS(Buf);
5382 OS << "'" << Concept->getName();
5383 if (TypeLoc.hasExplicitTemplateArgs()) {
5384 printTemplateArgumentList(OS, Type.getTypeConstraintArguments(),
5386 Type.getTypeConstraintConcept()
5387 .getAsTemplateDecl()
5388 ->getTemplateParameters());
5389 }
5390 OS << "'";
5391 S.Diag(TypeLoc.getConceptNameLoc(),
5392 diag::err_placeholder_constraints_not_satisfied)
5393 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5394 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5395 return true;
5396 }
5397 return false;
5398}
5399
5402 TemplateDeductionInfo &Info, bool DependentDeduction,
5403 bool IgnoreConstraints,
5404 TemplateSpecCandidateSet *FailedTSC) {
5405 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5406 if (Init->containsErrors())
5408
5409 const AutoType *AT = Type.getType()->getContainedAutoType();
5410 assert(AT);
5411
5412 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5413 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5414 if (NonPlaceholder.isInvalid())
5416 Init = NonPlaceholder.get();
5417 }
5418
5419 DependentAuto DependentResult = {
5420 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5421
5422 if (!DependentDeduction &&
5423 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5424 Init->containsUnexpandedParameterPack())) {
5425 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5426 assert(!Result.isNull() && "substituting DependentTy can't fail");
5428 }
5429
5430 auto *InitList = dyn_cast<InitListExpr>(Init);
5431 bool IsArrayType = Type.getType()->isArrayType();
5432 if (!getLangOpts().CPlusPlus && (InitList || IsArrayType)) {
5433 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5434 << (int)AT->getKeyword() << IsArrayType;
5436 }
5437
5438 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5439 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5440 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5441 }
5442
5443 // Deduce type of TemplParam in Func(Init)
5445 Deduced.resize(1);
5446
5447 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5448
5449 QualType DeducedType;
5450 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5451 if (AT->isDecltypeAuto()) {
5452 if (InitList) {
5453 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5455 }
5456
5457 DeducedType = getDecltypeForExpr(Init);
5458 assert(!DeducedType.isNull());
5459 } else {
5460 LocalInstantiationScope InstScope(*this);
5461
5462 // Build template<class TemplParam> void Func(FuncParam);
5463 SourceLocation Loc = Init->getExprLoc();
5465 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5466 nullptr, false, false, false);
5467 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5468 NamedDecl *TemplParamPtr = TemplParam;
5470 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5471
5472 if (InitList) {
5473 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5474 // deduce against that. Such deduction only succeeds if removing
5475 // cv-qualifiers and references results in std::initializer_list<T>.
5476 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5478
5479 SourceRange DeducedFromInitRange;
5480 for (Expr *Init : InitList->inits()) {
5481 // Resolving a core issue: a braced-init-list containing any designators
5482 // is a non-deduced context.
5486 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5487 Init->Classify(getASTContext()), Init, Info, Deduced,
5488 OriginalCallArgs,
5489 /*Decomposed=*/true,
5490 /*ArgIdx=*/0, /*TDF=*/0);
5493 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5494 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5495 << Init->getSourceRange();
5497 }
5498 return TDK;
5499 }
5500
5501 if (DeducedFromInitRange.isInvalid() &&
5502 Deduced[0].getKind() != TemplateArgument::Null)
5503 DeducedFromInitRange = Init->getSourceRange();
5504 }
5505 } else {
5506 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5507 Diag(Loc, diag::err_auto_bitfield);
5509 }
5510 QualType FuncParam =
5511 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5512 assert(!FuncParam.isNull() &&
5513 "substituting template parameter for 'auto' failed");
5515 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5516 Init->Classify(getASTContext()), Init, Info, Deduced,
5517 OriginalCallArgs,
5518 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5520 return TDK;
5521 }
5522
5523 // Could be null if somehow 'auto' appears in a non-deduced context.
5526 DeducedType = Deduced[0].getAsType();
5527
5528 if (InitList) {
5529 DeducedType = BuildStdInitializerList(DeducedType, Loc);
5530 if (DeducedType.isNull())
5532 }
5533 }
5534
5535 if (!Result.isNull()) {
5536 if (!Context.hasSameType(DeducedType, Result)) {
5537 Info.FirstArg = Result;
5538 Info.SecondArg = DeducedType;
5540 }
5541 DeducedType = Context.getCommonSugaredType(Result, DeducedType);
5542 }
5543
5544 if (AT->isConstrained() && !IgnoreConstraints &&
5546 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5548
5549 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5550 if (Result.isNull())
5552
5553 // Check that the deduced argument type is compatible with the original
5554 // argument type per C++ [temp.deduct.call]p4.
5555 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5556 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5557 assert((bool)InitList == OriginalArg.DecomposedParam &&
5558 "decomposed non-init-list in auto deduction?");
5559 if (auto TDK =
5560 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5562 Result = QualType();
5563 return TDK;
5564 }
5565 }
5566
5568}
5569
5571 QualType TypeToReplaceAuto) {
5572 assert(TypeToReplaceAuto != Context.DependentTy);
5573 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5574 .TransformType(TypeWithAuto);
5575}
5576
5578 QualType TypeToReplaceAuto) {
5579 assert(TypeToReplaceAuto != Context.DependentTy);
5580 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5581 .TransformType(TypeWithAuto);
5582}
5583
5585 return SubstituteDeducedTypeTransform(
5586 *this,
5587 DependentAuto{/*IsPack=*/isa<PackExpansionType>(TypeWithAuto)})
5588 .TransformType(TypeWithAuto);
5589}
5590
5593 return SubstituteDeducedTypeTransform(
5594 *this, DependentAuto{/*IsPack=*/isa<PackExpansionType>(
5595 TypeWithAuto->getType())})
5596 .TransformType(TypeWithAuto);
5597}
5598
5600 QualType TypeToReplaceAuto) {
5601 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5602 /*UseTypeSugar*/ false)
5603 .TransformType(TypeWithAuto);
5604}
5605
5607 QualType TypeToReplaceAuto) {
5608 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5609 /*UseTypeSugar*/ false)
5610 .TransformType(TypeWithAuto);
5611}
5612
5614 const Expr *Init) {
5616 Diag(VDecl->getLocation(),
5617 VDecl->isInitCapture()
5618 ? diag::err_init_capture_deduction_failure_from_init_list
5619 : diag::err_auto_var_deduction_failure_from_init_list)
5620 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5621 else
5622 Diag(VDecl->getLocation(),
5623 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5624 : diag::err_auto_var_deduction_failure)
5625 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5626 << Init->getSourceRange();
5627}
5628
5630 bool Diagnose) {
5631 assert(FD->getReturnType()->isUndeducedType());
5632
5633 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5634 // within the return type from the call operator's type.
5636 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5637 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5638
5639 // For a generic lambda, instantiate the call operator if needed.
5640 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5642 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5643 if (!CallOp || CallOp->isInvalidDecl())
5644 return true;
5645
5646 // We might need to deduce the return type by instantiating the definition
5647 // of the operator() function.
5648 if (CallOp->getReturnType()->isUndeducedType()) {
5650 InstantiateFunctionDefinition(Loc, CallOp);
5651 });
5652 }
5653 }
5654
5655 if (CallOp->isInvalidDecl())
5656 return true;
5657 assert(!CallOp->getReturnType()->isUndeducedType() &&
5658 "failed to deduce lambda return type");
5659
5660 // Build the new return type from scratch.
5661 CallingConv RetTyCC = FD->getReturnType()
5662 ->getPointeeType()
5663 ->castAs<FunctionType>()
5664 ->getCallConv();
5666 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5667 if (FD->getReturnType()->getAs<PointerType>())
5668 RetType = Context.getPointerType(RetType);
5669 else {
5670 assert(FD->getReturnType()->getAs<BlockPointerType>());
5671 RetType = Context.getBlockPointerType(RetType);
5672 }
5673 Context.adjustDeducedFunctionResultType(FD, RetType);
5674 return false;
5675 }
5676
5680 });
5681 }
5682
5683 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5684 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5685 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5686 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5687 }
5688
5689 return StillUndeduced;
5690}
5691
5693 SourceLocation Loc) {
5694 assert(FD->isImmediateEscalating());
5695
5697 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5698 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5699
5700 // For a generic lambda, instantiate the call operator if needed.
5701 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5703 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5704 if (!CallOp || CallOp->isInvalidDecl())
5705 return true;
5707 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5708 }
5709 return CallOp->isInvalidDecl();
5710 }
5711
5714 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5715 }
5716 return false;
5717}
5718
5720 const CXXMethodDecl *Method,
5721 QualType RawType,
5722 bool IsOtherRvr) {
5723 // C++20 [temp.func.order]p3.1, p3.2:
5724 // - The type X(M) is "rvalue reference to cv A" if the optional
5725 // ref-qualifier of M is && or if M has no ref-qualifier and the
5726 // positionally-corresponding parameter of the other transformed template
5727 // has rvalue reference type; if this determination depends recursively
5728 // upon whether X(M) is an rvalue reference type, it is not considered to
5729 // have rvalue reference type.
5730 //
5731 // - Otherwise, X(M) is "lvalue reference to cv A".
5732 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5733 "expected a member function with no explicit object parameter");
5734
5735 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5736 if (Method->getRefQualifier() == RQ_RValue ||
5737 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5738 return Context.getRValueReferenceType(RawType);
5739 return Context.getLValueReferenceType(RawType);
5740}
5741
5744 QualType A, ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5745 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5746 /*Final=*/true);
5748 S,
5749 ArgIdx ? ::getPackIndexForParam(S, FTD, MLTAL, *ArgIdx) : std::nullopt);
5750 bool IsIncompleteSubstitution = false;
5751 // FIXME: A substitution can be incomplete on a non-structural part of the
5752 // type. Use the canonical type for now, until the TemplateInstantiator can
5753 // deal with that.
5754
5755 // Workaround: Implicit deduction guides use InjectedClassNameTypes, whereas
5756 // the explicit guides don't. The substitution doesn't transform these types,
5757 // so let it transform their specializations instead.
5758 bool IsDeductionGuide = isa<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
5759 if (IsDeductionGuide) {
5760 if (auto *Injected = P->getAsCanonical<InjectedClassNameType>())
5761 P = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5762 S.Context);
5763 }
5764 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5765 FTD->getDeclName(), &IsIncompleteSubstitution);
5766 if (InstP.isNull() && !IsIncompleteSubstitution)
5768 if (!CheckConsistency)
5770 if (IsIncompleteSubstitution)
5772
5773 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5774 // This handles just the cases that can appear when partial ordering.
5775 if (auto *PA = dyn_cast<PackExpansionType>(A);
5776 PA && !isa<PackExpansionType>(InstP))
5777 A = PA->getPattern();
5780 if (IsDeductionGuide) {
5781 if (auto *Injected = T1->getAsCanonical<InjectedClassNameType>())
5782 T1 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5783 S.Context);
5784 if (auto *Injected = T2->getAsCanonical<InjectedClassNameType>())
5785 T2 = Injected->getDecl()->getCanonicalTemplateSpecializationType(
5786 S.Context);
5787 }
5788 if (!S.Context.hasSameType(T1, T2))
5791}
5792
5793template <class T>
5795 Sema &S, FunctionTemplateDecl *FTD,
5798 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5799
5800 // C++26 [temp.deduct.type]p2:
5801 // [...] or if any template argument remains neither deduced nor
5802 // explicitly specified, template argument deduction fails.
5803 bool IsIncomplete = false;
5804 Sema::CheckTemplateArgumentInfo CTAI(/*PartialOrdering=*/true);
5806 S, FTD, FTD->getTemplateParameters(), /*IsDeduced=*/true, Deduced,
5807 Info, CTAI,
5808 /*CurrentInstantiationScope=*/nullptr,
5809 /*NumAlreadyConverted=*/0, &IsIncomplete);
5811 return Result;
5812
5813 // Form the template argument list from the deduced template arguments.
5814 TemplateArgumentList *SugaredDeducedArgumentList =
5816 TemplateArgumentList *CanonicalDeducedArgumentList =
5818
5819 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5820
5821 // Substitute the deduced template arguments into the argument
5822 // and verify that the instantiated argument is both valid
5823 // and equivalent to the parameter.
5824 LocalInstantiationScope InstScope(S);
5825 return CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted);
5826}
5827
5828/// Determine whether the function template \p FT1 is at least as
5829/// specialized as \p FT2.
5833 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5834 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5835 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5836 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5837 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5838 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5839
5840 // C++26 [temp.deduct.partial]p3:
5841 // The types used to determine the ordering depend on the context in which
5842 // the partial ordering is done:
5843 // - In the context of a function call, the types used are those function
5844 // parameter types for which the function call has arguments.
5845 // - In the context of a call to a conversion operator, the return types
5846 // of the conversion function templates are used.
5847 // - In other contexts (14.6.6.2) the function template's function type
5848 // is used.
5849
5850 if (TPOC == TPOC_Other) {
5851 // We wouldn't be partial ordering these candidates if these didn't match.
5852 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5853 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5854 Proto1->isVariadic() == Proto2->isVariadic() &&
5855 "shouldn't partial order functions with different qualifiers in a "
5856 "context where the function type is used");
5857
5858 assert(Args1.empty() && Args2.empty() &&
5859 "Only call context should have arguments");
5860 Args1 = Proto1->getParamTypes();
5861 Args2 = Proto2->getParamTypes();
5862 }
5863
5864 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5866 TemplateDeductionInfo Info(Loc);
5867
5868 bool HasDeducedAnyParamFromReturnType = false;
5869 if (TPOC != TPOC_Call) {
5871 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5873 /*DeducedFromArrayBound=*/false,
5874 &HasDeducedAnyParamFromReturnType) !=
5876 return false;
5877 }
5878
5879 llvm::SmallBitVector HasDeducedParam;
5880 if (TPOC != TPOC_Conversion) {
5881 HasDeducedParam.resize(Args2.size());
5882 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5884 /*HasDeducedAnyParam=*/nullptr,
5885 &HasDeducedParam) !=
5887 return false;
5888 }
5889
5890 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5893 Sema::SFINAETrap Trap(S, Info);
5895 S, Info.getLocation(), FT2, DeducedArgs,
5897 if (Inst.isInvalid())
5898 return false;
5899
5900 bool AtLeastAsSpecialized;
5902 AtLeastAsSpecialized =
5903 ::FinishTemplateArgumentDeduction(
5904 S, FT2, Deduced, Info,
5905 [&](Sema &S, FunctionTemplateDecl *FTD,
5906 ArrayRef<TemplateArgument> DeducedArgs) {
5907 // As a provisional fix for a core issue that does not
5908 // exist yet, which may be related to CWG2160, only check the
5909 // consistency of parameters and return types which participated
5910 // in deduction. We will still try to substitute them though.
5911 if (TPOC != TPOC_Call) {
5912 if (auto TDR = ::CheckDeductionConsistency(
5913 S, FTD, /*ArgIdx=*/std::nullopt,
5914 Proto2->getReturnType(), Proto1->getReturnType(),
5915 DeducedArgs,
5916 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5917 TDR != TemplateDeductionResult::Success)
5918 return TDR;
5919 }
5920
5921 if (TPOC == TPOC_Conversion)
5922 return TemplateDeductionResult::Success;
5923
5924 return ::DeduceForEachType(
5925 S, TemplateParams, Args2, Args1, Info, Deduced,
5926 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5927 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5928 UnsignedOrNone ArgIdx, QualType P, QualType A,
5929 TemplateDeductionInfo &Info,
5930 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5931 PartialOrderingKind) {
5932 if (ArgIdx && *ArgIdx >= static_cast<unsigned>(Args1Offset))
5933 ArgIdx = *ArgIdx - Args1Offset;
5934 else
5935 ArgIdx = std::nullopt;
5936 return ::CheckDeductionConsistency(
5937 S, FTD, ArgIdx, P, A, DeducedArgs,
5938 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5939 });
5941 });
5942 if (!AtLeastAsSpecialized || Trap.hasErrorOccurred())
5943 return false;
5944
5945 // C++0x [temp.deduct.partial]p11:
5946 // In most cases, all template parameters must have values in order for
5947 // deduction to succeed, but for partial ordering purposes a template
5948 // parameter may remain without a value provided it is not used in the
5949 // types being used for partial ordering. [ Note: a template parameter used
5950 // in a non-deduced context is considered used. -end note]
5951 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5952 for (; ArgIdx != NumArgs; ++ArgIdx)
5953 if (Deduced[ArgIdx].isNull())
5954 break;
5955
5956 if (ArgIdx == NumArgs) {
5957 // All template arguments were deduced. FT1 is at least as specialized
5958 // as FT2.
5959 return true;
5960 }
5961
5962 // Figure out which template parameters were used.
5963 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5964 switch (TPOC) {
5965 case TPOC_Call:
5966 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5967 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5968 TemplateParams->getDepth(), UsedParameters);
5969 break;
5970
5971 case TPOC_Conversion:
5972 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5973 /*OnlyDeduced=*/false,
5974 TemplateParams->getDepth(), UsedParameters);
5975 break;
5976
5977 case TPOC_Other:
5978 // We do not deduce template arguments from the exception specification
5979 // when determining the primary template of a function template
5980 // specialization or when taking the address of a function template.
5981 // Therefore, we do not mark template parameters in the exception
5982 // specification as used during partial ordering to prevent the following
5983 // from being ambiguous:
5984 //
5985 // template<typename T, typename U>
5986 // void f(U) noexcept(noexcept(T())); // #1
5987 //
5988 // template<typename T>
5989 // void f(T*) noexcept; // #2
5990 //
5991 // template<>
5992 // void f<int>(int*) noexcept; // explicit specialization of #2
5993 //
5994 // Although there is no corresponding wording in the standard, this seems
5995 // to be the intended behavior given the definition of
5996 // 'deduction substitution loci' in [temp.deduct].
5998 S.Context,
5999 S.Context.getFunctionTypeWithExceptionSpec(FD2->getType(), EST_None),
6000 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
6001 break;
6002 }
6003
6004 for (; ArgIdx != NumArgs; ++ArgIdx)
6005 // If this argument had no value deduced but was used in one of the types
6006 // used for partial ordering, then deduction fails.
6007 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
6008 return false;
6009
6010 return true;
6011}
6012
6014
6015// This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6016// there is no wording or even resolution for this issue.
6019 const TemplateSpecializationType *TST1,
6020 const TemplateSpecializationType *TST2) {
6021 ArrayRef<TemplateArgument> As1 = TST1->template_arguments(),
6022 As2 = TST2->template_arguments();
6023 const TemplateArgument &TA1 = As1.back(), &TA2 = As2.back();
6024 bool IsPack = TA1.getKind() == TemplateArgument::Pack;
6025 assert(IsPack == (TA2.getKind() == TemplateArgument::Pack));
6026 if (!IsPack)
6028 assert(As1.size() == As2.size());
6029
6030 unsigned PackSize1 = TA1.pack_size(), PackSize2 = TA2.pack_size();
6031 bool IsPackExpansion1 =
6032 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6033 bool IsPackExpansion2 =
6034 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6035 if (PackSize1 == PackSize2 && IsPackExpansion1 == IsPackExpansion2)
6037 if (PackSize1 > PackSize2 && IsPackExpansion1)
6039 if (PackSize1 < PackSize2 && IsPackExpansion2)
6042}
6043
6046 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
6047 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed,
6048 bool PartialOverloading) {
6051 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
6052 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
6053 bool ShouldConvert1 = false;
6054 bool ShouldConvert2 = false;
6055 bool Args1Offset = false;
6056 bool Args2Offset = false;
6057 QualType Obj1Ty;
6058 QualType Obj2Ty;
6059 if (TPOC == TPOC_Call) {
6060 const FunctionProtoType *Proto1 =
6061 FD1->getType()->castAs<FunctionProtoType>();
6062 const FunctionProtoType *Proto2 =
6063 FD2->getType()->castAs<FunctionProtoType>();
6064
6065 // - In the context of a function call, the function parameter types are
6066 // used.
6067 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
6068 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
6069 // C++20 [temp.func.order]p3
6070 // [...] Each function template M that is a member function is
6071 // considered to have a new first parameter of type
6072 // X(M), described below, inserted in its function parameter list.
6073 //
6074 // Note that we interpret "that is a member function" as
6075 // "that is a member function with no expicit object argument".
6076 // Otherwise the ordering rules for methods with expicit objet arguments
6077 // against anything else make no sense.
6078
6079 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
6080 NonStaticMethod2 = Method2 && !Method2->isStatic();
6081
6082 auto Params1Begin = Proto1->param_type_begin(),
6083 Params2Begin = Proto2->param_type_begin();
6084
6085 size_t NumComparedArguments = NumCallArguments1;
6086
6087 if (auto OO = FD1->getOverloadedOperator();
6088 (NonStaticMethod1 && NonStaticMethod2) ||
6089 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
6090 ShouldConvert1 =
6091 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
6092 ShouldConvert2 =
6093 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
6094 NumComparedArguments += 1;
6095
6096 if (ShouldConvert1) {
6097 bool IsRValRef2 =
6098 ShouldConvert2
6099 ? Method2->getRefQualifier() == RQ_RValue
6100 : Proto2->param_type_begin()[0]->isRValueReferenceType();
6101 // Compare 'this' from Method1 against first parameter from Method2.
6102 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
6103 RawObj1Ty, IsRValRef2);
6104 Args1.push_back(Obj1Ty);
6105 Args1Offset = true;
6106 }
6107 if (ShouldConvert2) {
6108 bool IsRValRef1 =
6109 ShouldConvert1
6110 ? Method1->getRefQualifier() == RQ_RValue
6111 : Proto1->param_type_begin()[0]->isRValueReferenceType();
6112 // Compare 'this' from Method2 against first parameter from Method1.
6113 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
6114 RawObj2Ty, IsRValRef1);
6115 Args2.push_back(Obj2Ty);
6116 Args2Offset = true;
6117 }
6118 } else {
6119 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
6120 Params1Begin += 1;
6121 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
6122 Params2Begin += 1;
6123 }
6124 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
6125 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
6126
6127 // C++ [temp.func.order]p5:
6128 // The presence of unused ellipsis and default arguments has no effect on
6129 // the partial ordering of function templates.
6130 Args1.resize(std::min(Args1.size(), NumComparedArguments));
6131 Args2.resize(std::min(Args2.size(), NumComparedArguments));
6132
6133 if (Reversed)
6134 std::reverse(Args2.begin(), Args2.end());
6135 } else {
6136 assert(!Reversed && "Only call context could have reversed arguments");
6137 }
6138 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
6139 Args2, Args2Offset);
6140 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
6141 Args1, Args1Offset);
6142 // C++ [temp.deduct.partial]p10:
6143 // F is more specialized than G if F is at least as specialized as G and G
6144 // is not at least as specialized as F.
6145 if (Better1 != Better2) // We have a clear winner
6146 return Better1 ? FT1 : FT2;
6147
6148 if (!Better1 && !Better2) // Neither is better than the other
6149 return nullptr;
6150
6151 // C++ [temp.deduct.partial]p11:
6152 // ... and if G has a trailing function parameter pack for which F does not
6153 // have a corresponding parameter, and if F does not have a trailing
6154 // function parameter pack, then F is more specialized than G.
6155
6156 SmallVector<QualType> Param1;
6157 Param1.reserve(FD1->param_size() + ShouldConvert1);
6158 if (ShouldConvert1)
6159 Param1.push_back(Obj1Ty);
6160 for (const auto &P : FD1->parameters())
6161 Param1.push_back(P->getType());
6162
6163 SmallVector<QualType> Param2;
6164 Param2.reserve(FD2->param_size() + ShouldConvert2);
6165 if (ShouldConvert2)
6166 Param2.push_back(Obj2Ty);
6167 for (const auto &P : FD2->parameters())
6168 Param2.push_back(P->getType());
6169
6170 unsigned NumParams1 = Param1.size();
6171 unsigned NumParams2 = Param2.size();
6172
6173 bool Variadic1 =
6174 FD1->param_size() && FD1->parameters().back()->isParameterPack();
6175 bool Variadic2 =
6176 FD2->param_size() && FD2->parameters().back()->isParameterPack();
6177 if (Variadic1 != Variadic2) {
6178 if (Variadic1 && NumParams1 > NumParams2)
6179 return FT2;
6180 if (Variadic2 && NumParams2 > NumParams1)
6181 return FT1;
6182 }
6183
6184 // Skip this tie breaker if we are performing overload resolution with partial
6185 // arguments, as this breaks some assumptions about how closely related the
6186 // candidates are.
6187 for (int i = 0, e = std::min(NumParams1, NumParams2);
6188 !PartialOverloading && i < e; ++i) {
6189 QualType T1 = Param1[i].getCanonicalType();
6190 QualType T2 = Param2[i].getCanonicalType();
6191 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
6192 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
6193 if (!TST1 || !TST2)
6194 continue;
6195 switch (getMoreSpecializedTrailingPackTieBreaker(TST1, TST2)) {
6197 return FT1;
6199 return FT2;
6201 continue;
6202 }
6203 llvm_unreachable(
6204 "unknown MoreSpecializedTrailingPackTieBreakerResult value");
6205 }
6206
6207 if (!Context.getLangOpts().CPlusPlus20)
6208 return nullptr;
6209
6210 // Match GCC on not implementing [temp.func.order]p6.2.1.
6211
6212 // C++20 [temp.func.order]p6:
6213 // If deduction against the other template succeeds for both transformed
6214 // templates, constraints can be considered as follows:
6215
6216 // C++20 [temp.func.order]p6.1:
6217 // If their template-parameter-lists (possibly including template-parameters
6218 // invented for an abbreviated function template ([dcl.fct])) or function
6219 // parameter lists differ in length, neither template is more specialized
6220 // than the other.
6223 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
6224 return nullptr;
6225
6226 // C++20 [temp.func.order]p6.2.2:
6227 // Otherwise, if the corresponding template-parameters of the
6228 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6229 // function parameters that positionally correspond between the two
6230 // templates are not of the same type, neither template is more specialized
6231 // than the other.
6232 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
6234 return nullptr;
6235
6236 // [dcl.fct]p5:
6237 // Any top-level cv-qualifiers modifying a parameter type are deleted when
6238 // forming the function type.
6239 for (unsigned i = 0; i < NumParams1; ++i)
6240 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
6241 return nullptr;
6242
6243 // C++20 [temp.func.order]p6.3:
6244 // Otherwise, if the context in which the partial ordering is done is
6245 // that of a call to a conversion function and the return types of the
6246 // templates are not the same, then neither template is more specialized
6247 // than the other.
6248 if (TPOC == TPOC_Conversion &&
6249 !Context.hasSameType(FD1->getReturnType(), FD2->getReturnType()))
6250 return nullptr;
6251
6253 FT1->getAssociatedConstraints(AC1);
6254 FT2->getAssociatedConstraints(AC2);
6255 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6256 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
6257 return nullptr;
6258 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
6259 return nullptr;
6260 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6261 return nullptr;
6262 return AtLeastAsConstrained1 ? FT1 : FT2;
6263}
6264
6267 TemplateSpecCandidateSet &FailedCandidates,
6268 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
6269 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
6270 bool Complain, QualType TargetType) {
6271 if (SpecBegin == SpecEnd) {
6272 if (Complain) {
6273 Diag(Loc, NoneDiag);
6274 FailedCandidates.NoteCandidates(*this, Loc);
6275 }
6276 return SpecEnd;
6277 }
6278
6279 if (SpecBegin + 1 == SpecEnd)
6280 return SpecBegin;
6281
6282 // Find the function template that is better than all of the templates it
6283 // has been compared to.
6284 UnresolvedSetIterator Best = SpecBegin;
6285 FunctionTemplateDecl *BestTemplate
6286 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6287 assert(BestTemplate && "Not a function template specialization?");
6288 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6289 FunctionTemplateDecl *Challenger
6290 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6291 assert(Challenger && "Not a function template specialization?");
6292 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6293 Loc, TPOC_Other, 0),
6294 Challenger)) {
6295 Best = I;
6296 BestTemplate = Challenger;
6297 }
6298 }
6299
6300 // Make sure that the "best" function template is more specialized than all
6301 // of the others.
6302 bool Ambiguous = false;
6303 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6304 FunctionTemplateDecl *Challenger
6305 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6306 if (I != Best &&
6307 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6308 Loc, TPOC_Other, 0),
6309 BestTemplate)) {
6310 Ambiguous = true;
6311 break;
6312 }
6313 }
6314
6315 if (!Ambiguous) {
6316 // We found an answer. Return it.
6317 return Best;
6318 }
6319
6320 // Diagnose the ambiguity.
6321 if (Complain) {
6322 Diag(Loc, AmbigDiag);
6323
6324 // FIXME: Can we order the candidates in some sane way?
6325 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6326 PartialDiagnostic PD = CandidateDiag;
6327 const auto *FD = cast<FunctionDecl>(*I);
6329 FD->getPrimaryTemplate()->getTemplateParameters(),
6330 *FD->getTemplateSpecializationArgs());
6331 if (!TargetType.isNull())
6332 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6333 Diag((*I)->getLocation(), PD);
6334 }
6335 }
6336
6337 return SpecEnd;
6338}
6339
6341 FunctionDecl *FD2) {
6342 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6343 "not for function templates");
6344 assert(!FD1->isFunctionTemplateSpecialization() ||
6346 assert(!FD2->isFunctionTemplateSpecialization() ||
6348
6349 FunctionDecl *F1 = FD1;
6350 if (FunctionDecl *P = FD1->getTemplateInstantiationPattern(false))
6351 F1 = P;
6352
6353 FunctionDecl *F2 = FD2;
6354 if (FunctionDecl *P = FD2->getTemplateInstantiationPattern(false))
6355 F2 = P;
6356
6358 F1->getAssociatedConstraints(AC1);
6359 F2->getAssociatedConstraints(AC2);
6360 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6361 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6362 return nullptr;
6363 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6364 return nullptr;
6365 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6366 return nullptr;
6367 return AtLeastAsConstrained1 ? FD1 : FD2;
6368}
6369
6370/// Determine whether one template specialization, P1, is at least as
6371/// specialized than another, P2.
6372///
6373/// \tparam TemplateLikeDecl The kind of P2, which must be a
6374/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6375/// \param T1 The injected-class-name of P1 (faked for a variable template).
6376/// \param T2 The injected-class-name of P2 (faked for a variable template).
6377/// \param Template The primary template of P2, in case it is a partial
6378/// specialization, the same as P2 otherwise.
6379template <typename TemplateLikeDecl>
6381 TemplateLikeDecl *P2,
6383 TemplateDeductionInfo &Info) {
6384 // C++ [temp.class.order]p1:
6385 // For two class template partial specializations, the first is at least as
6386 // specialized as the second if, given the following rewrite to two
6387 // function templates, the first function template is at least as
6388 // specialized as the second according to the ordering rules for function
6389 // templates (14.6.6.2):
6390 // - the first function template has the same template parameters as the
6391 // first partial specialization and has a single function parameter
6392 // whose type is a class template specialization with the template
6393 // arguments of the first partial specialization, and
6394 // - the second function template has the same template parameters as the
6395 // second partial specialization and has a single function parameter
6396 // whose type is a class template specialization with the template
6397 // arguments of the second partial specialization.
6398 //
6399 // Rather than synthesize function templates, we merely perform the
6400 // equivalent partial ordering by performing deduction directly on
6401 // the template arguments of the class template partial
6402 // specializations. This computation is slightly simpler than the
6403 // general problem of function template partial ordering, because
6404 // class template partial specializations are more constrained. We
6405 // know that every template parameter is deducible from the class
6406 // template partial specialization's template arguments, for
6407 // example.
6409
6410 // Determine whether P1 is at least as specialized as P2.
6411 Deduced.resize(P2->getTemplateParameters()->size());
6413 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6414 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6415 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6416 return false;
6417
6418 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6421 Sema::SFINAETrap Trap(S, Info);
6422 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs);
6423 if (Inst.isInvalid())
6424 return false;
6425
6427 Ps = cast<TemplateSpecializationType>(T2)->template_arguments(),
6428 As = cast<TemplateSpecializationType>(T1)->template_arguments();
6429
6432 Result = ::FinishTemplateArgumentDeduction(
6433 S, P2, P2->getTemplateParameters(), Template,
6434 /*IsPartialOrdering=*/true, Ps, As, Deduced, Info,
6435 /*CopyDeducedArgs=*/false);
6436 });
6438}
6439
6440namespace {
6441// A dummy class to return nullptr instead of P2 when performing "more
6442// specialized than primary" check.
6443struct GetP2 {
6444 template <typename T1, typename T2,
6445 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6446 T2 *operator()(T1 *, T2 *P2) {
6447 return P2;
6448 }
6449 template <typename T1, typename T2,
6450 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6451 T1 *operator()(T1 *, T2 *) {
6452 return nullptr;
6453 }
6454};
6455
6456// The assumption is that two template argument lists have the same size.
6457struct TemplateArgumentListAreEqual {
6458 ASTContext &Ctx;
6459 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6460
6461 template <typename T1, typename T2,
6462 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6463 bool operator()(T1 *PS1, T2 *PS2) {
6464 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6465 Args2 = PS2->getTemplateArgs().asArray();
6466
6467 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6468 // We use profile, instead of structural comparison of the arguments,
6469 // because canonicalization can't do the right thing for dependent
6470 // expressions.
6471 llvm::FoldingSetNodeID IDA, IDB;
6472 Args1[I].Profile(IDA, Ctx);
6473 Args2[I].Profile(IDB, Ctx);
6474 if (IDA != IDB)
6475 return false;
6476 }
6477 return true;
6478 }
6479
6480 template <typename T1, typename T2,
6481 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6482 bool operator()(T1 *Spec, T2 *Primary) {
6483 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6484 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6485
6486 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6487 // We use profile, instead of structural comparison of the arguments,
6488 // because canonicalization can't do the right thing for dependent
6489 // expressions.
6490 llvm::FoldingSetNodeID IDA, IDB;
6491 Args1[I].Profile(IDA, Ctx);
6492 // Unlike the specialization arguments, the injected arguments are not
6493 // always canonical.
6494 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6495 if (IDA != IDB)
6496 return false;
6497 }
6498 return true;
6499 }
6500};
6501} // namespace
6502
6503/// Returns the more specialized template specialization between T1/P1 and
6504/// T2/P2.
6505/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6506/// specialization and T2/P2 is the primary template.
6507/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6508///
6509/// \param T1 the type of the first template partial specialization
6510///
6511/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6512/// template partial specialization; otherwise, the type of the
6513/// primary template.
6514///
6515/// \param P1 the first template partial specialization
6516///
6517/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6518/// partial specialization; otherwise, the primary template.
6519///
6520/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6521/// more specialized, returns nullptr if P1 is not more specialized.
6522/// - otherwise, returns the more specialized template partial
6523/// specialization. If neither partial specialization is more
6524/// specialized, returns NULL.
6525template <typename TemplateLikeDecl, typename PrimaryDel>
6526static TemplateLikeDecl *
6527getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6528 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6529 constexpr bool IsMoreSpecialThanPrimaryCheck =
6530 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6531
6532 TemplateDecl *P2T;
6533 if constexpr (IsMoreSpecialThanPrimaryCheck)
6534 P2T = P2;
6535 else
6536 P2T = P2->getSpecializedTemplate();
6537
6538 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, P2T, Info);
6539 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6540 return nullptr;
6541
6542 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1,
6543 P1->getSpecializedTemplate(), Info);
6544 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6545 return P1;
6546
6547 // C++ [temp.deduct.partial]p10:
6548 // F is more specialized than G if F is at least as specialized as G and G
6549 // is not at least as specialized as F.
6550 if (Better1 != Better2) // We have a clear winner
6551 return Better1 ? P1 : GetP2()(P1, P2);
6552
6553 if (!Better1 && !Better2)
6554 return nullptr;
6555
6560 return P1;
6562 return GetP2()(P1, P2);
6564 break;
6565 }
6566
6567 if (!S.Context.getLangOpts().CPlusPlus20)
6568 return nullptr;
6569
6570 // Match GCC on not implementing [temp.func.order]p6.2.1.
6571
6572 // C++20 [temp.func.order]p6:
6573 // If deduction against the other template succeeds for both transformed
6574 // templates, constraints can be considered as follows:
6575
6576 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6577 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6578 if (TPL1->size() != TPL2->size())
6579 return nullptr;
6580
6581 // C++20 [temp.func.order]p6.2.2:
6582 // Otherwise, if the corresponding template-parameters of the
6583 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6584 // function parameters that positionally correspond between the two
6585 // templates are not of the same type, neither template is more specialized
6586 // than the other.
6587 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6589 return nullptr;
6590
6591 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6592 return nullptr;
6593
6595 P1->getAssociatedConstraints(AC1);
6596 P2->getAssociatedConstraints(AC2);
6597 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6598 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6599 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6600 return nullptr;
6601 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6602 return nullptr;
6603 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6604 return nullptr;
6605 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6606}
6607
6619
6622 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6625
6627 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6628 if (MaybeSpec)
6629 Info.clearSFINAEDiagnostic();
6630 return MaybeSpec;
6631}
6632
6637 // Pretend the variable template specializations are class template
6638 // specializations and form a fake injected class name type for comparison.
6639 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6640 "the partial specializations being compared should specialize"
6641 " the same template.");
6643 QualType PT1 = Context.getCanonicalTemplateSpecializationType(
6645 QualType PT2 = Context.getCanonicalTemplateSpecializationType(
6647
6648 TemplateDeductionInfo Info(Loc);
6649 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6650}
6651
6654 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6655 TemplateName Name(Primary->getCanonicalDecl());
6656
6657 SmallVector<TemplateArgument, 8> PrimaryCanonArgs(
6659 Context.canonicalizeTemplateArguments(PrimaryCanonArgs);
6660
6661 QualType PrimaryT = Context.getCanonicalTemplateSpecializationType(
6662 ElaboratedTypeKeyword::None, Name, PrimaryCanonArgs);
6663 QualType PartialT = Context.getCanonicalTemplateSpecializationType(
6665
6667 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6668 if (MaybeSpec)
6669 Info.clearSFINAEDiagnostic();
6670 return MaybeSpec;
6671}
6672
6675 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
6676 bool PartialOrdering, bool *StrictPackMatch) {
6677 // C++1z [temp.arg.template]p4: (DR 150)
6678 // A template template-parameter P is at least as specialized as a
6679 // template template-argument A if, given the following rewrite to two
6680 // function templates...
6681
6682 // Rather than synthesize function templates, we merely perform the
6683 // equivalent partial ordering by performing deduction directly on
6684 // the template parameter lists of the template template parameters.
6685 //
6687
6691 if (Inst.isInvalid())
6692 return false;
6693
6695
6696 // Given an invented class template X with the template parameter list of
6697 // A (including default arguments):
6698 // - Each function template has a single function parameter whose type is
6699 // a specialization of X with template arguments corresponding to the
6700 // template parameters from the respective function template
6702
6703 // Check P's arguments against A's parameter list. This will fill in default
6704 // template arguments as needed. AArgs are already correct by construction.
6705 // We can't just use CheckTemplateIdType because that will expand alias
6706 // templates.
6708 {
6710 P->getRAngleLoc());
6711 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6712 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6713 // expansions, to form an "as written" argument list.
6714 TemplateArgument Arg = PArgs[I];
6715 if (Arg.getKind() == TemplateArgument::Pack) {
6716 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6717 Arg = *Arg.pack_begin();
6718 }
6720 Arg, QualType(), P->getParam(I)->getLocation()));
6721 }
6722 PArgs.clear();
6723
6724 // C++1z [temp.arg.template]p3:
6725 // If the rewrite produces an invalid type, then P is not at least as
6726 // specialized as A.
6728 /*PartialOrdering=*/false, /*MatchingTTP=*/true);
6729 CTAI.SugaredConverted = std::move(PArgs);
6730 if (CheckTemplateArgumentList(AArg, ArgLoc, PArgList, DefaultArgs,
6731 /*PartialTemplateArgs=*/false, CTAI,
6732 /*UpdateArgsWithConversions=*/true,
6733 /*ConstraintsNotSatisfied=*/nullptr))
6734 return false;
6735 PArgs = std::move(CTAI.SugaredConverted);
6736 if (StrictPackMatch)
6737 *StrictPackMatch |= CTAI.StrictPackMatch;
6738 }
6739
6740 // Determine whether P1 is at least as specialized as P2.
6741 TemplateDeductionInfo Info(ArgLoc, A->getDepth());
6743 Deduced.resize(A->size());
6744
6745 // ... the function template corresponding to P is at least as specialized
6746 // as the function template corresponding to A according to the partial
6747 // ordering rules for function templates.
6748
6749 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6750 // applying the partial ordering rules for function templates on
6751 // the rewritten template template parameters:
6752 // - In a deduced context, the matching of packs versus fixed-size needs to
6753 // be inverted between Ps and As. On non-deduced context, matching needs to
6754 // happen both ways, according to [temp.arg.template]p3, but this is
6755 // currently implemented as a special case elsewhere.
6757 *this, A, AArgs, PArgs, Info, Deduced,
6758 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true,
6760 /*HasDeducedAnyParam=*/nullptr)) {
6762 if (StrictPackMatch && Info.hasStrictPackMatch())
6763 *StrictPackMatch = true;
6764 break;
6765
6767 Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
6768 << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
6770 return false;
6772 Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
6773 << Info.FirstArg << Info.SecondArg;
6774 return false;
6777 diag::err_inconsistent_deduction)
6778 << Info.FirstArg << Info.SecondArg;
6779 return false;
6781 return false;
6782
6783 // None of these should happen for a plain deduction.
6798 llvm_unreachable("Unexpected Result");
6799 }
6800
6803 TDK = ::FinishTemplateArgumentDeduction(
6804 *this, AArg, AArg->getTemplateParameters(), AArg, PartialOrdering,
6805 AArgs, PArgs, Deduced, Info, /*CopyDeducedArgs=*/false);
6806 });
6807 switch (TDK) {
6809 return true;
6810
6811 // It doesn't seem possible to get a non-deduced mismatch when partial
6812 // ordering TTPs, except with an invalid template parameter list which has
6813 // a parameter after a pack.
6815 assert(PArg->isInvalidDecl() && "Unexpected NonDeducedMismatch");
6816 return false;
6817
6818 // Substitution failures should have already been diagnosed.
6822 return false;
6823
6824 // None of these should happen when just converting deduced arguments.
6839 llvm_unreachable("Unexpected Result");
6840 }
6841 llvm_unreachable("Unexpected TDK");
6842}
6843
6844namespace {
6845struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6846 llvm::SmallBitVector &Used;
6847 unsigned Depth;
6848 bool VisitDeclRefTypes = true;
6849
6850 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used, unsigned Depth,
6851 bool VisitDeclRefTypes = true)
6852 : Used(Used), Depth(Depth), VisitDeclRefTypes(VisitDeclRefTypes) {}
6853
6854 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6855 if (T->getDepth() == Depth)
6856 Used[T->getIndex()] = true;
6857 return true;
6858 }
6859
6860 bool TraverseTemplateName(TemplateName Template,
6861 bool TraverseQualifier) override {
6862 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6863 Template.getAsTemplateDecl()))
6864 if (TTP->getDepth() == Depth)
6865 Used[TTP->getIndex()] = true;
6867 TraverseQualifier);
6868 return true;
6869 }
6870
6871 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6872 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6873 if (NTTP->getDepth() == Depth)
6874 Used[NTTP->getIndex()] = true;
6875 if (VisitDeclRefTypes)
6877 return true;
6878 }
6879
6880 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
6881 TemplateTemplateParmDecl *TTP = E->getParameter();
6882 if (TTP->getDepth() == Depth)
6883 Used[TTP->getIndex()] = true;
6884 return true;
6885 }
6886
6887 bool TraverseSizeOfPackExpr(SizeOfPackExpr *SOPE) override {
6888 return TraverseDecl(SOPE->getPack());
6889 }
6890};
6891}
6892
6893/// Mark the template parameters that are used by the given
6894/// expression.
6895static void
6897 const Expr *E,
6898 bool OnlyDeduced,
6899 unsigned Depth,
6900 llvm::SmallBitVector &Used) {
6901 if (!OnlyDeduced) {
6902 MarkUsedTemplateParameterVisitor(Used, Depth)
6903 .TraverseStmt(const_cast<Expr *>(E));
6904 return;
6905 }
6906
6907 // We can deduce from a pack expansion.
6908 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6909 E = Expansion->getPattern();
6910
6912
6913 if (const auto *DTI = dyn_cast<DependentTemplateIdExpr>(E)) {
6914 Used[DTI->getParameter()->getIndex()] = true;
6915 for (const auto &TLoc : DTI->template_arguments())
6916 MarkUsedTemplateParameters(Ctx, TLoc.getArgument(), OnlyDeduced, Depth,
6917 Used);
6918 return;
6919 }
6920
6921 const NonTypeOrVarTemplateParmDecl NTTP =
6923 if (!NTTP)
6924 return;
6925 if (NTTP.getDepth() == Depth)
6926 Used[NTTP.getIndex()] = true;
6927
6928 // In C++17 mode, additional arguments may be deduced from the type of a
6929 // non-type argument.
6930 if (Ctx.getLangOpts().CPlusPlus17)
6931 MarkUsedTemplateParameters(Ctx, NTTP.getType(), OnlyDeduced, Depth, Used);
6932}
6933
6934/// Mark the template parameters that are used by the given
6935/// nested name specifier.
6937 bool OnlyDeduced, unsigned Depth,
6938 llvm::SmallBitVector &Used) {
6940 return;
6941 MarkUsedTemplateParameters(Ctx, QualType(NNS.getAsType(), 0), OnlyDeduced,
6942 Depth, Used);
6943}
6944
6945/// Mark the template parameters that are used by the given
6946/// template name.
6947static void
6949 TemplateName Name,
6950 bool OnlyDeduced,
6951 unsigned Depth,
6952 llvm::SmallBitVector &Used) {
6953 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6955 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6956 if (TTP->getDepth() == Depth)
6957 Used[TTP->getIndex()] = true;
6958 }
6959 return;
6960 }
6961
6963 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6964 Depth, Used);
6966 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6967 Depth, Used);
6968}
6969
6970/// Mark the template parameters that are used by the given
6971/// type.
6972static void
6974 bool OnlyDeduced,
6975 unsigned Depth,
6976 llvm::SmallBitVector &Used) {
6977 if (T.isNull())
6978 return;
6979
6980 // Non-dependent types have nothing deducible
6981 if (!T->isDependentType())
6982 return;
6983
6984 T = Ctx.getCanonicalType(T);
6985 switch (T->getTypeClass()) {
6986 case Type::Pointer:
6989 OnlyDeduced,
6990 Depth,
6991 Used);
6992 break;
6993
6994 case Type::BlockPointer:
6997 OnlyDeduced,
6998 Depth,
6999 Used);
7000 break;
7001
7002 case Type::LValueReference:
7003 case Type::RValueReference:
7006 OnlyDeduced,
7007 Depth,
7008 Used);
7009 break;
7010
7011 case Type::MemberPointer: {
7012 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
7013 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
7014 Depth, Used);
7016 QualType(MemPtr->getQualifier().getAsType(), 0),
7017 OnlyDeduced, Depth, Used);
7018 break;
7019 }
7020
7021 case Type::DependentSizedArray:
7023 cast<DependentSizedArrayType>(T)->getSizeExpr(),
7024 OnlyDeduced, Depth, Used);
7025 // Fall through to check the element type
7026 [[fallthrough]];
7027
7028 case Type::ConstantArray:
7029 case Type::IncompleteArray:
7030 case Type::ArrayParameter:
7032 cast<ArrayType>(T)->getElementType(),
7033 OnlyDeduced, Depth, Used);
7034 break;
7035 case Type::Vector:
7036 case Type::ExtVector:
7038 cast<VectorType>(T)->getElementType(),
7039 OnlyDeduced, Depth, Used);
7040 break;
7041
7042 case Type::DependentVector: {
7043 const auto *VecType = cast<DependentVectorType>(T);
7044 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
7045 Depth, Used);
7046 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
7047 Used);
7048 break;
7049 }
7050 case Type::DependentSizedExtVector: {
7051 const DependentSizedExtVectorType *VecType
7053 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
7054 Depth, Used);
7055 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
7056 Depth, Used);
7057 break;
7058 }
7059
7060 case Type::DependentAddressSpace: {
7061 const DependentAddressSpaceType *DependentASType =
7063 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
7064 OnlyDeduced, Depth, Used);
7066 DependentASType->getAddrSpaceExpr(),
7067 OnlyDeduced, Depth, Used);
7068 break;
7069 }
7070
7071 case Type::ConstantMatrix: {
7073 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
7074 Depth, Used);
7075 break;
7076 }
7077
7078 case Type::DependentSizedMatrix: {
7080 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
7081 Depth, Used);
7082 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
7083 Used);
7084 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
7085 Depth, Used);
7086 break;
7087 }
7088
7089 case Type::FunctionProto: {
7091 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
7092 Used);
7093 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
7094 // C++17 [temp.deduct.type]p5:
7095 // The non-deduced contexts are: [...]
7096 // -- A function parameter pack that does not occur at the end of the
7097 // parameter-declaration-list.
7098 if (!OnlyDeduced || I + 1 == N ||
7099 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
7100 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
7101 Depth, Used);
7102 } else {
7103 // FIXME: C++17 [temp.deduct.call]p1:
7104 // When a function parameter pack appears in a non-deduced context,
7105 // the type of that pack is never deduced.
7106 //
7107 // We should also track a set of "never deduced" parameters, and
7108 // subtract that from the list of deduced parameters after marking.
7109 }
7110 }
7111 if (auto *E = Proto->getNoexceptExpr())
7112 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
7113 break;
7114 }
7115
7116 case Type::TemplateTypeParm: {
7117 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
7118 if (TTP->getDepth() == Depth)
7119 Used[TTP->getIndex()] = true;
7120 break;
7121 }
7122
7123 case Type::SubstTemplateTypeParmPack: {
7124 const SubstTemplateTypeParmPackType *Subst
7126 if (Subst->getReplacedParameter()->getDepth() == Depth)
7127 Used[Subst->getIndex()] = true;
7128 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), OnlyDeduced,
7129 Depth, Used);
7130 break;
7131 }
7132 case Type::SubstBuiltinTemplatePack: {
7133 MarkUsedTemplateParameters(Ctx, cast<SubstPackType>(T)->getArgumentPack(),
7134 OnlyDeduced, Depth, Used);
7135 break;
7136 }
7137
7138 case Type::InjectedClassName:
7140 ->getDecl()
7141 ->getCanonicalTemplateSpecializationType(Ctx);
7142 [[fallthrough]];
7143
7144 case Type::TemplateSpecialization: {
7145 const TemplateSpecializationType *Spec
7147
7148 TemplateName Name = Spec->getTemplateName();
7149 if (OnlyDeduced && Name.getAsDependentTemplateName())
7150 break;
7151
7152 MarkUsedTemplateParameters(Ctx, Name, OnlyDeduced, Depth, Used);
7153
7154 // C++0x [temp.deduct.type]p9:
7155 // If the template argument list of P contains a pack expansion that is
7156 // not the last template argument, the entire template argument list is a
7157 // non-deduced context.
7158 if (OnlyDeduced &&
7159 hasPackExpansionBeforeEnd(Spec->template_arguments()))
7160 break;
7161
7162 for (const auto &Arg : Spec->template_arguments())
7163 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
7164 break;
7165 }
7166
7167 case Type::Complex:
7168 if (!OnlyDeduced)
7170 cast<ComplexType>(T)->getElementType(),
7171 OnlyDeduced, Depth, Used);
7172 break;
7173
7174 case Type::Atomic:
7175 if (!OnlyDeduced)
7177 cast<AtomicType>(T)->getValueType(),
7178 OnlyDeduced, Depth, Used);
7179 break;
7180
7181 case Type::DependentName:
7182 if (!OnlyDeduced)
7184 cast<DependentNameType>(T)->getQualifier(),
7185 OnlyDeduced, Depth, Used);
7186 break;
7187
7188 case Type::TypeOf:
7189 if (!OnlyDeduced)
7190 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
7191 OnlyDeduced, Depth, Used);
7192 break;
7193
7194 case Type::TypeOfExpr:
7195 if (!OnlyDeduced)
7197 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
7198 OnlyDeduced, Depth, Used);
7199 break;
7200
7201 case Type::Decltype:
7202 if (!OnlyDeduced)
7204 cast<DecltypeType>(T)->getUnderlyingExpr(),
7205 OnlyDeduced, Depth, Used);
7206 break;
7207
7208 case Type::PackIndexing:
7209 if (!OnlyDeduced) {
7211 OnlyDeduced, Depth, Used);
7213 OnlyDeduced, Depth, Used);
7214 }
7215 break;
7216
7217 case Type::UnaryTransform:
7218 if (!OnlyDeduced) {
7219 auto *UTT = cast<UnaryTransformType>(T);
7220 auto Next = UTT->getUnderlyingType();
7221 if (Next.isNull())
7222 Next = UTT->getBaseType();
7223 MarkUsedTemplateParameters(Ctx, Next, OnlyDeduced, Depth, Used);
7224 }
7225 break;
7226
7227 case Type::PackExpansion:
7229 cast<PackExpansionType>(T)->getPattern(),
7230 OnlyDeduced, Depth, Used);
7231 break;
7232
7233 case Type::Auto:
7234 case Type::DeducedTemplateSpecialization:
7236 cast<DeducedType>(T)->getDeducedType(),
7237 OnlyDeduced, Depth, Used);
7238 break;
7239 case Type::DependentBitInt:
7241 cast<DependentBitIntType>(T)->getNumBitsExpr(),
7242 OnlyDeduced, Depth, Used);
7243 break;
7244
7245 case Type::HLSLAttributedResource:
7247 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
7248 Depth, Used);
7249 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
7251 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
7252 OnlyDeduced, Depth, Used);
7253 break;
7254
7255 // None of these types have any template parameters in them.
7256 case Type::Builtin:
7257 case Type::VariableArray:
7258 case Type::FunctionNoProto:
7259 case Type::Record:
7260 case Type::Enum:
7261 case Type::ObjCInterface:
7262 case Type::ObjCObject:
7263 case Type::ObjCObjectPointer:
7264 case Type::UnresolvedUsing:
7265 case Type::Pipe:
7266 case Type::BitInt:
7267 case Type::HLSLInlineSpirv:
7268 case Type::OverflowBehavior:
7269#define TYPE(Class, Base)
7270#define ABSTRACT_TYPE(Class, Base)
7271#define DEPENDENT_TYPE(Class, Base)
7272#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7273#include "clang/AST/TypeNodes.inc"
7274 break;
7275 }
7276}
7277
7278/// Mark the template parameters that are used by this
7279/// template argument.
7280static void
7283 bool OnlyDeduced,
7284 unsigned Depth,
7285 llvm::SmallBitVector &Used) {
7286 switch (TemplateArg.getKind()) {
7292 break;
7293
7295 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
7296 Depth, Used);
7297 break;
7298
7302 TemplateArg.getAsTemplateOrTemplatePattern(),
7303 OnlyDeduced, Depth, Used);
7304 break;
7305
7307 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
7308 Depth, Used);
7309 break;
7310
7312 for (const auto &P : TemplateArg.pack_elements())
7313 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
7314 break;
7315 }
7316}
7317
7318void
7319Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7320 unsigned Depth,
7321 llvm::SmallBitVector &Used) {
7322 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
7323}
7324
7326 const Expr *E, unsigned Depth, llvm::SmallBitVector &Used) {
7327 MarkUsedTemplateParameterVisitor(Used, Depth, /*VisitDeclRefTypes=*/false)
7328 .TraverseStmt(const_cast<Expr *>(E));
7329}
7330
7331void
7333 bool OnlyDeduced, unsigned Depth,
7334 llvm::SmallBitVector &Used) {
7335 // C++0x [temp.deduct.type]p9:
7336 // If the template argument list of P contains a pack expansion that is not
7337 // the last template argument, the entire template argument list is a
7338 // non-deduced context.
7339 if (OnlyDeduced &&
7340 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
7341 return;
7342
7343 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7344 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
7345 Depth, Used);
7346}
7347
7349 bool OnlyDeduced, unsigned Depth,
7350 llvm::SmallBitVector &Used) {
7351 if (OnlyDeduced && hasPackExpansionBeforeEnd(TemplateArgs))
7352 return;
7353
7354 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7355 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced, Depth,
7356 Used);
7357}
7358
7360 ArrayRef<TemplateArgumentLoc> TemplateArgs, unsigned Depth,
7361 llvm::SmallBitVector &Used) {
7362 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7364 /*OnlyDeduced=*/false, Depth, Used);
7365}
7366
7369 llvm::SmallBitVector &Deduced) {
7370 TemplateParameterList *TemplateParams
7371 = FunctionTemplate->getTemplateParameters();
7372 Deduced.clear();
7373 Deduced.resize(TemplateParams->size());
7374
7375 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
7376 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
7377 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
7378 true, TemplateParams->getDepth(), Deduced);
7379}
7380
7383 QualType T) {
7384 if (!T->isDependentType())
7385 return false;
7386
7387 TemplateParameterList *TemplateParams
7388 = FunctionTemplate->getTemplateParameters();
7389 llvm::SmallBitVector Deduced(TemplateParams->size());
7390 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
7391 Deduced);
7392
7393 return Deduced.any();
7394}
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.
Result
Implement __builtin_bit_cast and related operations.
#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 AccessResult DeduceTemplateArguments(Sema &S, FriendTemplateDecl *FTD, DeclContext *DC, const TemplateSpecializationType *TST, ArrayRef< TemplateParameterList * > TPLs, TemplateSpecCandidateSet *FailedTSC, MultiLevelTemplateArgumentList &DeducedArgs)
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 void AddFriendTemplateDeductionCandidate(Sema &S, TemplateDecl *TD, TemplateDeductionInfo &Info, TemplateDeductionResult Result, TemplateSpecCandidateSet *FailedTSC)
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...
static TemplateDeductionResult CheckDeducedTemplateArgumentList(Sema &S, TemplateDecl *Template, ArrayRef< TemplateArgumentLoc > Ps, ArrayRef< TemplateArgument > As, const MultiLevelTemplateArgumentList &MLTAL, TemplateDeductionInfo &Info)
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:239
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
QualType getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateName TypeConstraintConcept=TemplateName(), ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
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
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given 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
TypeLoc getValueLoc() const
Definition TypeLoc.h:2692
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8276
Pointer to a block type.
Definition TypeBase.h:3633
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2976
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3012
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
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:2719
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition DeclCXX.h:2342
bool isStatic() const
Definition DeclCXX.cpp:2417
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
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:1744
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:3355
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:4465
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4484
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4481
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.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
ValueDecl * getDecl()
Definition Expr.h:1358
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:550
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:995
Kind getKind() const
Definition DeclBase.h:450
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition Template.h:339
void setDeducedFromArrayBound(bool Deduced)
Specify whether the given non-type template argument was deduced from an array bound.
Definition Template.h:366
bool wasDeducedFromArrayBound() const
For a non-type template argument, determine whether the template argument was deduced from an array b...
Definition Template.h:362
SourceLocation getElaboratedKeywordLoc() const
Definition TypeLoc.h:2540
NestedNameSpecifierLoc getQualifierLoc() const
Definition TypeLoc.h:2552
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4139
QualType getPointeeType() const
Definition TypeBase.h:4151
Represents an extended vector type where either the type or size is dependent.
Definition TypeBase.h:4179
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition TypeBase.h:4551
TemplateTemplateParmDecl * getParameter() const
Definition ExprCXX.h:3509
Represents a vector type where either the type or size is dependent.
Definition TypeBase.h:4305
virtual bool TraverseTemplateName(TemplateName Template, bool TraverseQualifier=true)
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:1948
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition DeclCXX.h:1977
const Expr * getExpr() const
Definition DeclCXX.h:1957
The return type of classify().
Definition Expr.h:340
bool isLValue() const
Definition Expr.h:391
This represents one expression.
Definition Expr.h:113
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3115
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition Expr.h:145
ExtVectorType - Extended vector type.
Definition TypeBase.h:4345
Stores a list of template parameters and the associated requires-clause (if any) for a TemplateDecl a...
Declaration of a friend template.
Represents a function declaration or definition.
Definition Decl.h:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4246
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4234
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3909
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
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:4305
void getAssociatedConstraints(SmallVectorImpl< AssociatedConstraint > &ACs) const
Get the associated-constraints of this function declaration.
Definition Decl.h:2883
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4370
bool isImmediateEscalating() const
Definition Decl.cpp:3355
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4171
size_t param_size() const
Definition Decl.h:2921
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5385
param_type_iterator param_type_begin() const
Definition TypeBase.h:5829
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition TypeBase.h:5867
unsigned getNumParams() const
Definition TypeBase.h:5663
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition TypeBase.h:5805
Qualifiers getMethodQuals() const
Definition TypeBase.h:5811
QualType getParamType(unsigned i) const
Definition TypeBase.h:5665
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition TypeBase.h:5698
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5789
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5674
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition TypeBase.h:5750
param_type_iterator param_type_end() const
Definition TypeBase.h:5833
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5670
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5819
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:4581
QualType getReturnType() const
Definition TypeBase.h:4921
Describes an C or C++ initializer list.
Definition Expr.h:5352
unsigned getNumInits() const
Definition Expr.h:5385
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition Expr.h:5389
ArrayRef< Expr * > inits() const
Definition Expr.h:5405
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3695
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
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:565
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4415
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4429
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3731
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3763
QualType getPointeeType() const
Definition TypeBase.h:3749
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final)
Add a new outmost level to the multi-level template argument list.
Definition Template.h:218
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args, bool Final=false)
Replaces the current 'innermost' level with the provided argument list.
Definition Template.h:245
This represents a decl that may have a name.
Definition Decl.h:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
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:8059
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3142
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3294
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3203
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3255
decls_iterator decls_begin() const
Definition ExprCXX.h:3235
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3324
decls_iterator decls_end() const
Definition ExprCXX.h:3238
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition ExprCXX.h:4416
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
QualType getPointeeType() const
Definition TypeBase.h:3406
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8507
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8418
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8544
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8458
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:8603
QualType getCanonicalType() const
Definition TypeBase.h:8470
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8512
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1745
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8464
Represents a template name as written in source code.
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
GC getObjCGCAttr() const
Definition TypeBase.h:520
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
void removeObjCLifetime()
Definition TypeBase.h:552
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:458
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition TypeBase.h:560
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
bool hasAddressSpace() const
Definition TypeBase.h:571
void removeObjCGCAttr()
Definition TypeBase.h:524
void removeAddressSpace()
Definition TypeBase.h:597
bool hasObjCGCAttr() const
Definition TypeBase.h:519
void setCVRQualifiers(unsigned mask)
Definition TypeBase.h:492
bool hasObjCLifetime() const
Definition TypeBase.h:545
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:534
LangAS getAddressSpace() const
Definition TypeBase.h:572
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3713
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:3658
QualType getPointeeType() const
Definition TypeBase.h:3680
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:13760
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8476
A RAII object to temporarily push a declaration context.
Definition Sema.h:3532
A helper class for building up ExtParameterInfos.
Definition Sema.h:13129
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:13148
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12549
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12583
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:13158
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:1471
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:6965
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:12071
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition Sema.h:12063
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition Sema.h:12067
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1304
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:935
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:777
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:1208
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:12267
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:928
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
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:1444
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:12620
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:8209
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)
TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs, bool EvaluateConstraints=true)
bool isSFINAEContext() const
Definition Sema.h:13798
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15594
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:6776
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6745
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:646
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.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6453
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:13001
NamedDecl * getPack() const
Retrieve the parameter pack.
Definition ExprCXX.h:4562
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
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
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
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
All associated constraints derived from this template parameter list, including the requires clause a...
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...
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
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, int D, int 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:3673
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
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
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:8389
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8400
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:1879
bool isVoidType() const
Definition TypeBase.h:9027
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition Type.cpp:1996
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:9003
bool isRValueReferenceType() const
Definition TypeBase.h:8687
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:8754
bool isFunctionPointerType() const
Definition TypeBase.h:8722
bool isPointerType() const
Definition TypeBase.h:8655
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9321
bool isReferenceType() const
Definition TypeBase.h:8679
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2976
bool isLValueReferenceType() const
Definition TypeBase.h:8683
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3196
bool isMemberPointerType() const
Definition TypeBase.h:8736
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5459
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9170
bool isFunctionType() const
Definition TypeBase.h:8651
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8740
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isAnyPointerType() const
Definition TypeBase.h:8663
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9254
bool isRecordType() const
Definition TypeBase.h:8782
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:713
QualType getType() const
Definition Decl.h:724
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:933
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1603
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:4253
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
Top level wrappers for InstallAPI frontend operations.
@ OO_None
Not an overloaded operator.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
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:793
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
@ 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)
@ AS_public
Definition Specifiers.h:125
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:906
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:581
@ Concept
The name was classified as a concept name.
Definition Sema.h:585
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
DeducedKind
Definition TypeBase.h:1811
@ Deduced
The normal deduced case.
Definition TypeBase.h:1818
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
@ DeducedAsPack
Same as above, but additionally this represents a case where the deduced entity itself is a pack.
Definition TypeBase.h:1834
@ DeducedAsDependent
This is a special case where the initializer is dependent, so we can't deduce a type yet.
Definition TypeBase.h:1828
@ 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:310
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:316
@ TPOC_Other
Partial ordering of function templates in other contexts, e.g., taking the address of a function temp...
Definition Template.h:321
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:312
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:374
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:424
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:419
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:422
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:395
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:381
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:417
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:426
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:414
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:384
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:378
@ Success
Template argument deduction was successful.
Definition Sema.h:376
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:398
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:387
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:401
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:390
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:411
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:428
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:405
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:408
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:840
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:845
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6004
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:5444
Extra information about a function prototype.
Definition TypeBase.h:5470
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5475
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition Sema.h:12098
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition Sema.h:12094
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition Sema.h:12087
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition Sema.h:12084
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition Sema.h:12084
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13230
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13237
A stack object to be created when performing template instantiation.
Definition Sema.h:13403
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13556
brief A function argument from which we performed template argument
Definition Sema.h:12719
Location information for a TemplateArgument.
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)