clang 22.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,
125 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
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
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:
176 assert(
177 !Template || isa<NonTypeTemplateParmDecl>(Template) ||
178 (isa<TemplateTemplateParmDecl>(Template) &&
179 (cast<TemplateTemplateParmDecl>(Template)->templateParameterKind() ==
181 cast<TemplateTemplateParmDecl>(Template)->templateParameterKind() ==
183 }
184
186 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
187 return NTTP->getType();
191 }
192
193 unsigned getDepth() const {
194 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
195 return NTTP->getDepth();
196 return getTemplate()->getDepth();
197 }
198
199 unsigned getIndex() const {
200 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
201 return NTTP->getIndex();
202 return getTemplate()->getIndex();
203 }
204
206 return cast<TemplateTemplateParmDecl>(Template);
207 }
208
210 return cast<NonTypeTemplateParmDecl>(Template);
211 }
212
214 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
215 return const_cast<NonTypeTemplateParmDecl *>(NTTP);
216 return const_cast<TemplateTemplateParmDecl *>(getTemplate());
217 }
218
220 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
221 return NTTP->isExpandedParameterPack();
223 }
224
226 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Template))
227 return NTTP->getLocation();
228 return getTemplate()->getLocation();
229 }
230
231 operator bool() const { return Template; }
232
233private:
234 const NamedDecl *Template;
235};
236
237/// If the given expression is of a form that permits the deduction
238/// of a non-type template parameter, return the declaration of that
239/// non-type template parameter.
241getDeducedNTTParameterFromExpr(const Expr *E, unsigned Depth) {
242 // If we are within an alias template, the expression may have undergone
243 // any number of parameter substitutions already.
245 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
246 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
247 if (NTTP->getDepth() == Depth)
248 return NTTP;
249
250 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E);
251 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
252 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
253
254 if (TTP->getDepth() == Depth)
255 return TTP;
256 }
257 }
258 return nullptr;
259}
260
264}
265
266/// Determine whether two declaration pointers refer to the same
267/// declaration.
268static bool isSameDeclaration(Decl *X, Decl *Y) {
269 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
270 X = NX->getUnderlyingDecl();
271 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
272 Y = NY->getUnderlyingDecl();
273
274 return X->getCanonicalDecl() == Y->getCanonicalDecl();
275}
276
277/// Verify that the given, deduced template arguments are compatible.
278///
279/// \returns The deduced template argument, or a NULL template argument if
280/// the deduced template arguments were incompatible.
285 bool AggregateCandidateDeduction = false) {
286 // We have no deduction for one or both of the arguments; they're compatible.
287 if (X.isNull())
288 return Y;
289 if (Y.isNull())
290 return X;
291
292 // If we have two non-type template argument values deduced for the same
293 // parameter, they must both match the type of the parameter, and thus must
294 // match each other's type. As we're only keeping one of them, we must check
295 // for that now. The exception is that if either was deduced from an array
296 // bound, the type is permitted to differ.
297 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
298 QualType XType = X.getNonTypeTemplateArgumentType();
299 if (!XType.isNull()) {
301 if (YType.isNull() || !Context.hasSameType(XType, YType))
303 }
304 }
305
306 switch (X.getKind()) {
308 llvm_unreachable("Non-deduced template arguments handled above");
309
311 // If two template type arguments have the same type, they're compatible.
312 QualType TX = X.getAsType(), TY = Y.getAsType();
313 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
314 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
315 X.wasDeducedFromArrayBound() ||
317
318 // If one of the two arguments was deduced from an array bound, the other
319 // supersedes it.
320 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
321 return X.wasDeducedFromArrayBound() ? Y : X;
322
323 // The arguments are not compatible.
325 }
326
328 // If we deduced a constant in one case and either a dependent expression or
329 // declaration in another case, keep the integral constant.
330 // If both are integral constants with the same value, keep that value.
334 llvm::APSInt::isSameValue(X.getAsIntegral(), Y.getAsIntegral())))
335 return X.wasDeducedFromArrayBound() ? Y : X;
336
337 // All other combinations are incompatible.
339
341 // If we deduced a value and a dependent expression, keep the value.
344 X.structurallyEquals(Y)))
345 return X;
346
347 // All other combinations are incompatible.
349
352 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
353 return X;
354
355 // All other combinations are incompatible.
357
360 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
362 return X;
363
364 // All other combinations are incompatible.
366
369 return checkDeducedTemplateArguments(Context, Y, X);
370
371 // Compare the expressions for equality
372 llvm::FoldingSetNodeID ID1, ID2;
373 X.getAsExpr()->Profile(ID1, Context, true);
374 Y.getAsExpr()->Profile(ID2, Context, true);
375 if (ID1 == ID2)
376 return X.wasDeducedFromArrayBound() ? Y : X;
377
378 // Differing dependent expressions are incompatible.
380 }
381
383 assert(!X.wasDeducedFromArrayBound());
384
385 // If we deduced a declaration and a dependent expression, keep the
386 // declaration.
388 return X;
389
390 // If we deduced a declaration and an integral constant, keep the
391 // integral constant and whichever type did not come from an array
392 // bound.
395 return TemplateArgument(Context, Y.getAsIntegral(),
396 X.getParamTypeForDecl());
397 return Y;
398 }
399
400 // If we deduced two declarations, make sure that they refer to the
401 // same declaration.
403 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
404 return X;
405
406 // All other combinations are incompatible.
408
410 // If we deduced a null pointer and a dependent expression, keep the
411 // null pointer.
414 X.getNullPtrType(), Y.getAsExpr()->getType()),
415 true);
416
417 // If we deduced a null pointer and an integral constant, keep the
418 // integral constant.
420 return Y;
421
422 // If we deduced two null pointers, they are the same.
424 return TemplateArgument(
425 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
426 true);
427
428 // All other combinations are incompatible.
430
432 if (Y.getKind() != TemplateArgument::Pack ||
433 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
435
438 XA = X.pack_begin(),
439 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
440 XA != XAEnd; ++XA) {
441 if (YA != YAEnd) {
443 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
445 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
447 NewPack.push_back(Merged);
448 ++YA;
449 } else {
450 NewPack.push_back(*XA);
451 }
452 }
453
455 TemplateArgument::CreatePackCopy(Context, NewPack),
456 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
457 }
458 }
459
460 llvm_unreachable("Invalid TemplateArgument Kind!");
461}
462
463/// Deduce the value of the given non-type template parameter
464/// as the given deduced template argument. All non-type template parameter
465/// deduction is funneled through here.
469 const DeducedTemplateArgument &NewDeduced,
470 QualType ValueType, TemplateDeductionInfo &Info,
471 bool PartialOrdering,
473 bool *HasDeducedAnyParam) {
474 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
475 "deducing non-type template argument with wrong depth");
476
478 S.Context, Deduced[NTTP.getIndex()], NewDeduced);
479 if (Result.isNull()) {
480 Info.Param = NTTP.asTemplateParam();
481 Info.FirstArg = Deduced[NTTP.getIndex()];
482 Info.SecondArg = NewDeduced;
483 return TemplateDeductionResult::Inconsistent;
484 }
485 Deduced[NTTP.getIndex()] = Result;
486 if (!S.getLangOpts().CPlusPlus17)
487 return TemplateDeductionResult::Success;
488
489 if (NTTP.isExpandedParameterPack())
490 // FIXME: We may still need to deduce parts of the type here! But we
491 // don't have any way to find which slice of the type to use, and the
492 // type stored on the NTTP itself is nonsense. Perhaps the type of an
493 // expanded NTTP should be a pack expansion type?
494 return TemplateDeductionResult::Success;
495
496 // Get the type of the parameter for deduction. If it's a (dependent) array
497 // or function type, we will not have decayed it yet, so do that now.
498 QualType ParamType = S.Context.getAdjustedParameterType(NTTP.getType());
499 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
500 ParamType = Expansion->getPattern();
501
502 // FIXME: It's not clear how deduction of a parameter of reference
503 // type from an argument (of non-reference type) should be performed.
504 // For now, we just make the argument have same reference type as the
505 // parameter.
506 if (ParamType->isReferenceType() && !ValueType->isReferenceType()) {
507 if (ParamType->isRValueReferenceType())
508 ValueType = S.Context.getRValueReferenceType(ValueType);
509 else
510 ValueType = S.Context.getLValueReferenceType(ValueType);
511 }
512
514 S, TemplateParams, ParamType, ValueType, Info, Deduced,
518 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
519}
520
521/// Deduce the value of the given non-type template parameter
522/// from the given integral constant.
524 Sema &S, TemplateParameterList *TemplateParams,
525 NonTypeOrVarTemplateParmDecl NTTP, const llvm::APSInt &Value,
526 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
528 bool *HasDeducedAnyParam) {
530 S, TemplateParams, NTTP,
532 DeducedFromArrayBound),
533 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
534}
535
536/// Deduce the value of the given non-type template parameter
537/// from the given null pointer template argument type.
541 QualType NullPtrType, TemplateDeductionInfo &Info,
542 bool PartialOrdering,
544 bool *HasDeducedAnyParam) {
547 NTTP.getLocation()),
548 NullPtrType,
549 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
550 : CK_NullToPointer)
551 .get();
553 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
554 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
555}
556
557/// Deduce the value of the given non-type template parameter
558/// from the given type- or value-dependent expression.
559///
560/// \returns true if deduction succeeded, false otherwise.
566 bool *HasDeducedAnyParam) {
568 S, TemplateParams, NTTP, TemplateArgument(Value, /*IsCanonical=*/false),
569 Value->getType(), Info, PartialOrdering, Deduced, HasDeducedAnyParam);
570}
571
572/// Deduce the value of the given non-type template parameter
573/// from the given declaration.
574///
575/// \returns true if deduction succeeded, false otherwise.
580 bool PartialOrdering,
582 bool *HasDeducedAnyParam) {
585 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
586 PartialOrdering, Deduced, HasDeducedAnyParam);
587}
588
590 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
594 bool *HasDeducedAnyParam) {
595 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
596 if (!ParamDecl) {
597 // The parameter type is dependent and is not a template template parameter,
598 // so there is nothing that we can deduce.
599 return TemplateDeductionResult::Success;
600 }
601
602 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
603 // If we're not deducing at this depth, there's nothing to deduce.
604 if (TempParam->getDepth() != Info.getDeducedDepth())
605 return TemplateDeductionResult::Success;
606
607 ArrayRef<NamedDecl *> Params =
608 ParamDecl->getTemplateParameters()->asArray();
609 unsigned StartPos = 0;
610 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
611 I < E; ++I) {
612 if (Params[I]->isParameterPack()) {
613 StartPos = DefaultArguments.size();
614 break;
615 }
616 StartPos = I + 1;
617 }
618
619 // Provisional resolution for CWG2398: If Arg names a template
620 // specialization, then we deduce a synthesized template name
621 // based on A, but using the TS's extra arguments, relative to P, as
622 // defaults.
623 DeducedTemplateArgument NewDeduced =
626 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
627 : Arg;
628
630 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
631 if (Result.isNull()) {
632 Info.Param = TempParam;
633 Info.FirstArg = Deduced[TempParam->getIndex()];
634 Info.SecondArg = NewDeduced;
635 return TemplateDeductionResult::Inconsistent;
636 }
637
638 Deduced[TempParam->getIndex()] = Result;
639 if (HasDeducedAnyParam)
640 *HasDeducedAnyParam = true;
641 return TemplateDeductionResult::Success;
642 }
643
644 // Verify that the two template names are equivalent.
646 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
647 return TemplateDeductionResult::Success;
648
649 // Mismatch of non-dependent template parameter to argument.
650 Info.FirstArg = TemplateArgument(Param);
651 Info.SecondArg = TemplateArgument(Arg);
652 return TemplateDeductionResult::NonDeducedMismatch;
653}
654
655/// Deduce the template arguments by comparing the template parameter
656/// type (which is a template-id) with the template argument type.
657///
658/// \param S the Sema
659///
660/// \param TemplateParams the template parameters that we are deducing
661///
662/// \param P the parameter type
663///
664/// \param A the argument type
665///
666/// \param Info information about the template argument deduction itself
667///
668/// \param Deduced the deduced template arguments
669///
670/// \returns the result of template argument deduction so far. Note that a
671/// "success" result means that template argument deduction has not yet failed,
672/// but it may still fail, later, for other reasons.
673
675 const TemplateSpecializationType *LastTST = nullptr;
676 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
677 const TemplateSpecializationType *TST =
679 if (!TST)
680 return LastTST;
681 if (!TST->isSugared())
682 return TST;
683 LastTST = TST;
684 T = TST->desugar().getTypePtr();
685 }
686}
687
690 const QualType P, QualType A,
693 bool *HasDeducedAnyParam) {
694 TemplateName TNP;
696 if (isa<TemplateSpecializationType>(P.getCanonicalType())) {
698 TNP = TP->getTemplateName();
699 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
700 // arguments.
701 PResolved =
702 TP->castAsCanonical<TemplateSpecializationType>()->template_arguments();
703 } else {
704 const auto *TT = P->castAs<InjectedClassNameType>();
705 TNP = TT->getTemplateName(S.Context);
706 PResolved = TT->getTemplateArgs(S.Context);
707 }
708
709 // If the parameter is an alias template, there is nothing to deduce.
710 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
711 return TemplateDeductionResult::Success;
712 // Pack-producing templates can only be matched after substitution.
714 return TemplateDeductionResult::Success;
715
716 // Check whether the template argument is a dependent template-id.
717 if (isa<TemplateSpecializationType>(A.getCanonicalType())) {
719 TemplateName TNA = SA->getTemplateName();
720
721 // If the argument is an alias template, there is nothing to deduce.
722 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
723 return TemplateDeductionResult::Success;
724
725 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
726 // arguments.
730 ->template_arguments();
731
732 // Perform template argument deduction for the template name.
733 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
734 /*DefaultArguments=*/AResolved,
735 PartialOrdering, Deduced,
736 HasDeducedAnyParam);
737 Result != TemplateDeductionResult::Success)
738 return Result;
739
740 // Perform template argument deduction on each template
741 // argument. Ignore any missing/extra arguments, since they could be
742 // filled in by default arguments.
744 S, TemplateParams, PResolved, AResolved, Info, Deduced,
745 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
746 PackFold::ParameterToArgument, HasDeducedAnyParam);
747 }
748
749 // If the argument type is a class template specialization, we
750 // perform template argument deduction using its template
751 // arguments.
752 const auto *TA = A->getAs<TagType>();
753 TemplateName TNA;
754 if (TA) {
755 // FIXME: Can't use the template arguments from this TST, as they are not
756 // resolved.
757 if (const auto *TST = A->getAsNonAliasTemplateSpecializationType())
758 TNA = TST->getTemplateName();
759 else
760 TNA = TA->getTemplateName(S.Context);
761 }
762 if (TNA.isNull()) {
764 Info.SecondArg = TemplateArgument(A);
765 return TemplateDeductionResult::NonDeducedMismatch;
766 }
767
768 ArrayRef<TemplateArgument> AResolved = TA->getTemplateArgs(S.Context);
769 // Perform template argument deduction for the template name.
770 if (auto Result =
771 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
772 /*DefaultArguments=*/AResolved,
773 PartialOrdering, Deduced, HasDeducedAnyParam);
774 Result != TemplateDeductionResult::Success)
775 return Result;
776
777 // Perform template argument deduction for the template arguments.
779 S, TemplateParams, PResolved, AResolved, Info, Deduced,
780 /*NumberOfArgumentsMustMatch=*/true, PartialOrdering,
781 PackFold::ParameterToArgument, HasDeducedAnyParam);
782}
783
785 assert(T->isCanonicalUnqualified());
786
787 switch (T->getTypeClass()) {
788 case Type::TypeOfExpr:
789 case Type::TypeOf:
790 case Type::DependentName:
791 case Type::Decltype:
792 case Type::PackIndexing:
793 case Type::UnresolvedUsing:
794 case Type::TemplateTypeParm:
795 case Type::Auto:
796 return true;
797
798 case Type::ConstantArray:
799 case Type::IncompleteArray:
800 case Type::VariableArray:
801 case Type::DependentSizedArray:
803 cast<ArrayType>(T)->getElementType().getTypePtr());
804
805 default:
806 return false;
807 }
808}
809
810/// Determines whether the given type is an opaque type that
811/// might be more qualified when instantiated.
815}
816
817/// Helper function to build a TemplateParameter when we don't
818/// know its type statically.
820 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
821 return TemplateParameter(TTP);
822 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
823 return TemplateParameter(NTTP);
824
825 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
826}
827
828/// A pack that we're currently deducing.
830 // The index of the pack.
831 unsigned Index;
832
833 // The old value of the pack before we started deducing it.
835
836 // A deferred value of this pack from an inner deduction, that couldn't be
837 // deduced because this deduction hadn't happened yet.
839
840 // The new value of the pack.
842
843 // The outer deduction for this pack, if any.
844 DeducedPack *Outer = nullptr;
845
846 DeducedPack(unsigned Index) : Index(Index) {}
847};
848
849namespace {
850
851/// A scope in which we're performing pack deduction.
852class PackDeductionScope {
853public:
854 /// Prepare to deduce the packs named within Pattern.
855 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
856 /// just checking a previous deduction of the pack.
857 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
860 bool DeducePackIfNotAlreadyDeduced = false,
861 bool FinishingDeduction = false)
862 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
863 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
864 FinishingDeduction(FinishingDeduction) {
865 unsigned NumNamedPacks = addPacks(Pattern);
866 finishConstruction(NumNamedPacks);
867 }
868
869 /// Prepare to directly deduce arguments of the parameter with index \p Index.
870 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
872 TemplateDeductionInfo &Info, unsigned Index)
873 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
874 addPack(Index);
875 finishConstruction(1);
876 }
877
878private:
879 void addPack(unsigned Index) {
880 // Save the deduced template argument for the parameter pack expanded
881 // by this pack expansion, then clear out the deduction.
882 DeducedFromEarlierParameter = !Deduced[Index].isNull();
883 DeducedPack Pack(Index);
884 if (!FinishingDeduction) {
885 Pack.Saved = Deduced[Index];
886 Deduced[Index] = TemplateArgument();
887 }
888
889 // FIXME: What if we encounter multiple packs with different numbers of
890 // pre-expanded expansions? (This should already have been diagnosed
891 // during substitution.)
892 if (UnsignedOrNone ExpandedPackExpansions =
893 getExpandedPackSize(TemplateParams->getParam(Index)))
894 FixedNumExpansions = ExpandedPackExpansions;
895
896 Packs.push_back(Pack);
897 }
898
899 unsigned addPacks(TemplateArgument Pattern) {
900 // Compute the set of template parameter indices that correspond to
901 // parameter packs expanded by the pack expansion.
902 llvm::SmallBitVector SawIndices(TemplateParams->size());
904
905 auto AddPack = [&](unsigned Index) {
906 if (SawIndices[Index])
907 return;
908 SawIndices[Index] = true;
909 addPack(Index);
910
911 // Deducing a parameter pack that is a pack expansion also constrains the
912 // packs appearing in that parameter to have the same deduced arity. Also,
913 // in C++17 onwards, deducing a non-type template parameter deduces its
914 // type, so we need to collect the pending deduced values for those packs.
915 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
916 TemplateParams->getParam(Index))) {
917 if (!NTTP->isExpandedParameterPack())
918 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
919 // context, however it is not yet resolved.
920 if (auto *Expansion = dyn_cast<PackExpansionType>(
921 S.Context.getUnconstrainedType(NTTP->getType())))
922 ExtraDeductions.push_back(Expansion->getPattern());
923 }
924 // FIXME: Also collect the unexpanded packs in any type and template
925 // parameter packs that are pack expansions.
926 };
927
928 auto Collect = [&](TemplateArgument Pattern) {
930 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
931 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
932 unsigned Depth, Index;
933 if (auto DI = getDepthAndIndex(Unexpanded[I]))
934 std::tie(Depth, Index) = *DI;
935 else
936 continue;
937
938 if (Depth == Info.getDeducedDepth())
939 AddPack(Index);
940 }
941 };
942
943 // Look for unexpanded packs in the pattern.
944 Collect(Pattern);
945
946 unsigned NumNamedPacks = Packs.size();
947
948 // Also look for unexpanded packs that are indirectly deduced by deducing
949 // the sizes of the packs in this pattern.
950 while (!ExtraDeductions.empty())
951 Collect(ExtraDeductions.pop_back_val());
952
953 return NumNamedPacks;
954 }
955
956 void finishConstruction(unsigned NumNamedPacks) {
957 // Dig out the partially-substituted pack, if there is one.
958 const TemplateArgument *PartialPackArgs = nullptr;
959 unsigned NumPartialPackArgs = 0;
960 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
961 if (auto *Scope = S.CurrentInstantiationScope)
962 if (auto *Partial = Scope->getPartiallySubstitutedPack(
963 &PartialPackArgs, &NumPartialPackArgs))
964 PartialPackDepthIndex = getDepthAndIndex(Partial);
965
966 // This pack expansion will have been partially or fully expanded if
967 // it only names explicitly-specified parameter packs (including the
968 // partially-substituted one, if any).
969 bool IsExpanded = true;
970 for (unsigned I = 0; I != NumNamedPacks; ++I) {
971 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
972 IsExpanded = false;
973 IsPartiallyExpanded = false;
974 break;
975 }
976 if (PartialPackDepthIndex ==
977 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
978 IsPartiallyExpanded = true;
979 }
980 }
981
982 // Skip over the pack elements that were expanded into separate arguments.
983 // If we partially expanded, this is the number of partial arguments.
984 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
985 // https://github.com/llvm/llvm-project/issues/100095
986 if (IsPartiallyExpanded)
987 PackElements += NumPartialPackArgs;
988 else if (IsExpanded && FixedNumExpansions)
989 PackElements += *FixedNumExpansions;
990
991 for (auto &Pack : Packs) {
992 if (Info.PendingDeducedPacks.size() > Pack.Index)
993 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
994 else
995 Info.PendingDeducedPacks.resize(Pack.Index + 1);
996 Info.PendingDeducedPacks[Pack.Index] = &Pack;
997
998 if (PartialPackDepthIndex ==
999 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
1000 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
1001 // We pre-populate the deduced value of the partially-substituted
1002 // pack with the specified value. This is not entirely correct: the
1003 // value is supposed to have been substituted, not deduced, but the
1004 // cases where this is observable require an exact type match anyway.
1005 //
1006 // FIXME: If we could represent a "depth i, index j, pack elem k"
1007 // parameter, we could substitute the partially-substituted pack
1008 // everywhere and avoid this.
1009 if (!FinishingDeduction && !IsPartiallyExpanded)
1010 Deduced[Pack.Index] = Pack.New[PackElements];
1011 }
1012 }
1013 }
1014
1015public:
1016 ~PackDeductionScope() {
1017 for (auto &Pack : Packs)
1018 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
1019 }
1020
1021 // Return the size of the saved packs if all of them has the same size.
1022 UnsignedOrNone getSavedPackSizeIfAllEqual() const {
1023 unsigned PackSize = Packs[0].Saved.pack_size();
1024
1025 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
1026 return P.Saved.pack_size() == PackSize;
1027 }))
1028 return PackSize;
1029 return std::nullopt;
1030 }
1031
1032 /// Determine whether this pack has already been deduced from a previous
1033 /// argument.
1034 bool isDeducedFromEarlierParameter() const {
1035 return DeducedFromEarlierParameter;
1036 }
1037
1038 /// Determine whether this pack has already been partially expanded into a
1039 /// sequence of (prior) function parameters / template arguments.
1040 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
1041
1042 /// Determine whether this pack expansion scope has a known, fixed arity.
1043 /// This happens if it involves a pack from an outer template that has
1044 /// (notionally) already been expanded.
1045 bool hasFixedArity() { return static_cast<bool>(FixedNumExpansions); }
1046
1047 /// Determine whether the next element of the argument is still part of this
1048 /// pack. This is the case unless the pack is already expanded to a fixed
1049 /// length.
1050 bool hasNextElement() {
1051 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
1052 }
1053
1054 /// Move to deducing the next element in each pack that is being deduced.
1055 void nextPackElement() {
1056 // Capture the deduced template arguments for each parameter pack expanded
1057 // by this pack expansion, add them to the list of arguments we've deduced
1058 // for that pack, then clear out the deduced argument.
1059 if (!FinishingDeduction) {
1060 for (auto &Pack : Packs) {
1061 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1062 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1063 while (Pack.New.size() < PackElements)
1064 Pack.New.push_back(DeducedTemplateArgument());
1065 if (Pack.New.size() == PackElements)
1066 Pack.New.push_back(DeducedArg);
1067 else
1068 Pack.New[PackElements] = DeducedArg;
1069 DeducedArg = Pack.New.size() > PackElements + 1
1070 ? Pack.New[PackElements + 1]
1072 }
1073 }
1074 }
1075 ++PackElements;
1076 }
1077
1078 /// Finish template argument deduction for a set of argument packs,
1079 /// producing the argument packs and checking for consistency with prior
1080 /// deductions.
1081 TemplateDeductionResult finish() {
1082 if (FinishingDeduction)
1083 return TemplateDeductionResult::Success;
1084 // Build argument packs for each of the parameter packs expanded by this
1085 // pack expansion.
1086 for (auto &Pack : Packs) {
1087 // Put back the old value for this pack.
1088 if (!FinishingDeduction)
1089 Deduced[Pack.Index] = Pack.Saved;
1090
1091 // Always make sure the size of this pack is correct, even if we didn't
1092 // deduce any values for it.
1093 //
1094 // FIXME: This isn't required by the normative wording, but substitution
1095 // and post-substitution checking will always fail if the arity of any
1096 // pack is not equal to the number of elements we processed. (Either that
1097 // or something else has gone *very* wrong.) We're permitted to skip any
1098 // hard errors from those follow-on steps by the intent (but not the
1099 // wording) of C++ [temp.inst]p8:
1100 //
1101 // If the function selected by overload resolution can be determined
1102 // without instantiating a class template definition, it is unspecified
1103 // whether that instantiation actually takes place
1104 Pack.New.resize(PackElements);
1105
1106 // Build or find a new value for this pack.
1108 if (Pack.New.empty()) {
1109 // If we deduced an empty argument pack, create it now.
1111 } else {
1112 TemplateArgument *ArgumentPack =
1113 new (S.Context) TemplateArgument[Pack.New.size()];
1114 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1115 NewPack = DeducedTemplateArgument(
1116 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1117 // FIXME: This is wrong, it's possible that some pack elements are
1118 // deduced from an array bound and others are not:
1119 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1120 // g({1, 2, 3}, {{}, {}});
1121 // ... should deduce T = {int, size_t (from array bound)}.
1122 Pack.New[0].wasDeducedFromArrayBound());
1123 }
1124
1125 // Pick where we're going to put the merged pack.
1127 if (Pack.Outer) {
1128 if (Pack.Outer->DeferredDeduction.isNull()) {
1129 // Defer checking this pack until we have a complete pack to compare
1130 // it against.
1131 Pack.Outer->DeferredDeduction = NewPack;
1132 continue;
1133 }
1134 Loc = &Pack.Outer->DeferredDeduction;
1135 } else {
1136 Loc = &Deduced[Pack.Index];
1137 }
1138
1139 // Check the new pack matches any previous value.
1140 DeducedTemplateArgument OldPack = *Loc;
1142 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1143
1144 Info.AggregateDeductionCandidateHasMismatchedArity =
1145 OldPack.getKind() == TemplateArgument::Pack &&
1146 NewPack.getKind() == TemplateArgument::Pack &&
1147 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1148
1149 // If we deferred a deduction of this pack, check that one now too.
1150 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1151 OldPack = Result;
1152 NewPack = Pack.DeferredDeduction;
1153 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1154 }
1155
1156 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1157 if (Result.isNull()) {
1158 Info.Param = makeTemplateParameter(Param);
1159 Info.FirstArg = OldPack;
1160 Info.SecondArg = NewPack;
1161 return TemplateDeductionResult::Inconsistent;
1162 }
1163
1164 // If we have a pre-expanded pack and we didn't deduce enough elements
1165 // for it, fail deduction.
1166 if (UnsignedOrNone Expansions = getExpandedPackSize(Param)) {
1167 if (*Expansions != PackElements) {
1168 Info.Param = makeTemplateParameter(Param);
1169 Info.FirstArg = Result;
1170 return TemplateDeductionResult::IncompletePack;
1171 }
1172 }
1173
1174 *Loc = Result;
1175 }
1176
1177 return TemplateDeductionResult::Success;
1178 }
1179
1180private:
1181 Sema &S;
1182 TemplateParameterList *TemplateParams;
1185 unsigned PackElements = 0;
1186 bool IsPartiallyExpanded = false;
1187 bool DeducePackIfNotAlreadyDeduced = false;
1188 bool DeducedFromEarlierParameter = false;
1189 bool FinishingDeduction = false;
1190 /// The number of expansions, if we have a fully-expanded pack in this scope.
1191 UnsignedOrNone FixedNumExpansions = std::nullopt;
1192
1194};
1195
1196} // namespace
1197
1198template <class T>
1200 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1203 bool FinishingDeduction, T &&DeductFunc) {
1204 // C++0x [temp.deduct.type]p10:
1205 // Similarly, if P has a form that contains (T), then each parameter type
1206 // Pi of the respective parameter-type- list of P is compared with the
1207 // corresponding parameter type Ai of the corresponding parameter-type-list
1208 // of A. [...]
1209 unsigned ArgIdx = 0, ParamIdx = 0;
1210 for (; ParamIdx != Params.size(); ++ParamIdx) {
1211 // Check argument types.
1212 const PackExpansionType *Expansion
1213 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1214 if (!Expansion) {
1215 // Simple case: compare the parameter and argument types at this point.
1216
1217 // Make sure we have an argument.
1218 if (ArgIdx >= Args.size())
1219 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1220
1221 if (isa<PackExpansionType>(Args[ArgIdx])) {
1222 // C++0x [temp.deduct.type]p22:
1223 // If the original function parameter associated with A is a function
1224 // parameter pack and the function parameter associated with P is not
1225 // a function parameter pack, then template argument deduction fails.
1226 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1227 }
1228
1229 if (TemplateDeductionResult Result =
1230 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1231 Params[ParamIdx].getUnqualifiedType(),
1232 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1233 Result != TemplateDeductionResult::Success)
1234 return Result;
1235
1236 ++ArgIdx;
1237 continue;
1238 }
1239
1240 // C++0x [temp.deduct.type]p10:
1241 // If the parameter-declaration corresponding to Pi is a function
1242 // parameter pack, then the type of its declarator- id is compared with
1243 // each remaining parameter type in the parameter-type-list of A. Each
1244 // comparison deduces template arguments for subsequent positions in the
1245 // template parameter packs expanded by the function parameter pack.
1246
1247 QualType Pattern = Expansion->getPattern();
1248 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1249 /*DeducePackIfNotAlreadyDeduced=*/false,
1250 FinishingDeduction);
1251
1252 // A pack scope with fixed arity is not really a pack any more, so is not
1253 // a non-deduced context.
1254 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1255 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1256 // Deduce template arguments from the pattern.
1257 if (TemplateDeductionResult Result = DeductFunc(
1258 S, TemplateParams, ParamIdx, ArgIdx,
1259 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1260 Info, Deduced, POK);
1261 Result != TemplateDeductionResult::Success)
1262 return Result;
1263 PackScope.nextPackElement();
1264 }
1265 } else {
1266 // C++0x [temp.deduct.type]p5:
1267 // The non-deduced contexts are:
1268 // - A function parameter pack that does not occur at the end of the
1269 // parameter-declaration-clause.
1270 //
1271 // FIXME: There is no wording to say what we should do in this case. We
1272 // choose to resolve this by applying the same rule that is applied for a
1273 // function call: that is, deduce all contained packs to their
1274 // explicitly-specified values (or to <> if there is no such value).
1275 //
1276 // This is seemingly-arbitrarily different from the case of a template-id
1277 // with a non-trailing pack-expansion in its arguments, which renders the
1278 // entire template-argument-list a non-deduced context.
1279
1280 // If the parameter type contains an explicitly-specified pack that we
1281 // could not expand, skip the number of parameters notionally created
1282 // by the expansion.
1283 UnsignedOrNone NumExpansions = Expansion->getNumExpansions();
1284 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1285 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1286 ++I, ++ArgIdx)
1287 PackScope.nextPackElement();
1288 }
1289 }
1290
1291 // Build argument packs for each of the parameter packs expanded by this
1292 // pack expansion.
1293 if (auto Result = PackScope.finish();
1294 Result != TemplateDeductionResult::Success)
1295 return Result;
1296 }
1297
1298 // DR692, DR1395
1299 // C++0x [temp.deduct.type]p10:
1300 // If the parameter-declaration corresponding to P_i ...
1301 // During partial ordering, if Ai was originally a function parameter pack:
1302 // - if P does not contain a function parameter type corresponding to Ai then
1303 // Ai is ignored;
1304 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1305 isa<PackExpansionType>(Args[ArgIdx]))
1306 return TemplateDeductionResult::Success;
1307
1308 // Make sure we don't have any extra arguments.
1309 if (ArgIdx < Args.size())
1310 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1311
1312 return TemplateDeductionResult::Success;
1313}
1314
1315/// Deduce the template arguments by comparing the list of parameter
1316/// types to the list of argument types, as in the parameter-type-lists of
1317/// function types (C++ [temp.deduct.type]p10).
1318///
1319/// \param S The semantic analysis object within which we are deducing
1320///
1321/// \param TemplateParams The template parameters that we are deducing
1322///
1323/// \param Params The list of parameter types
1324///
1325/// \param Args The list of argument types
1326///
1327/// \param Info information about the template argument deduction itself
1328///
1329/// \param Deduced the deduced template arguments
1330///
1331/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1332/// how template argument deduction is performed.
1333///
1334/// \param PartialOrdering If true, we are performing template argument
1335/// deduction for during partial ordering for a call
1336/// (C++0x [temp.deduct.partial]).
1337///
1338/// \param HasDeducedAnyParam If set, the object pointed at will indicate
1339/// whether any template parameter was deduced.
1340///
1341/// \param HasDeducedParam If set, the bit vector will be used to represent
1342/// which template parameters were deduced, in order.
1343///
1344/// \returns the result of template argument deduction so far. Note that a
1345/// "success" result means that template argument deduction has not yet failed,
1346/// but it may still fail, later, for other reasons.
1348 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1350 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1351 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1352 llvm::SmallBitVector *HasDeducedParam) {
1353 return ::DeduceForEachType(
1354 S, TemplateParams, Params, Args, Info, Deduced, POK,
1355 /*FinishingDeduction=*/false,
1356 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1357 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1359 PartialOrderingKind POK) {
1360 bool HasDeducedAnyParamCopy = false;
1362 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1363 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1364 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1365 *HasDeducedAnyParam = true;
1366 if (HasDeducedParam && HasDeducedAnyParamCopy)
1367 (*HasDeducedParam)[ParamIdx] = true;
1368 return TDR;
1369 });
1370}
1371
1372/// Determine whether the parameter has qualifiers that the argument
1373/// lacks. Put another way, determine whether there is no way to add
1374/// a deduced set of qualifiers to the ParamType that would result in
1375/// its qualifiers matching those of the ArgType.
1377 QualType ArgType) {
1378 Qualifiers ParamQs = ParamType.getQualifiers();
1379 Qualifiers ArgQs = ArgType.getQualifiers();
1380
1381 if (ParamQs == ArgQs)
1382 return false;
1383
1384 // Mismatched (but not missing) Objective-C GC attributes.
1385 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1386 ParamQs.hasObjCGCAttr())
1387 return true;
1388
1389 // Mismatched (but not missing) address spaces.
1390 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1391 ParamQs.hasAddressSpace())
1392 return true;
1393
1394 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1395 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1396 ParamQs.hasObjCLifetime())
1397 return true;
1398
1399 // CVR qualifiers inconsistent or a superset.
1400 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1401}
1402
1404 const FunctionType *PF = P->getAs<FunctionType>(),
1405 *AF = A->getAs<FunctionType>();
1406
1407 // Just compare if not functions.
1408 if (!PF || !AF)
1409 return Context.hasSameType(P, A);
1410
1411 // Noreturn and noexcept adjustment.
1412 if (QualType AdjustedParam; TryFunctionConversion(P, A, AdjustedParam))
1413 P = AdjustedParam;
1414
1415 // FIXME: Compatible calling conventions.
1417}
1418
1419/// Get the index of the first template parameter that was originally from the
1420/// innermost template-parameter-list. This is 0 except when we concatenate
1421/// the template parameter lists of a class template and a constructor template
1422/// when forming an implicit deduction guide.
1424 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1425 if (!Guide || !Guide->isImplicit())
1426 return 0;
1427 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1428}
1429
1430/// Determine whether a type denotes a forwarding reference.
1431static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1432 // C++1z [temp.deduct.call]p3:
1433 // A forwarding reference is an rvalue reference to a cv-unqualified
1434 // template parameter that does not represent a template parameter of a
1435 // class template.
1436 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1437 if (ParamRef->getPointeeType().getQualifiers())
1438 return false;
1439 auto *TypeParm =
1440 ParamRef->getPointeeType()->getAsCanonical<TemplateTypeParmType>();
1441 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1442 }
1443 return false;
1444}
1445
1446/// Attempt to deduce the template arguments by checking the base types
1447/// according to (C++20 [temp.deduct.call] p4b3.
1448///
1449/// \param S the semantic analysis object within which we are deducing.
1450///
1451/// \param RD the top level record object we are deducing against.
1452///
1453/// \param TemplateParams the template parameters that we are deducing.
1454///
1455/// \param P the template specialization parameter type.
1456///
1457/// \param Info information about the template argument deduction itself.
1458///
1459/// \param Deduced the deduced template arguments.
1460///
1461/// \returns the result of template argument deduction with the bases. "invalid"
1462/// means no matches, "success" found a single item, and the
1463/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1466 TemplateParameterList *TemplateParams, QualType P,
1469 bool *HasDeducedAnyParam) {
1470 // C++14 [temp.deduct.call] p4b3:
1471 // If P is a class and P has the form simple-template-id, then the
1472 // transformed A can be a derived class of the deduced A. Likewise if
1473 // P is a pointer to a class of the form simple-template-id, the
1474 // transformed A can be a pointer to a derived class pointed to by the
1475 // deduced A. However, if there is a class C that is a (direct or
1476 // indirect) base class of D and derived (directly or indirectly) from a
1477 // class B and that would be a valid deduced A, the deduced A cannot be
1478 // B or pointer to B, respectively.
1479 //
1480 // These alternatives are considered only if type deduction would
1481 // otherwise fail. If they yield more than one possible deduced A, the
1482 // type deduction fails.
1483
1484 // Use a breadth-first search through the bases to collect the set of
1485 // successful matches. Visited contains the set of nodes we have already
1486 // visited, while ToVisit is our stack of records that we still need to
1487 // visit. Matches contains a list of matches that have yet to be
1488 // disqualified.
1491 // We iterate over this later, so we have to use MapVector to ensure
1492 // determinism.
1493 struct MatchValue {
1495 bool HasDeducedAnyParam;
1496 };
1497 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1498
1499 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1500 for (const auto &Base : RD->bases()) {
1501 QualType T = Base.getType();
1502 assert(T->isRecordType() && "Base class that isn't a record?");
1503 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1504 ToVisit.push_back(T);
1505 }
1506 };
1507
1508 // Set up the loop by adding all the bases.
1509 AddBases(RD);
1510
1511 // Search each path of bases until we either run into a successful match
1512 // (where all bases of it are invalid), or we run out of bases.
1513 while (!ToVisit.empty()) {
1514 QualType NextT = ToVisit.pop_back_val();
1515
1516 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1517 Deduced.end());
1519 bool HasDeducedAnyParamCopy = false;
1521 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1522 &HasDeducedAnyParamCopy);
1523
1524 // If this was a successful deduction, add it to the list of matches,
1525 // otherwise we need to continue searching its bases.
1526 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1528 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1529 else
1530 AddBases(RD);
1531 }
1532
1533 // At this point, 'Matches' contains a list of seemingly valid bases, however
1534 // in the event that we have more than 1 match, it is possible that the base
1535 // of one of the matches might be disqualified for being a base of another
1536 // valid match. We can count on cyclical instantiations being invalid to
1537 // simplify the disqualifications. That is, if A & B are both matches, and B
1538 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1539 if (Matches.size() > 1) {
1540 Visited.clear();
1541 for (const auto &Match : Matches)
1542 AddBases(Match.first);
1543
1544 // We can give up once we have a single item (or have run out of things to
1545 // search) since cyclical inheritance isn't valid.
1546 while (Matches.size() > 1 && !ToVisit.empty()) {
1547 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1548 Matches.erase(RD);
1549
1550 // Always add all bases, since the inheritance tree can contain
1551 // disqualifications for multiple matches.
1552 AddBases(RD);
1553 }
1554 }
1555
1556 if (Matches.empty())
1558 if (Matches.size() > 1)
1560
1561 std::swap(Matches.front().second.Deduced, Deduced);
1562 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1563 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1564 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1566}
1567
1568/// When propagating a partial ordering kind into a NonCall context,
1569/// this is used to downgrade a 'Call' into a 'NonCall', so that
1570/// the kind still reflects whether we are in a partial ordering context.
1573 return std::min(POK, PartialOrderingKind::NonCall);
1574}
1575
1576/// Deduce the template arguments by comparing the parameter type and
1577/// the argument type (C++ [temp.deduct.type]).
1578///
1579/// \param S the semantic analysis object within which we are deducing
1580///
1581/// \param TemplateParams the template parameters that we are deducing
1582///
1583/// \param P the parameter type
1584///
1585/// \param A the argument type
1586///
1587/// \param Info information about the template argument deduction itself
1588///
1589/// \param Deduced the deduced template arguments
1590///
1591/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1592/// how template argument deduction is performed.
1593///
1594/// \param PartialOrdering Whether we're performing template argument deduction
1595/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1596///
1597/// \returns the result of template argument deduction so far. Note that a
1598/// "success" result means that template argument deduction has not yet failed,
1599/// but it may still fail, later, for other reasons.
1601 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1603 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1604 PartialOrderingKind POK, bool DeducedFromArrayBound,
1605 bool *HasDeducedAnyParam) {
1606
1607 // If the argument type is a pack expansion, look at its pattern.
1608 // This isn't explicitly called out
1609 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1610 A = AExp->getPattern();
1611 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1612
1613 if (POK == PartialOrderingKind::Call) {
1614 // C++11 [temp.deduct.partial]p5:
1615 // Before the partial ordering is done, certain transformations are
1616 // performed on the types used for partial ordering:
1617 // - If P is a reference type, P is replaced by the type referred to.
1618 const ReferenceType *PRef = P->getAs<ReferenceType>();
1619 if (PRef)
1620 P = PRef->getPointeeType();
1621
1622 // - If A is a reference type, A is replaced by the type referred to.
1623 const ReferenceType *ARef = A->getAs<ReferenceType>();
1624 if (ARef)
1625 A = A->getPointeeType();
1626
1627 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1628 // C++11 [temp.deduct.partial]p9:
1629 // If, for a given type, deduction succeeds in both directions (i.e.,
1630 // the types are identical after the transformations above) and both
1631 // P and A were reference types [...]:
1632 // - if [one type] was an lvalue reference and [the other type] was
1633 // not, [the other type] is not considered to be at least as
1634 // specialized as [the first type]
1635 // - if [one type] is more cv-qualified than [the other type],
1636 // [the other type] is not considered to be at least as specialized
1637 // as [the first type]
1638 // Objective-C ARC adds:
1639 // - [one type] has non-trivial lifetime, [the other type] has
1640 // __unsafe_unretained lifetime, and the types are otherwise
1641 // identical
1642 //
1643 // A is "considered to be at least as specialized" as P iff deduction
1644 // succeeds, so we model this as a deduction failure. Note that
1645 // [the first type] is P and [the other type] is A here; the standard
1646 // gets this backwards.
1647 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1648 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1649 PQuals.isStrictSupersetOf(AQuals) ||
1650 (PQuals.hasNonTrivialObjCLifetime() &&
1651 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1652 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1653 Info.FirstArg = TemplateArgument(P);
1654 Info.SecondArg = TemplateArgument(A);
1656 }
1657 }
1658 Qualifiers DiscardedQuals;
1659 // C++11 [temp.deduct.partial]p7:
1660 // Remove any top-level cv-qualifiers:
1661 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1662 // version of P.
1663 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1664 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1665 // version of A.
1666 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1667 } else {
1668 // C++0x [temp.deduct.call]p4 bullet 1:
1669 // - If the original P is a reference type, the deduced A (i.e., the type
1670 // referred to by the reference) can be more cv-qualified than the
1671 // transformed A.
1672 if (TDF & TDF_ParamWithReferenceType) {
1673 Qualifiers Quals;
1674 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1676 P = S.Context.getQualifiedType(UnqualP, Quals);
1677 }
1678
1679 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1680 // C++0x [temp.deduct.type]p10:
1681 // If P and A are function types that originated from deduction when
1682 // taking the address of a function template (14.8.2.2) or when deducing
1683 // template arguments from a function declaration (14.8.2.6) and Pi and
1684 // Ai are parameters of the top-level parameter-type-list of P and A,
1685 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1686 // is an lvalue reference, in
1687 // which case the type of Pi is changed to be the template parameter
1688 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1689 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1690 // deduced as X&. - end note ]
1691 TDF &= ~TDF_TopLevelParameterTypeList;
1692 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1694 P = P->getPointeeType();
1695 }
1696 }
1697
1698 // C++ [temp.deduct.type]p9:
1699 // A template type argument T, a template template argument TT or a
1700 // template non-type argument i can be deduced if P and A have one of
1701 // the following forms:
1702 //
1703 // T
1704 // cv-list T
1705 if (const auto *TTP = P->getAsCanonical<TemplateTypeParmType>()) {
1706 // Just skip any attempts to deduce from a placeholder type or a parameter
1707 // at a different depth.
1708 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1710
1711 unsigned Index = TTP->getIndex();
1712
1713 // If the argument type is an array type, move the qualifiers up to the
1714 // top level, so they can be matched with the qualifiers on the parameter.
1715 if (A->isArrayType()) {
1716 Qualifiers Quals;
1717 A = S.Context.getUnqualifiedArrayType(A, Quals);
1718 if (Quals)
1719 A = S.Context.getQualifiedType(A, Quals);
1720 }
1721
1722 // The argument type can not be less qualified than the parameter
1723 // type.
1724 if (!(TDF & TDF_IgnoreQualifiers) &&
1726 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1727 Info.FirstArg = TemplateArgument(P);
1728 Info.SecondArg = TemplateArgument(A);
1730 }
1731
1732 // Do not match a function type with a cv-qualified type.
1733 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1734 if (A->isFunctionType() && P.hasQualifiers())
1736
1737 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1738 "saw template type parameter with wrong depth");
1739 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1740 "Unresolved overloaded function");
1742
1743 // Remove any qualifiers on the parameter from the deduced type.
1744 // We checked the qualifiers for consistency above.
1745 Qualifiers DeducedQs = DeducedType.getQualifiers();
1746 Qualifiers ParamQs = P.getQualifiers();
1747 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1748 if (ParamQs.hasObjCGCAttr())
1749 DeducedQs.removeObjCGCAttr();
1750 if (ParamQs.hasAddressSpace())
1751 DeducedQs.removeAddressSpace();
1752 if (ParamQs.hasObjCLifetime())
1753 DeducedQs.removeObjCLifetime();
1754
1755 // Objective-C ARC:
1756 // If template deduction would produce a lifetime qualifier on a type
1757 // that is not a lifetime type, template argument deduction fails.
1758 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1760 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1761 Info.FirstArg = TemplateArgument(P);
1762 Info.SecondArg = TemplateArgument(A);
1764 }
1765
1766 // Objective-C ARC:
1767 // If template deduction would produce an argument type with lifetime type
1768 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1769 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1770 !DeducedQs.hasObjCLifetime())
1772
1773 DeducedType =
1774 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1775
1776 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1778 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1779 if (Result.isNull()) {
1780 // We can also get inconsistencies when matching NTTP type.
1781 switch (NamedDecl *Param = TemplateParams->getParam(Index);
1782 Param->getKind()) {
1783 case Decl::TemplateTypeParm:
1784 Info.Param = cast<TemplateTypeParmDecl>(Param);
1785 break;
1786 case Decl::NonTypeTemplateParm:
1787 Info.Param = cast<NonTypeTemplateParmDecl>(Param);
1788 break;
1789 case Decl::TemplateTemplateParm:
1790 Info.Param = cast<TemplateTemplateParmDecl>(Param);
1791 break;
1792 default:
1793 llvm_unreachable("unexpected kind");
1794 }
1795 Info.FirstArg = Deduced[Index];
1796 Info.SecondArg = NewDeduced;
1798 }
1799
1800 Deduced[Index] = Result;
1801 if (HasDeducedAnyParam)
1802 *HasDeducedAnyParam = true;
1804 }
1805
1806 // Set up the template argument deduction information for a failure.
1807 Info.FirstArg = TemplateArgument(P);
1808 Info.SecondArg = TemplateArgument(A);
1809
1810 // If the parameter is an already-substituted template parameter
1811 // pack, do nothing: we don't know which of its arguments to look
1812 // at, so we have to wait until all of the parameter packs in this
1813 // expansion have arguments.
1814 if (P->getAs<SubstTemplateTypeParmPackType>())
1816
1817 // Check the cv-qualifiers on the parameter and argument types.
1818 if (!(TDF & TDF_IgnoreQualifiers)) {
1819 if (TDF & TDF_ParamWithReferenceType) {
1822 } else if (TDF & TDF_ArgWithReferenceType) {
1823 // C++ [temp.deduct.conv]p4:
1824 // If the original A is a reference type, A can be more cv-qualified
1825 // than the deduced A
1826 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers(),
1827 S.getASTContext()))
1829
1830 // Strip out all extra qualifiers from the argument to figure out the
1831 // type we're converting to, prior to the qualification conversion.
1832 Qualifiers Quals;
1833 A = S.Context.getUnqualifiedArrayType(A, Quals);
1834 A = S.Context.getQualifiedType(A, P.getQualifiers());
1835 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1836 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1838 }
1839 }
1840
1841 // If the parameter type is not dependent, there is nothing to deduce.
1842 if (!P->isDependentType()) {
1843 if (TDF & TDF_SkipNonDependent)
1846 : S.Context.hasSameType(P, A))
1851 if (!(TDF & TDF_IgnoreQualifiers))
1853 // Otherwise, when ignoring qualifiers, the types not having the same
1854 // unqualified type does not mean they do not match, so in this case we
1855 // must keep going and analyze with a non-dependent parameter type.
1856 }
1857
1858 switch (P.getCanonicalType()->getTypeClass()) {
1859 // Non-canonical types cannot appear here.
1860#define NON_CANONICAL_TYPE(Class, Base) \
1861 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1862#define TYPE(Class, Base)
1863#include "clang/AST/TypeNodes.inc"
1864
1865 case Type::TemplateTypeParm:
1866 case Type::SubstTemplateTypeParmPack:
1867 case Type::SubstBuiltinTemplatePack:
1868 llvm_unreachable("Type nodes handled above");
1869
1870 case Type::Auto:
1871 // C++23 [temp.deduct.funcaddr]/3:
1872 // A placeholder type in the return type of a function template is a
1873 // non-deduced context.
1874 // There's no corresponding wording for [temp.deduct.decl], but we treat
1875 // it the same to match other compilers.
1876 if (P->isDependentType())
1878 [[fallthrough]];
1879 case Type::Builtin:
1880 case Type::VariableArray:
1881 case Type::Vector:
1882 case Type::FunctionNoProto:
1883 case Type::Record:
1884 case Type::Enum:
1885 case Type::ObjCObject:
1886 case Type::ObjCInterface:
1887 case Type::ObjCObjectPointer:
1888 case Type::BitInt:
1889 return (TDF & TDF_SkipNonDependent) ||
1890 ((TDF & TDF_IgnoreQualifiers)
1892 : S.Context.hasSameType(P, A))
1895
1896 // _Complex T [placeholder extension]
1897 case Type::Complex: {
1898 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1899 if (!CA)
1902 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1903 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1904 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1905 }
1906
1907 // _Atomic T [extension]
1908 case Type::Atomic: {
1909 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1910 if (!AA)
1913 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1914 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1915 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1916 }
1917
1918 // T *
1919 case Type::Pointer: {
1920 QualType PointeeType;
1921 if (const auto *PA = A->getAs<PointerType>()) {
1922 PointeeType = PA->getPointeeType();
1923 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1924 PointeeType = PA->getPointeeType();
1925 } else {
1927 }
1929 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1930 PointeeType, Info, Deduced,
1933 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1934 }
1935
1936 // T &
1937 case Type::LValueReference: {
1938 const auto *RP = P->castAs<LValueReferenceType>(),
1939 *RA = A->getAs<LValueReferenceType>();
1940 if (!RA)
1942
1944 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1945 Deduced, 0, degradeCallPartialOrderingKind(POK),
1946 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1947 }
1948
1949 // T && [C++0x]
1950 case Type::RValueReference: {
1951 const auto *RP = P->castAs<RValueReferenceType>(),
1952 *RA = A->getAs<RValueReferenceType>();
1953 if (!RA)
1955
1957 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1958 Deduced, 0, degradeCallPartialOrderingKind(POK),
1959 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1960 }
1961
1962 // T [] (implied, but not stated explicitly)
1963 case Type::IncompleteArray: {
1964 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1965 if (!IAA)
1967
1968 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1969 assert(IAP && "Template parameter not of incomplete array type");
1970
1972 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1973 Deduced, TDF & TDF_IgnoreQualifiers,
1975 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1976 }
1977
1978 // T [integer-constant]
1979 case Type::ConstantArray: {
1980 const auto *CAA = S.Context.getAsConstantArrayType(A),
1982 assert(CAP);
1983 if (!CAA || CAA->getSize() != CAP->getSize())
1985
1987 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1988 Deduced, TDF & TDF_IgnoreQualifiers,
1990 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1991 }
1992
1993 // type [i]
1994 case Type::DependentSizedArray: {
1995 const auto *AA = S.Context.getAsArrayType(A);
1996 if (!AA)
1998
1999 // Check the element type of the arrays
2000 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
2001 assert(DAP);
2003 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
2004 Info, Deduced, TDF & TDF_IgnoreQualifiers,
2006 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2008 return Result;
2009
2010 // Determine the array bound is something we can deduce.
2012 getDeducedNTTParameterFromExpr(Info, DAP->getSizeExpr());
2013 if (!NTTP)
2015
2016 // We can perform template argument deduction for the given non-type
2017 // template parameter.
2018 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2019 "saw non-type template parameter with wrong depth");
2020 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
2021 llvm::APSInt Size(CAA->getSize());
2023 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
2024 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2025 Deduced, HasDeducedAnyParam);
2026 }
2027 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
2028 if (DAA->getSizeExpr())
2030 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
2031 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2032
2033 // Incomplete type does not match a dependently-sized array type
2035 }
2036
2037 // type(*)(T)
2038 // T(*)()
2039 // T(*)(T)
2040 case Type::FunctionProto: {
2041 const auto *FPP = P->castAs<FunctionProtoType>(),
2042 *FPA = A->getAs<FunctionProtoType>();
2043 if (!FPA)
2045
2046 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
2047 FPP->getRefQualifier() != FPA->getRefQualifier() ||
2048 FPP->isVariadic() != FPA->isVariadic())
2050
2051 // Check return types.
2053 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
2054 Info, Deduced, 0, degradeCallPartialOrderingKind(POK),
2055 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2057 return Result;
2058
2059 // Check parameter types.
2061 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
2062 Deduced, TDF & TDF_TopLevelParameterTypeList, POK,
2063 HasDeducedAnyParam,
2064 /*HasDeducedParam=*/nullptr);
2066 return Result;
2067
2070
2071 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
2072 // deducing through the noexcept-specifier if it's part of the canonical
2073 // type. libstdc++ relies on this.
2074 Expr *NoexceptExpr = FPP->getNoexceptExpr();
2076 NoexceptExpr ? getDeducedNTTParameterFromExpr(Info, NoexceptExpr)
2077 : nullptr) {
2078 assert(NTTP.getDepth() == Info.getDeducedDepth() &&
2079 "saw non-type template parameter with wrong depth");
2080
2081 llvm::APSInt Noexcept(1);
2082 switch (FPA->canThrow()) {
2083 case CT_Cannot:
2084 Noexcept = 1;
2085 [[fallthrough]];
2086
2087 case CT_Can:
2088 // We give E in noexcept(E) the "deduced from array bound" treatment.
2089 // FIXME: Should we?
2091 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2092 /*DeducedFromArrayBound=*/true, Info,
2093 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2094
2095 case CT_Dependent:
2096 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2098 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2099 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2100 // Can't deduce anything from throw(T...).
2101 break;
2102 }
2103 }
2104 // FIXME: Detect non-deduced exception specification mismatches?
2105 //
2106 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2107 // top-level differences in noexcept-specifications.
2108
2110 }
2111
2112 case Type::InjectedClassName:
2113 // Treat a template's injected-class-name as if the template
2114 // specialization type had been used.
2115
2116 // template-name<T> (where template-name refers to a class template)
2117 // template-name<i>
2118 // TT<T>
2119 // TT<i>
2120 // TT<>
2121 case Type::TemplateSpecialization: {
2122 // When Arg cannot be a derived class, we can just try to deduce template
2123 // arguments from the template-id.
2124 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2125 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2126 POK != PartialOrderingKind::None,
2127 Deduced, HasDeducedAnyParam);
2128
2129 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2130 Deduced.end());
2131
2133 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2134 Deduced, HasDeducedAnyParam);
2136 return Result;
2137
2138 // We cannot inspect base classes as part of deduction when the type
2139 // is incomplete, so either instantiate any templates necessary to
2140 // complete the type, or skip over it if it cannot be completed.
2141 if (!S.isCompleteType(Info.getLocation(), A))
2142 return Result;
2143
2144 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2145 if (RD->isInvalidDecl())
2146 return Result;
2147
2148 // Reset the incorrectly deduced argument from above.
2149 Deduced = DeducedOrig;
2150
2151 // Check bases according to C++14 [temp.deduct.call] p4b3:
2152 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2153 POK != PartialOrderingKind::None,
2154 Deduced, HasDeducedAnyParam);
2156 : Result;
2157 }
2158
2159 // T type::*
2160 // T T::*
2161 // T (type::*)()
2162 // type (T::*)()
2163 // type (type::*)(T)
2164 // type (T::*)(T)
2165 // T (type::*)(T)
2166 // T (T::*)()
2167 // T (T::*)(T)
2168 case Type::MemberPointer: {
2169 const auto *MPP = P->castAs<MemberPointerType>(),
2170 *MPA = A->getAs<MemberPointerType>();
2171 if (!MPA)
2173
2174 QualType PPT = MPP->getPointeeType();
2175 if (PPT->isFunctionType())
2176 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2177 /*IsCtorOrDtor=*/false, Info.getLocation());
2178 QualType APT = MPA->getPointeeType();
2179 if (APT->isFunctionType())
2180 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2181 /*IsCtorOrDtor=*/false, Info.getLocation());
2182
2183 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2185 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2187 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2189 return Result;
2190
2191 QualType TP =
2192 MPP->isSugared()
2193 ? S.Context.getCanonicalTagType(MPP->getMostRecentCXXRecordDecl())
2194 : QualType(MPP->getQualifier().getAsType(), 0);
2195 assert(!TP.isNull() && "member pointer with non-type class");
2196
2197 QualType TA =
2198 MPA->isSugared()
2199 ? S.Context.getCanonicalTagType(MPA->getMostRecentCXXRecordDecl())
2200 : QualType(MPA->getQualifier().getAsType(), 0)
2202 assert(!TA.isNull() && "member pointer with non-type class");
2203
2205 S, TemplateParams, TP, TA, Info, Deduced, SubTDF,
2207 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2208 }
2209
2210 // (clang extension)
2211 //
2212 // type(^)(T)
2213 // T(^)()
2214 // T(^)(T)
2215 case Type::BlockPointer: {
2216 const auto *BPP = P->castAs<BlockPointerType>(),
2217 *BPA = A->getAs<BlockPointerType>();
2218 if (!BPA)
2221 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2222 Deduced, 0, degradeCallPartialOrderingKind(POK),
2223 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2224 }
2225
2226 // (clang extension)
2227 //
2228 // T __attribute__(((ext_vector_type(<integral constant>))))
2229 case Type::ExtVector: {
2230 const auto *VP = P->castAs<ExtVectorType>();
2231 QualType ElementType;
2232 if (const auto *VA = A->getAs<ExtVectorType>()) {
2233 // Make sure that the vectors have the same number of elements.
2234 if (VP->getNumElements() != VA->getNumElements())
2236 ElementType = VA->getElementType();
2237 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2238 // We can't check the number of elements, since the argument has a
2239 // dependent number of elements. This can only occur during partial
2240 // ordering.
2241 ElementType = VA->getElementType();
2242 } else {
2244 }
2245 // Perform deduction on the element types.
2247 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2249 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2250 }
2251
2252 case Type::DependentVector: {
2253 const auto *VP = P->castAs<DependentVectorType>();
2254
2255 if (const auto *VA = A->getAs<VectorType>()) {
2256 // Perform deduction on the element types.
2258 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2259 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2260 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2262 return Result;
2263
2264 // Perform deduction on the vector size, if we can.
2266 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2267 if (!NTTP)
2269
2270 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2271 ArgSize = VA->getNumElements();
2272 // Note that we use the "array bound" rules here; just like in that
2273 // case, we don't have any particular type for the vector size, but
2274 // we can provide one if necessary.
2276 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2277 Info, POK != PartialOrderingKind::None, Deduced,
2278 HasDeducedAnyParam);
2279 }
2280
2281 if (const auto *VA = A->getAs<DependentVectorType>()) {
2282 // Perform deduction on the element types.
2284 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2285 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2286 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2288 return Result;
2289
2290 // Perform deduction on the vector size, if we can.
2292 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2293 if (!NTTP)
2295
2297 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2298 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2299 }
2300
2302 }
2303
2304 // (clang extension)
2305 //
2306 // T __attribute__(((ext_vector_type(N))))
2307 case Type::DependentSizedExtVector: {
2308 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2309
2310 if (const auto *VA = A->getAs<ExtVectorType>()) {
2311 // Perform deduction on the element types.
2313 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2314 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2315 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2317 return Result;
2318
2319 // Perform deduction on the vector size, if we can.
2321 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2322 if (!NTTP)
2324
2325 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2326 ArgSize = VA->getNumElements();
2327 // Note that we use the "array bound" rules here; just like in that
2328 // case, we don't have any particular type for the vector size, but
2329 // we can provide one if necessary.
2331 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2332 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2333 }
2334
2335 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2336 // Perform deduction on the element types.
2338 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2339 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2340 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2342 return Result;
2343
2344 // Perform deduction on the vector size, if we can.
2346 getDeducedNTTParameterFromExpr(Info, VP->getSizeExpr());
2347 if (!NTTP)
2349
2351 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2352 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2353 }
2354
2356 }
2357
2358 // (clang extension)
2359 //
2360 // T __attribute__((matrix_type(<integral constant>,
2361 // <integral constant>)))
2362 case Type::ConstantMatrix: {
2363 const auto *MP = P->castAs<ConstantMatrixType>(),
2364 *MA = A->getAs<ConstantMatrixType>();
2365 if (!MA)
2367
2368 // Check that the dimensions are the same
2369 if (MP->getNumRows() != MA->getNumRows() ||
2370 MP->getNumColumns() != MA->getNumColumns()) {
2372 }
2373 // Perform deduction on element types.
2375 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2376 Deduced, TDF, degradeCallPartialOrderingKind(POK),
2377 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2378 }
2379
2380 case Type::DependentSizedMatrix: {
2381 const auto *MP = P->castAs<DependentSizedMatrixType>();
2382 const auto *MA = A->getAs<MatrixType>();
2383 if (!MA)
2385
2386 // Check the element type of the matrixes.
2388 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2389 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2390 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2392 return Result;
2393
2394 // Try to deduce a matrix dimension.
2395 auto DeduceMatrixArg =
2396 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2397 Expr *ParamExpr, const MatrixType *A,
2398 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2399 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2400 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2401 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2402 if (!ParamExpr->isValueDependent()) {
2403 std::optional<llvm::APSInt> ParamConst =
2404 ParamExpr->getIntegerConstantExpr(S.Context);
2405 if (!ParamConst)
2407
2408 if (ACM) {
2409 if ((ACM->*GetArgDimension)() == *ParamConst)
2412 }
2413
2414 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2415 if (std::optional<llvm::APSInt> ArgConst =
2416 ArgExpr->getIntegerConstantExpr(S.Context))
2417 if (*ArgConst == *ParamConst)
2420 }
2421
2423 getDeducedNTTParameterFromExpr(Info, ParamExpr);
2424 if (!NTTP)
2426
2427 if (ACM) {
2428 llvm::APSInt ArgConst(
2430 ArgConst = (ACM->*GetArgDimension)();
2432 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2433 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2434 Deduced, HasDeducedAnyParam);
2435 }
2436
2438 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2439 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2440 };
2441
2442 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2446 return Result;
2447
2448 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2451 }
2452
2453 // (clang extension)
2454 //
2455 // T __attribute__(((address_space(N))))
2456 case Type::DependentAddressSpace: {
2457 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2458
2459 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2460 // Perform deduction on the pointer type.
2462 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2463 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2464 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2466 return Result;
2467
2468 // Perform deduction on the address space, if we can.
2470 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2471 if (!NTTP)
2473
2475 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2476 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2477 }
2478
2480 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2481 false);
2482 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2483
2484 // Perform deduction on the pointer types.
2486 S, TemplateParams, ASP->getPointeeType(),
2487 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2489 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2491 return Result;
2492
2493 // Perform deduction on the address space, if we can.
2495 getDeducedNTTParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2496 if (!NTTP)
2498
2500 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2501 Info, POK != PartialOrderingKind::None, Deduced,
2502 HasDeducedAnyParam);
2503 }
2504
2506 }
2507 case Type::DependentBitInt: {
2508 const auto *IP = P->castAs<DependentBitIntType>();
2509
2510 if (const auto *IA = A->getAs<BitIntType>()) {
2511 if (IP->isUnsigned() != IA->isUnsigned())
2513
2515 getDeducedNTTParameterFromExpr(Info, IP->getNumBitsExpr());
2516 if (!NTTP)
2518
2519 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2520 ArgSize = IA->getNumBits();
2521
2523 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, 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::DependentTemplateSpecialization:
2544 case Type::PackExpansion:
2545 case Type::Pipe:
2546 case Type::ArrayParameter:
2547 case Type::HLSLAttributedResource:
2548 case Type::HLSLInlineSpirv:
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,
2587 PartialOrdering ? PartialOrderingKind::NonCall
2588 : PartialOrderingKind::None,
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
2611 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
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.
2641
2642 Info.FirstArg = P;
2643 Info.SecondArg = A;
2645
2648 getDeducedNTTParameterFromExpr(Info, P.getAsExpr())) {
2649 switch (A.getKind()) {
2651 const Expr *E = A.getAsExpr();
2652 // When checking NTTP, if either the parameter or the argument is
2653 // dependent, as there would be otherwise nothing to deduce, we force
2654 // the argument to the parameter type using this dependent implicit
2655 // cast, in order to maintain invariants. Now we can deduce the
2656 // resulting type from the original type, and deduce the original type
2657 // against the parameter we are checking.
2658 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
2659 ICE && ICE->getCastKind() == clang::CK_Dependent) {
2660 E = ICE->getSubExpr();
2662 S, TemplateParams, ICE->getType(), E->getType(), Info,
2663 Deduced, TDF_SkipNonDependent,
2664 PartialOrdering ? PartialOrderingKind::NonCall
2665 : PartialOrderingKind::None,
2666 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2668 return Result;
2669 }
2671 S, TemplateParams, NTTP, DeducedTemplateArgument(A), E->getType(),
2672 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2673 }
2677 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2679 HasDeducedAnyParam);
2680
2683 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2684 Deduced, HasDeducedAnyParam);
2685
2688 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2689 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2690
2696 Info.FirstArg = P;
2697 Info.SecondArg = A;
2699 }
2700 llvm_unreachable("Unknown template argument kind");
2701 }
2702 // Can't deduce anything, but that's okay.
2705 llvm_unreachable("Argument packs should be expanded by the caller!");
2706 }
2707
2708 llvm_unreachable("Invalid TemplateArgument Kind!");
2709}
2710
2711/// Determine whether there is a template argument to be used for
2712/// deduction.
2713///
2714/// This routine "expands" argument packs in-place, overriding its input
2715/// parameters so that \c Args[ArgIdx] will be the available template argument.
2716///
2717/// \returns true if there is another template argument (which will be at
2718/// \c Args[ArgIdx]), false otherwise.
2720 unsigned &ArgIdx) {
2721 if (ArgIdx == Args.size())
2722 return false;
2723
2724 const TemplateArgument &Arg = Args[ArgIdx];
2725 if (Arg.getKind() != TemplateArgument::Pack)
2726 return true;
2727
2728 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2729 Args = Arg.pack_elements();
2730 ArgIdx = 0;
2731 return ArgIdx < Args.size();
2732}
2733
2734/// Determine whether the given set of template arguments has a pack
2735/// expansion that is not the last template argument.
2737 bool FoundPackExpansion = false;
2738 for (const auto &A : Args) {
2739 if (FoundPackExpansion)
2740 return true;
2741
2742 if (A.getKind() == TemplateArgument::Pack)
2743 return hasPackExpansionBeforeEnd(A.pack_elements());
2744
2745 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2746 // templates, it should not be treated as a pack expansion.
2747 if (A.isPackExpansion())
2748 FoundPackExpansion = true;
2749 }
2750
2751 return false;
2752}
2753
2760 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2761 PackFold PackFold, bool *HasDeducedAnyParam) {
2762 bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
2763 PackFold == PackFold::Both,
2764 FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
2765 PackFold == PackFold::Both;
2766
2767 // C++0x [temp.deduct.type]p9:
2768 // If the template argument list of P contains a pack expansion that is not
2769 // the last template argument, the entire template argument list is a
2770 // non-deduced context.
2771 if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
2773
2774 // C++0x [temp.deduct.type]p9:
2775 // If P has a form that contains <T> or <i>, then each argument Pi of the
2776 // respective template argument list P is compared with the corresponding
2777 // argument Ai of the corresponding template argument list of A.
2778 for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
2780 return !FoldPackParameter && hasTemplateArgumentForDeduction(As, ArgIdx)
2783
2784 if (!Ps[ParamIdx].isPackExpansion()) {
2785 // The simple case: deduce template arguments by matching Pi and Ai.
2786
2787 // Check whether we have enough arguments.
2788 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2789 return !FoldPackArgument && NumberOfArgumentsMustMatch
2792
2793 if (As[ArgIdx].isPackExpansion()) {
2794 // C++1z [temp.deduct.type]p9:
2795 // During partial ordering, if Ai was originally a pack expansion
2796 // [and] Pi is not a pack expansion, template argument deduction
2797 // fails.
2798 if (!FoldPackArgument)
2800
2801 TemplateArgument Pattern = As[ArgIdx].getPackExpansionPattern();
2802 for (;;) {
2803 // Deduce template parameters from the pattern.
2805 S, TemplateParams, Ps[ParamIdx], Pattern, Info,
2806 PartialOrdering, Deduced, HasDeducedAnyParam);
2808 return Result;
2809
2810 ++ParamIdx;
2813 if (Ps[ParamIdx].isPackExpansion())
2814 break;
2815 }
2816 } else {
2817 // Perform deduction for this Pi/Ai pair.
2819 S, TemplateParams, Ps[ParamIdx], As[ArgIdx], Info,
2820 PartialOrdering, Deduced, HasDeducedAnyParam);
2822 return Result;
2823
2824 ++ArgIdx;
2825 ++ParamIdx;
2826 continue;
2827 }
2828 }
2829
2830 // The parameter is a pack expansion.
2831
2832 // C++0x [temp.deduct.type]p9:
2833 // If Pi is a pack expansion, then the pattern of Pi is compared with
2834 // each remaining argument in the template argument list of A. Each
2835 // comparison deduces template arguments for subsequent positions in the
2836 // template parameter packs expanded by Pi.
2837 TemplateArgument Pattern = Ps[ParamIdx].getPackExpansionPattern();
2838
2839 // Prepare to deduce the packs within the pattern.
2840 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2841
2842 // Keep track of the deduced template arguments for each parameter pack
2843 // expanded by this pack expansion (the outer index) and for each
2844 // template argument (the inner SmallVectors).
2845 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2846 PackScope.hasNextElement();
2847 ++ArgIdx) {
2848 if (!As[ArgIdx].isPackExpansion()) {
2849 if (!FoldPackParameter)
2851 if (FoldPackArgument)
2852 Info.setStrictPackMatch();
2853 }
2854 // Deduce template arguments from the pattern.
2856 S, TemplateParams, Pattern, As[ArgIdx], Info, PartialOrdering,
2857 Deduced, HasDeducedAnyParam);
2859 return Result;
2860
2861 PackScope.nextPackElement();
2862 }
2863
2864 // Build argument packs for each of the parameter packs expanded by this
2865 // pack expansion.
2866 return PackScope.finish();
2867 }
2868}
2869
2874 bool NumberOfArgumentsMustMatch) {
2875 return ::DeduceTemplateArguments(
2876 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2877 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2878 /*HasDeducedAnyParam=*/nullptr);
2879}
2880
2883 QualType NTTPType, SourceLocation Loc,
2885 switch (Arg.getKind()) {
2887 llvm_unreachable("Can't get a NULL template argument here");
2888
2890 return TemplateArgumentLoc(
2892
2894 if (NTTPType.isNull())
2895 NTTPType = Arg.getParamTypeForDecl();
2898 .getAs<Expr>();
2899 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2900 }
2901
2903 if (NTTPType.isNull())
2904 NTTPType = Arg.getNullPtrType();
2906 .getAs<Expr>();
2907 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2908 E);
2909 }
2910
2914 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
2915 }
2916
2921 Builder.MakeTrivial(Context, Template.getQualifier(), Loc);
2922 return TemplateArgumentLoc(
2923 Context, Arg, Loc, Builder.getWithLocInContext(Context), Loc,
2924 /*EllipsisLoc=*/Arg.getKind() == TemplateArgument::TemplateExpansion
2925 ? Loc
2926 : SourceLocation());
2927 }
2928
2930 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2931
2934 }
2935
2936 llvm_unreachable("Invalid TemplateArgument Kind!");
2937}
2938
2941 SourceLocation Location) {
2943 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2944}
2945
2946/// Convert the given deduced template argument and add it to the set of
2947/// fully-converted template arguments.
2948static bool
2951 TemplateDeductionInfo &Info, bool IsDeduced,
2953 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2954 unsigned ArgumentPackIndex) {
2955 // Convert the deduced template argument into a template
2956 // argument that we can check, almost as if the user had written
2957 // the template argument explicitly.
2959 Arg, QualType(), Info.getLocation(), Param);
2960
2961 SaveAndRestore _1(CTAI.MatchingTTP, false);
2962 SaveAndRestore _2(CTAI.StrictPackMatch, false);
2963 // Check the template argument, converting it as necessary.
2964 auto Res = S.CheckTemplateArgument(
2965 Param, ArgLoc, Template, Template->getLocation(),
2966 Template->getSourceRange().getEnd(), ArgumentPackIndex, CTAI,
2967 IsDeduced
2971 if (CTAI.StrictPackMatch)
2972 Info.setStrictPackMatch();
2973 return Res;
2974 };
2975
2976 if (Arg.getKind() == TemplateArgument::Pack) {
2977 // This is a template argument pack, so check each of its arguments against
2978 // the template parameter.
2979 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2980 CanonicalPackedArgsBuilder;
2981 for (const auto &P : Arg.pack_elements()) {
2982 // When converting the deduced template argument, append it to the
2983 // general output list. We need to do this so that the template argument
2984 // checking logic has all of the prior template arguments available.
2985 DeducedTemplateArgument InnerArg(P);
2987 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2988 "deduced nested pack");
2989 if (P.isNull()) {
2990 // We deduced arguments for some elements of this pack, but not for
2991 // all of them. This happens if we get a conditionally-non-deduced
2992 // context in a pack expansion (such as an overload set in one of the
2993 // arguments).
2994 S.Diag(Param->getLocation(),
2995 diag::err_template_arg_deduced_incomplete_pack)
2996 << Arg << Param;
2997 return true;
2998 }
2999 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
3000 return true;
3001
3002 // Move the converted template argument into our argument pack.
3003 SugaredPackedArgsBuilder.push_back(CTAI.SugaredConverted.pop_back_val());
3004 CanonicalPackedArgsBuilder.push_back(
3005 CTAI.CanonicalConverted.pop_back_val());
3006 }
3007
3008 // If the pack is empty, we still need to substitute into the parameter
3009 // itself, in case that substitution fails.
3010 if (SugaredPackedArgsBuilder.empty()) {
3013 /*Final=*/true);
3014 Sema::ArgPackSubstIndexRAII OnlySubstNonPackExpansion(S, std::nullopt);
3015
3016 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3017 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3018 NTTP, CTAI.SugaredConverted,
3019 Template->getSourceRange());
3020 if (Inst.isInvalid() ||
3021 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
3022 NTTP->getDeclName()).isNull())
3023 return true;
3024 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3025 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
3026 TTP, CTAI.SugaredConverted,
3027 Template->getSourceRange());
3028 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
3029 return true;
3030 }
3031 // For type parameters, no substitution is ever required.
3032 }
3033
3034 // Create the resulting argument pack.
3035 CTAI.SugaredConverted.push_back(
3036 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
3038 S.Context, CanonicalPackedArgsBuilder));
3039 return false;
3040 }
3041
3042 return ConvertArg(Arg, 0);
3043}
3044
3045/// \param IsIncomplete When used, we only consider template parameters that
3046/// were deduced, disregarding any default arguments. After the function
3047/// finishes, the object pointed at will contain a value indicating if the
3048/// conversion was actually incomplete.
3050 Sema &S, NamedDecl *Template, TemplateParameterList *TemplateParams,
3051 bool IsDeduced, SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3053 LocalInstantiationScope *CurrentInstantiationScope,
3054 unsigned NumAlreadyConverted, bool *IsIncomplete) {
3055 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3056 NamedDecl *Param = TemplateParams->getParam(I);
3057
3058 // C++0x [temp.arg.explicit]p3:
3059 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3060 // be deduced to an empty sequence of template arguments.
3061 // FIXME: Where did the word "trailing" come from?
3062 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3063 if (auto Result =
3064 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3066 return Result;
3067 }
3068
3069 if (!Deduced[I].isNull()) {
3070 if (I < NumAlreadyConverted) {
3071 // We may have had explicitly-specified template arguments for a
3072 // template parameter pack (that may or may not have been extended
3073 // via additional deduced arguments).
3074 if (Param->isParameterPack() && CurrentInstantiationScope &&
3075 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3076 // Forget the partially-substituted pack; its substitution is now
3077 // complete.
3078 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3079 // We still need to check the argument in case it was extended by
3080 // deduction.
3081 } else {
3082 // We have already fully type-checked and converted this
3083 // argument, because it was explicitly-specified. Just record the
3084 // presence of this argument.
3085 CTAI.SugaredConverted.push_back(Deduced[I]);
3086 CTAI.CanonicalConverted.push_back(
3088 continue;
3089 }
3090 }
3091
3092 // We may have deduced this argument, so it still needs to be
3093 // checked and converted.
3094 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3095 IsDeduced, CTAI)) {
3096 Info.Param = makeTemplateParameter(Param);
3097 // FIXME: These template arguments are temporary. Free them!
3098 Info.reset(
3101 CTAI.CanonicalConverted));
3103 }
3104
3105 continue;
3106 }
3107
3108 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3109 // template parameters to remain not deduced. As a provisional fix for a
3110 // core issue that does not exist yet, which may be related to CWG2160, only
3111 // consider template parameters that were deduced, disregarding any default
3112 // arguments.
3113 if (IsIncomplete) {
3114 *IsIncomplete = true;
3115 CTAI.SugaredConverted.push_back({});
3116 CTAI.CanonicalConverted.push_back({});
3117 continue;
3118 }
3119
3120 // Substitute into the default template argument, if available.
3121 bool HasDefaultArg = false;
3122 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3123 if (!TD) {
3124 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
3125 isa<VarTemplatePartialSpecializationDecl>(Template));
3127 }
3128
3129 TemplateArgumentLoc DefArg;
3130 {
3131 Qualifiers ThisTypeQuals;
3132 CXXRecordDecl *ThisContext = nullptr;
3133 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3134 if (Rec->isLambda())
3135 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3136 ThisContext = Method->getParent();
3137 ThisTypeQuals = Method->getMethodQualifiers();
3138 }
3139
3140 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3141 S.getLangOpts().CPlusPlus17);
3142
3144 TD, /*TemplateKWLoc=*/SourceLocation(), TD->getLocation(),
3145 TD->getSourceRange().getEnd(), Param, CTAI.SugaredConverted,
3146 CTAI.CanonicalConverted, HasDefaultArg);
3147 }
3148
3149 // If there was no default argument, deduction is incomplete.
3150 if (DefArg.getArgument().isNull()) {
3151 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3152 Info.reset(
3155
3158 }
3159
3160 SaveAndRestore _1(CTAI.PartialOrdering, false);
3161 SaveAndRestore _2(CTAI.MatchingTTP, false);
3162 SaveAndRestore _3(CTAI.StrictPackMatch, false);
3163 // Check whether we can actually use the default argument.
3165 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3166 /*ArgumentPackIndex=*/0, CTAI, Sema::CTAK_Specified)) {
3167 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3168 // FIXME: These template arguments are temporary. Free them!
3169 Info.reset(
3173 }
3174
3175 // If we get here, we successfully used the default template argument.
3176 }
3177
3179}
3180
3182 if (auto *DC = dyn_cast<DeclContext>(D))
3183 return DC;
3184 return D->getDeclContext();
3185}
3186
3187template<typename T> struct IsPartialSpecialization {
3188 static constexpr bool value = false;
3189};
3190template<>
3192 static constexpr bool value = true;
3193};
3194template<>
3196 static constexpr bool value = true;
3197};
3198
3201 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3202 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3203 TemplateDeductionInfo &Info) {
3204 llvm::SmallVector<AssociatedConstraint, 3> AssociatedConstraints;
3205 bool DeducedArgsNeedReplacement = false;
3206 if (auto *TD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Template)) {
3207 TD->getAssociatedConstraints(AssociatedConstraints);
3208 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3209 } else if (auto *TD =
3210 dyn_cast<VarTemplatePartialSpecializationDecl>(Template)) {
3211 TD->getAssociatedConstraints(AssociatedConstraints);
3212 DeducedArgsNeedReplacement = !TD->isClassScopeExplicitSpecialization();
3213 } else {
3214 cast<TemplateDecl>(Template)->getAssociatedConstraints(
3215 AssociatedConstraints);
3216 }
3217
3218 std::optional<ArrayRef<TemplateArgument>> Innermost;
3219 // If we don't need to replace the deduced template arguments,
3220 // we can add them immediately as the inner-most argument list.
3221 if (!DeducedArgsNeedReplacement)
3222 Innermost = CanonicalDeducedArgs;
3223
3225 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3226 /*RelativeToPrimary=*/true, /*Pattern=*/
3227 nullptr, /*ForConstraintInstantiation=*/true);
3228
3229 // getTemplateInstantiationArgs picks up the non-deduced version of the
3230 // template args when this is a variable template partial specialization and
3231 // not class-scope explicit specialization, so replace with Deduced Args
3232 // instead of adding to inner-most.
3233 if (!Innermost)
3234 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3235
3236 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3237 Info.getLocation(),
3240 Info.reset(
3241 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3242 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3244 }
3246}
3247
3248/// Complete template argument deduction.
3250 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3254 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3255 // Unevaluated SFINAE context.
3258
3259 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Entity));
3260
3261 // C++ [temp.deduct.type]p2:
3262 // [...] or if any template argument remains neither deduced nor
3263 // explicitly specified, template argument deduction fails.
3266 S, Entity, EntityTPL, /*IsDeduced=*/PartialOrdering, Deduced, Info,
3267 CTAI,
3268 /*CurrentInstantiationScope=*/nullptr,
3269 /*NumAlreadyConverted=*/0U, /*IsIncomplete=*/nullptr);
3271 return Result;
3272
3273 if (CopyDeducedArgs) {
3274 // Form the template argument list from the deduced template arguments.
3275 TemplateArgumentList *SugaredDeducedArgumentList =
3277 TemplateArgumentList *CanonicalDeducedArgumentList =
3279 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3280 }
3281
3282 TemplateParameterList *TPL = Template->getTemplateParameters();
3283 TemplateArgumentListInfo InstArgs(TPL->getLAngleLoc(), TPL->getRAngleLoc());
3285 /*Final=*/true);
3286 MLTAL.addOuterRetainedLevels(TPL->getDepth());
3287
3288 if (S.SubstTemplateArguments(Ps, MLTAL, InstArgs)) {
3289 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3290 if (ParamIdx >= TPL->size())
3291 ParamIdx = TPL->size() - 1;
3292
3293 Decl *Param = TPL->getParam(ParamIdx);
3294 Info.Param = makeTemplateParameter(Param);
3295 Info.FirstArg = Ps[ArgIdx].getArgument();
3297 }
3298
3301 if (S.CheckTemplateArgumentList(Template, Template->getLocation(), InstArgs,
3302 /*DefaultArgs=*/{}, false, InstCTAI,
3303 /*UpdateArgsWithConversions=*/true,
3308
3309 // Check that we produced the correct argument list.
3311 AsStack{As};
3312 for (;;) {
3313 auto take = [](SmallVectorImpl<ArrayRef<TemplateArgument>> &Stack)
3315 while (!Stack.empty()) {
3316 auto &Xs = Stack.back();
3317 if (Xs.empty()) {
3318 Stack.pop_back();
3319 continue;
3320 }
3321 auto &X = Xs.front();
3322 if (X.getKind() == TemplateArgument::Pack) {
3323 Stack.emplace_back(X.getPackAsArray());
3324 Xs = Xs.drop_front();
3325 continue;
3326 }
3327 assert(!X.isNull());
3328 return {Xs, X};
3329 }
3330 static constexpr ArrayRef<TemplateArgument> None;
3331 return {const_cast<ArrayRef<TemplateArgument> &>(None),
3333 };
3334 auto [Ps, P] = take(PsStack);
3335 auto [As, A] = take(AsStack);
3336 if (P.isNull() && A.isNull())
3337 break;
3338 TemplateArgument PP = P.isPackExpansion() ? P.getPackExpansionPattern() : P,
3339 PA = A.isPackExpansion() ? A.getPackExpansionPattern() : A;
3340 if (!S.Context.isSameTemplateArgument(PP, PA)) {
3341 if (!P.isPackExpansion() && !A.isPackExpansion()) {
3343 (AsStack.empty() ? As.end() : AsStack.back().begin()) -
3344 As.begin()));
3345 Info.FirstArg = P;
3346 Info.SecondArg = A;
3348 }
3349 if (P.isPackExpansion()) {
3350 Ps = Ps.drop_front();
3351 continue;
3352 }
3353 if (A.isPackExpansion()) {
3354 As = As.drop_front();
3355 continue;
3356 }
3357 }
3358 Ps = Ps.drop_front(P.isPackExpansion() ? 0 : 1);
3359 As = As.drop_front(A.isPackExpansion() && !P.isPackExpansion() ? 0 : 1);
3360 }
3361 assert(PsStack.empty());
3362 assert(AsStack.empty());
3363
3364 if (!PartialOrdering) {
3366 S, Entity, CTAI.SugaredConverted, CTAI.CanonicalConverted, Info);
3368 return Result;
3369 }
3370
3372}
3374 Sema &S, NamedDecl *Entity, TemplateParameterList *EntityTPL,
3378 TemplateDeductionInfo &Info, bool CopyDeducedArgs) {
3379 TemplateParameterList *TPL = Template->getTemplateParameters();
3380 SmallVector<TemplateArgumentLoc, 8> PsLoc(Ps.size());
3381 for (unsigned I = 0, N = Ps.size(); I != N; ++I)
3382 PsLoc[I] = S.getTrivialTemplateArgumentLoc(Ps[I], QualType(),
3383 TPL->getParam(I)->getLocation());
3384 return FinishTemplateArgumentDeduction(S, Entity, EntityTPL, Template,
3385 PartialOrdering, PsLoc, As, Deduced,
3386 Info, CopyDeducedArgs);
3387}
3388
3389/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3390/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3391/// the three implementations.
3393 Sema &S, TemplateDecl *TD,
3395 TemplateDeductionInfo &Info) {
3396 // Unevaluated SFINAE context.
3399
3401
3402 // C++ [temp.deduct.type]p2:
3403 // [...] or if any template argument remains neither deduced nor
3404 // explicitly specified, template argument deduction fails.
3407 S, TD, TD->getTemplateParameters(), /*IsDeduced=*/false, Deduced,
3408 Info, CTAI,
3409 /*CurrentInstantiationScope=*/nullptr, /*NumAlreadyConverted=*/0,
3410 /*IsIncomplete=*/nullptr);
3412 return Result;
3413
3414 return ::CheckDeducedArgumentConstraints(S, TD, CTAI.SugaredConverted,
3415 CTAI.CanonicalConverted, Info);
3416}
3417
3418/// Perform template argument deduction to determine whether the given template
3419/// arguments match the given class or variable template partial specialization
3420/// per C++ [temp.class.spec.match].
3421template <typename T>
3422static std::enable_if_t<IsPartialSpecialization<T>::value,
3425 ArrayRef<TemplateArgument> TemplateArgs,
3426 TemplateDeductionInfo &Info) {
3427 if (Partial->isInvalidDecl())
3429
3430 // C++ [temp.class.spec.match]p2:
3431 // A partial specialization matches a given actual template
3432 // argument list if the template arguments of the partial
3433 // specialization can be deduced from the actual template argument
3434 // list (14.8.2).
3435
3436 // Unevaluated SFINAE context.
3439 Sema::SFINAETrap Trap(S);
3440
3441 // This deduction has no relation to any outer instantiation we might be
3442 // performing.
3443 LocalInstantiationScope InstantiationScope(S);
3444
3446 Deduced.resize(Partial->getTemplateParameters()->size());
3448 S, Partial->getTemplateParameters(),
3449 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3450 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3451 PackFold::ParameterToArgument,
3452 /*HasDeducedAnyParam=*/nullptr);
3454 return Result;
3455
3456 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3457 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3458 Info);
3459 if (Inst.isInvalid())
3461
3464 Result = ::FinishTemplateArgumentDeduction(
3465 S, Partial, Partial->getTemplateParameters(),
3466 Partial->getSpecializedTemplate(),
3467 /*IsPartialOrdering=*/false,
3468 Partial->getTemplateArgsAsWritten()->arguments(), TemplateArgs, Deduced,
3469 Info, /*CopyDeducedArgs=*/true);
3470 });
3471
3473 return Result;
3474
3475 if (Trap.hasErrorOccurred())
3477
3479}
3480
3483 ArrayRef<TemplateArgument> TemplateArgs,
3484 TemplateDeductionInfo &Info) {
3485 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3486}
3489 ArrayRef<TemplateArgument> TemplateArgs,
3490 TemplateDeductionInfo &Info) {
3491 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3492}
3493
3497 if (TD->isInvalidDecl())
3499
3500 QualType PType;
3501 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3502 // Use the InjectedClassNameType.
3503 PType = Context.getCanonicalTagType(CTD->getTemplatedDecl());
3504 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3505 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3506 } else {
3507 assert(false && "Expected a class or alias template");
3508 }
3509
3510 // Unevaluated SFINAE context.
3513 SFINAETrap Trap(*this);
3514
3515 // This deduction has no relation to any outer instantiation we might be
3516 // performing.
3517 LocalInstantiationScope InstantiationScope(*this);
3518
3520 TD->getTemplateParameters()->size());
3523 if (auto DeducedResult = DeduceTemplateArguments(
3524 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3525 DeducedResult != TemplateDeductionResult::Success) {
3526 return DeducedResult;
3527 }
3528
3529 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3530 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3531 if (Inst.isInvalid())
3533
3536 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3537 });
3538
3540 return Result;
3541
3542 if (Trap.hasErrorOccurred())
3544
3546}
3547
3548/// Determine whether the given type T is a simple-template-id type.
3550 if (const TemplateSpecializationType *Spec
3552 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3553
3554 // C++17 [temp.local]p2:
3555 // the injected-class-name [...] is equivalent to the template-name followed
3556 // by the template-arguments of the class template specialization or partial
3557 // specialization enclosed in <>
3558 // ... which means it's equivalent to a simple-template-id.
3559 //
3560 // This only arises during class template argument deduction for a copy
3561 // deduction candidate, where it permits slicing.
3562 if (isa<InjectedClassNameType>(T.getCanonicalType()))
3563 return true;
3564
3565 return false;
3566}
3567
3570 TemplateArgumentListInfo &ExplicitTemplateArgs,
3573 TemplateDeductionInfo &Info) {
3574 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3575 TemplateParameterList *TemplateParams
3576 = FunctionTemplate->getTemplateParameters();
3577
3578 if (ExplicitTemplateArgs.size() == 0) {
3579 // No arguments to substitute; just copy over the parameter types and
3580 // fill in the function type.
3581 for (auto *P : Function->parameters())
3582 ParamTypes.push_back(P->getType());
3583
3584 if (FunctionType)
3585 *FunctionType = Function->getType();
3587 }
3588
3589 // Unevaluated SFINAE context.
3592 SFINAETrap Trap(*this);
3593
3594 // C++ [temp.arg.explicit]p3:
3595 // Template arguments that are present shall be specified in the
3596 // declaration order of their corresponding template-parameters. The
3597 // template argument list shall not specify more template-arguments than
3598 // there are corresponding template-parameters.
3599
3600 // Enter a new template instantiation context where we check the
3601 // explicitly-specified template arguments against this function template,
3602 // and then substitute them into the function parameter types.
3605 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3607 if (Inst.isInvalid())
3609
3612 ExplicitTemplateArgs, /*DefaultArgs=*/{},
3613 /*PartialTemplateArgs=*/true, CTAI,
3614 /*UpdateArgsWithConversions=*/false) ||
3615 Trap.hasErrorOccurred()) {
3616 unsigned Index = CTAI.SugaredConverted.size();
3617 if (Index >= TemplateParams->size())
3619 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3621 }
3622
3623 // Form the template argument list from the explicitly-specified
3624 // template arguments.
3625 TemplateArgumentList *SugaredExplicitArgumentList =
3627 TemplateArgumentList *CanonicalExplicitArgumentList =
3629 Info.setExplicitArgs(SugaredExplicitArgumentList,
3630 CanonicalExplicitArgumentList);
3631
3632 // Template argument deduction and the final substitution should be
3633 // done in the context of the templated declaration. Explicit
3634 // argument substitution, on the other hand, needs to happen in the
3635 // calling context.
3636 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3637
3638 // If we deduced template arguments for a template parameter pack,
3639 // note that the template argument pack is partially substituted and record
3640 // the explicit template arguments. They'll be used as part of deduction
3641 // for this template parameter pack.
3642 unsigned PartiallySubstitutedPackIndex = -1u;
3643 if (!CTAI.SugaredConverted.empty()) {
3644 const TemplateArgument &Arg = CTAI.SugaredConverted.back();
3645 if (Arg.getKind() == TemplateArgument::Pack) {
3646 auto *Param = TemplateParams->getParam(CTAI.SugaredConverted.size() - 1);
3647 // If this is a fully-saturated fixed-size pack, it should be
3648 // fully-substituted, not partially-substituted.
3649 UnsignedOrNone Expansions = getExpandedPackSize(Param);
3650 if (!Expansions || Arg.pack_size() < *Expansions) {
3651 PartiallySubstitutedPackIndex = CTAI.SugaredConverted.size() - 1;
3653 Param, Arg.pack_begin(), Arg.pack_size());
3654 }
3655 }
3656 }
3657
3658 const FunctionProtoType *Proto
3659 = Function->getType()->getAs<FunctionProtoType>();
3660 assert(Proto && "Function template does not have a prototype?");
3661
3662 // Isolate our substituted parameters from our caller.
3663 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3664
3665 ExtParameterInfoBuilder ExtParamInfos;
3666
3668 SugaredExplicitArgumentList->asArray(),
3669 /*Final=*/true);
3670
3671 // Instantiate the types of each of the function parameters given the
3672 // explicitly-specified template arguments. If the function has a trailing
3673 // return type, substitute it after the arguments to ensure we substitute
3674 // in lexical order.
3675 if (Proto->hasTrailingReturn()) {
3676 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3677 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3678 /*params=*/nullptr, ExtParamInfos))
3680 }
3681
3682 // Instantiate the return type.
3683 QualType ResultType;
3684 {
3685 // C++11 [expr.prim.general]p3:
3686 // If a declaration declares a member function or member function
3687 // template of a class X, the expression this is a prvalue of type
3688 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3689 // and the end of the function-definition, member-declarator, or
3690 // declarator.
3691 Qualifiers ThisTypeQuals;
3692 CXXRecordDecl *ThisContext = nullptr;
3693 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3694 ThisContext = Method->getParent();
3695 ThisTypeQuals = Method->getMethodQualifiers();
3696 }
3697
3698 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3700
3701 ResultType =
3702 SubstType(Proto->getReturnType(), MLTAL,
3703 Function->getTypeSpecStartLoc(), Function->getDeclName());
3704 if (ResultType.isNull() || Trap.hasErrorOccurred())
3706 // CUDA: Kernel function must have 'void' return type.
3707 if (getLangOpts().CUDA)
3708 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3709 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3710 << Function->getType() << Function->getSourceRange();
3712 }
3713 }
3714
3715 // Instantiate the types of each of the function parameters given the
3716 // explicitly-specified template arguments if we didn't do so earlier.
3717 if (!Proto->hasTrailingReturn() &&
3718 SubstParmTypes(Function->getLocation(), Function->parameters(),
3719 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3720 /*params*/ nullptr, ExtParamInfos))
3722
3723 if (FunctionType) {
3724 auto EPI = Proto->getExtProtoInfo();
3725 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3726 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3727 Function->getLocation(),
3728 Function->getDeclName(),
3729 EPI);
3730 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3732 }
3733
3734 // C++ [temp.arg.explicit]p2:
3735 // Trailing template arguments that can be deduced (14.8.2) may be
3736 // omitted from the list of explicit template-arguments. If all of the
3737 // template arguments can be deduced, they may all be omitted; in this
3738 // case, the empty template argument list <> itself may also be omitted.
3739 //
3740 // Take all of the explicitly-specified arguments and put them into
3741 // the set of deduced template arguments. The partially-substituted
3742 // parameter pack, however, will be set to NULL since the deduction
3743 // mechanism handles the partially-substituted argument pack directly.
3744 Deduced.reserve(TemplateParams->size());
3745 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3746 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3747 if (I == PartiallySubstitutedPackIndex)
3748 Deduced.push_back(DeducedTemplateArgument());
3749 else
3750 Deduced.push_back(Arg);
3751 }
3752
3754}
3755
3756/// Check whether the deduced argument type for a call to a function
3757/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3760 Sema::OriginalCallArg OriginalArg,
3761 QualType DeducedA) {
3762 ASTContext &Context = S.Context;
3763
3764 auto Failed = [&]() -> TemplateDeductionResult {
3765 Info.FirstArg = TemplateArgument(DeducedA);
3766 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3767 Info.CallArgIndex = OriginalArg.ArgIdx;
3768 return OriginalArg.DecomposedParam
3771 };
3772
3773 QualType A = OriginalArg.OriginalArgType;
3774 QualType OriginalParamType = OriginalArg.OriginalParamType;
3775
3776 // Check for type equality (top-level cv-qualifiers are ignored).
3777 if (Context.hasSameUnqualifiedType(A, DeducedA))
3779
3780 // Strip off references on the argument types; they aren't needed for
3781 // the following checks.
3782 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3783 DeducedA = DeducedARef->getPointeeType();
3784 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3785 A = ARef->getPointeeType();
3786
3787 // C++ [temp.deduct.call]p4:
3788 // [...] However, there are three cases that allow a difference:
3789 // - If the original P is a reference type, the deduced A (i.e., the
3790 // type referred to by the reference) can be more cv-qualified than
3791 // the transformed A.
3792 if (const ReferenceType *OriginalParamRef
3793 = OriginalParamType->getAs<ReferenceType>()) {
3794 // We don't want to keep the reference around any more.
3795 OriginalParamType = OriginalParamRef->getPointeeType();
3796
3797 // FIXME: Resolve core issue (no number yet): if the original P is a
3798 // reference type and the transformed A is function type "noexcept F",
3799 // the deduced A can be F.
3800 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA))
3802
3803 Qualifiers AQuals = A.getQualifiers();
3804 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3805
3806 // Under Objective-C++ ARC, the deduced type may have implicitly
3807 // been given strong or (when dealing with a const reference)
3808 // unsafe_unretained lifetime. If so, update the original
3809 // qualifiers to include this lifetime.
3810 if (S.getLangOpts().ObjCAutoRefCount &&
3811 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3813 (DeducedAQuals.hasConst() &&
3814 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3815 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3816 }
3817
3818 if (AQuals == DeducedAQuals) {
3819 // Qualifiers match; there's nothing to do.
3820 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3821 return Failed();
3822 } else {
3823 // Qualifiers are compatible, so have the argument type adopt the
3824 // deduced argument type's qualifiers as if we had performed the
3825 // qualification conversion.
3826 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3827 }
3828 }
3829
3830 // - The transformed A can be another pointer or pointer to member
3831 // type that can be converted to the deduced A via a function pointer
3832 // conversion and/or a qualification conversion.
3833 //
3834 // Also allow conversions which merely strip __attribute__((noreturn)) from
3835 // function types (recursively).
3836 bool ObjCLifetimeConversion = false;
3837 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3838 (S.IsQualificationConversion(A, DeducedA, false,
3839 ObjCLifetimeConversion) ||
3840 S.IsFunctionConversion(A, DeducedA)))
3842
3843 // - If P is a class and P has the form simple-template-id, then the
3844 // transformed A can be a derived class of the deduced A. [...]
3845 // [...] Likewise, if P is a pointer to a class of the form
3846 // simple-template-id, the transformed A can be a pointer to a
3847 // derived class pointed to by the deduced A.
3848 if (const PointerType *OriginalParamPtr
3849 = OriginalParamType->getAs<PointerType>()) {
3850 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3851 if (const PointerType *APtr = A->getAs<PointerType>()) {
3852 if (A->getPointeeType()->isRecordType()) {
3853 OriginalParamType = OriginalParamPtr->getPointeeType();
3854 DeducedA = DeducedAPtr->getPointeeType();
3855 A = APtr->getPointeeType();
3856 }
3857 }
3858 }
3859 }
3860
3861 if (Context.hasSameUnqualifiedType(A, DeducedA))
3863
3864 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3865 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3867
3868 return Failed();
3869}
3870
3871/// Find the pack index for a particular parameter index in an instantiation of
3872/// a function template with specific arguments.
3873///
3874/// \return The pack index for whichever pack produced this parameter, or -1
3875/// if this was not produced by a parameter. Intended to be used as the
3876/// ArgumentPackSubstitutionIndex for further substitutions.
3877// FIXME: We should track this in OriginalCallArgs so we don't need to
3878// reconstruct it here.
3879static UnsignedOrNone
3882 unsigned ParamIdx) {
3883 unsigned Idx = 0;
3884 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3885 if (PD->isParameterPack()) {
3886 UnsignedOrNone NumArgs =
3887 S.getNumArgumentsInExpansion(PD->getType(), Args);
3888 unsigned NumExpansions = NumArgs ? *NumArgs : 1;
3889 if (Idx + NumExpansions > ParamIdx)
3890 return ParamIdx - Idx;
3891 Idx += NumExpansions;
3892 } else {
3893 if (Idx == ParamIdx)
3894 return std::nullopt; // Not a pack expansion
3895 ++Idx;
3896 }
3897 }
3898
3899 llvm_unreachable("parameter index would not be produced from template");
3900}
3901
3902// if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3903// we'll try to instantiate and update its explicit specifier after constraint
3904// checking.
3907 const MultiLevelTemplateArgumentList &SubstArgs,
3909 ArrayRef<TemplateArgument> DeducedArgs) {
3910 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3911 return isa<CXXConstructorDecl>(D)
3912 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3913 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3914 };
3915 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3916 isa<CXXConstructorDecl>(D)
3917 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3918 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3919 };
3920
3921 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3922 Expr *ExplicitExpr = ES.getExpr();
3923 if (!ExplicitExpr)
3925 if (!ExplicitExpr->isValueDependent())
3927
3929 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3931 if (Inst.isInvalid())
3933 Sema::SFINAETrap Trap(S);
3934 const ExplicitSpecifier InstantiatedES =
3935 S.instantiateExplicitSpecifier(SubstArgs, ES);
3936 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3937 Specialization->setInvalidDecl(true);
3939 }
3940 SetExplicitSpecifier(Specialization, InstantiatedES);
3942}
3943
3947 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3949 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3950 bool PartialOverloading, bool PartialOrdering,
3951 bool ForOverloadSetAddressResolution,
3952 llvm::function_ref<bool(bool)> CheckNonDependent) {
3953 // Unevaluated SFINAE context.
3956 SFINAETrap Trap(*this);
3957
3958 // Enter a new template instantiation context while we instantiate the
3959 // actual function declaration.
3960 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3962 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3964 if (Inst.isInvalid())
3966
3967 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3968
3969 // C++ [temp.deduct.type]p2:
3970 // [...] or if any template argument remains neither deduced nor
3971 // explicitly specified, template argument deduction fails.
3972 bool IsIncomplete = false;
3975 *this, FunctionTemplate, FunctionTemplate->getTemplateParameters(),
3976 /*IsDeduced=*/true, Deduced, Info, CTAI, CurrentInstantiationScope,
3977 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
3979 return Result;
3980
3981 // Form the template argument list from the deduced template arguments.
3982 TemplateArgumentList *SugaredDeducedArgumentList =
3984 TemplateArgumentList *CanonicalDeducedArgumentList =
3986 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3987
3988 // Substitute the deduced template arguments into the function template
3989 // declaration to produce the function template specialization.
3990 DeclContext *Owner = FunctionTemplate->getDeclContext();
3991 if (FunctionTemplate->getFriendObjectKind())
3992 Owner = FunctionTemplate->getLexicalDeclContext();
3993 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3994
3995 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/true))
3997
3998 // C++20 [temp.deduct.general]p5: [CWG2369]
3999 // If the function template has associated constraints, those constraints
4000 // are checked for satisfaction. If the constraints are not satisfied, type
4001 // deduction fails.
4002 //
4003 // FIXME: We haven't implemented CWG2369 for lambdas yet, because we need
4004 // to figure out how to instantiate lambda captures to the scope without
4005 // first instantiating the lambda.
4006 bool IsLambda = isLambdaCallOperator(FD) || isLambdaConversionOperator(FD);
4007 if (!IsLambda && !IsIncomplete) {
4009 Info.getLocation(),
4010 FunctionTemplate->getCanonicalDecl()->getTemplatedDecl(),
4017 }
4018 }
4019 // C++ [temp.deduct.call]p10: [CWG1391]
4020 // If deduction succeeds for all parameters that contain
4021 // template-parameters that participate in template argument deduction,
4022 // and all template arguments are explicitly specified, deduced, or
4023 // obtained from default template arguments, remaining parameters are then
4024 // compared with the corresponding arguments. For each remaining parameter
4025 // P with a type that was non-dependent before substitution of any
4026 // explicitly-specified template arguments, if the corresponding argument
4027 // A cannot be implicitly converted to P, deduction fails.
4028 if (CheckNonDependent(/*OnlyInitializeNonUserDefinedConversions=*/false))
4030
4032 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
4033 /*Final=*/false);
4034 Specialization = cast_or_null<FunctionDecl>(
4035 SubstDecl(FD, Owner, SubstArgs));
4036 if (!Specialization || Specialization->isInvalidDecl())
4038
4039 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
4041
4042 // If the template argument list is owned by the function template
4043 // specialization, release it.
4044 if (Specialization->getTemplateSpecializationArgs() ==
4045 CanonicalDeducedArgumentList &&
4046 !Trap.hasErrorOccurred())
4047 Info.takeCanonical();
4048
4049 // There may have been an error that did not prevent us from constructing a
4050 // declaration. Mark the declaration invalid and return with a substitution
4051 // failure.
4052 if (Trap.hasErrorOccurred()) {
4053 Specialization->setInvalidDecl(true);
4055 }
4056
4057 // C++2a [temp.deduct]p5
4058 // [...] When all template arguments have been deduced [...] all uses of
4059 // template parameters [...] are replaced with the corresponding deduced
4060 // or default argument values.
4061 // [...] If the function template has associated constraints
4062 // ([temp.constr.decl]), those constraints are checked for satisfaction
4063 // ([temp.constr.constr]). If the constraints are not satisfied, type
4064 // deduction fails.
4065 if (IsLambda && !IsIncomplete) {
4070
4075 }
4076 }
4077
4078 // We skipped the instantiation of the explicit-specifier during the
4079 // substitution of `FD` before. So, we try to instantiate it back if
4080 // `Specialization` is either a constructor or a conversion function.
4081 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
4084 Info, FunctionTemplate,
4085 DeducedArgs)) {
4087 }
4088 }
4089
4090 if (OriginalCallArgs) {
4091 // C++ [temp.deduct.call]p4:
4092 // In general, the deduction process attempts to find template argument
4093 // values that will make the deduced A identical to A (after the type A
4094 // is transformed as described above). [...]
4095 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4096 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4097 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4098
4099 auto ParamIdx = OriginalArg.ArgIdx;
4100 unsigned ExplicitOffset =
4101 (Specialization->hasCXXExplicitFunctionObjectParameter() &&
4102 !ForOverloadSetAddressResolution)
4103 ? 1
4104 : 0;
4105 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4106 // FIXME: This presumably means a pack ended up smaller than we
4107 // expected while deducing. Should this not result in deduction
4108 // failure? Can it even happen?
4109 continue;
4110
4111 QualType DeducedA;
4112 if (!OriginalArg.DecomposedParam) {
4113 // P is one of the function parameters, just look up its substituted
4114 // type.
4115 DeducedA =
4116 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4117 } else {
4118 // P is a decomposed element of a parameter corresponding to a
4119 // braced-init-list argument. Substitute back into P to find the
4120 // deduced A.
4121 QualType &CacheEntry =
4122 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4123 if (CacheEntry.isNull()) {
4124 ArgPackSubstIndexRAII PackIndex(
4125 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4126 ParamIdx));
4127 CacheEntry =
4128 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4129 Specialization->getTypeSpecStartLoc(),
4130 Specialization->getDeclName());
4131 }
4132 DeducedA = CacheEntry;
4133 }
4134
4135 if (auto TDK =
4136 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4138 return TDK;
4139 }
4140 }
4141
4142 // If we suppressed any diagnostics while performing template argument
4143 // deduction, and if we haven't already instantiated this declaration,
4144 // keep track of these diagnostics. They'll be emitted if this specialization
4145 // is actually used.
4146 if (Info.diag_begin() != Info.diag_end()) {
4147 auto [Pos, Inserted] =
4148 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4149 if (Inserted)
4150 Pos->second.append(Info.diag_begin(), Info.diag_end());
4151 }
4152
4154}
4155
4156/// Gets the type of a function for template-argument-deducton
4157/// purposes when it's considered as part of an overload set.
4159 FunctionDecl *Fn) {
4160 // We may need to deduce the return type of the function now.
4161 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4162 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4163 return {};
4164
4165 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4166 if (Method->isImplicitObjectMemberFunction()) {
4167 // An instance method that's referenced in a form that doesn't
4168 // look like a member pointer is just invalid.
4170 return {};
4171
4173 Fn->getType(), /*Qualifier=*/std::nullopt, Method->getParent());
4174 }
4175
4176 if (!R.IsAddressOfOperand) return Fn->getType();
4177 return S.Context.getPointerType(Fn->getType());
4178}
4179
4180/// Apply the deduction rules for overload sets.
4181///
4182/// \return the null type if this argument should be treated as an
4183/// undeduced context
4184static QualType
4186 Expr *Arg, QualType ParamType,
4187 bool ParamWasReference,
4188 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4189
4191
4192 OverloadExpr *Ovl = R.Expression;
4193
4194 // C++0x [temp.deduct.call]p4
4195 unsigned TDF = 0;
4196 if (ParamWasReference)
4198 if (R.IsAddressOfOperand)
4199 TDF |= TDF_IgnoreQualifiers;
4200
4201 // C++0x [temp.deduct.call]p6:
4202 // When P is a function type, pointer to function type, or pointer
4203 // to member function type:
4204
4205 if (!ParamType->isFunctionType() &&
4206 !ParamType->isFunctionPointerType() &&
4207 !ParamType->isMemberFunctionPointerType()) {
4208 if (Ovl->hasExplicitTemplateArgs()) {
4209 // But we can still look for an explicit specialization.
4210 if (FunctionDecl *ExplicitSpec =
4212 Ovl, /*Complain=*/false,
4213 /*Found=*/nullptr, FailedTSC,
4214 /*ForTypeDeduction=*/true))
4215 return GetTypeOfFunction(S, R, ExplicitSpec);
4216 }
4217
4218 DeclAccessPair DAP;
4219 if (FunctionDecl *Viable =
4221 return GetTypeOfFunction(S, R, Viable);
4222
4223 return {};
4224 }
4225
4226 // Gather the explicit template arguments, if any.
4227 TemplateArgumentListInfo ExplicitTemplateArgs;
4228 if (Ovl->hasExplicitTemplateArgs())
4229 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4231 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4232 E = Ovl->decls_end(); I != E; ++I) {
4233 NamedDecl *D = (*I)->getUnderlyingDecl();
4234
4235 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4236 // - If the argument is an overload set containing one or more
4237 // function templates, the parameter is treated as a
4238 // non-deduced context.
4239 if (!Ovl->hasExplicitTemplateArgs())
4240 return {};
4241
4242 // Otherwise, see if we can resolve a function type
4243 FunctionDecl *Specialization = nullptr;
4244 TemplateDeductionInfo Info(Ovl->getNameLoc());
4245 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4248 continue;
4249
4250 D = Specialization;
4251 }
4252
4253 FunctionDecl *Fn = cast<FunctionDecl>(D);
4254 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4255 if (ArgType.isNull()) continue;
4256
4257 // Function-to-pointer conversion.
4258 if (!ParamWasReference && ParamType->isPointerType() &&
4259 ArgType->isFunctionType())
4260 ArgType = S.Context.getPointerType(ArgType);
4261
4262 // - If the argument is an overload set (not containing function
4263 // templates), trial argument deduction is attempted using each
4264 // of the members of the set. If deduction succeeds for only one
4265 // of the overload set members, that member is used as the
4266 // argument value for the deduction. If deduction succeeds for
4267 // more than one member of the overload set the parameter is
4268 // treated as a non-deduced context.
4269
4270 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4271 // Type deduction is done independently for each P/A pair, and
4272 // the deduced template argument values are then combined.
4273 // So we do not reject deductions which were made elsewhere.
4275 Deduced(TemplateParams->size());
4276 TemplateDeductionInfo Info(Ovl->getNameLoc());
4278 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4279 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4280 /*HasDeducedAnyParam=*/nullptr);
4282 continue;
4283 // C++ [temp.deduct.call]p6:
4284 // [...] If all successful deductions yield the same deduced A, that
4285 // deduced A is the result of deduction; otherwise, the parameter is
4286 // treated as a non-deduced context. [...]
4287 if (!Match.isNull() && !S.isSameOrCompatibleFunctionType(Match, ArgType))
4288 return {};
4289 Match = ArgType;
4290 }
4291
4292 return Match;
4293}
4294
4295/// Perform the adjustments to the parameter and argument types
4296/// described in C++ [temp.deduct.call].
4297///
4298/// \returns true if the caller should not attempt to perform any template
4299/// argument deduction based on this P/A pair because the argument is an
4300/// overloaded function set that could not be resolved.
4302 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4303 QualType &ParamType, QualType &ArgType,
4304 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4305 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4306 // C++0x [temp.deduct.call]p3:
4307 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4308 // are ignored for type deduction.
4309 if (ParamType.hasQualifiers())
4310 ParamType = ParamType.getUnqualifiedType();
4311
4312 // [...] If P is a reference type, the type referred to by P is
4313 // used for type deduction.
4314 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4315 if (ParamRefType)
4316 ParamType = ParamRefType->getPointeeType();
4317
4318 // Overload sets usually make this parameter an undeduced context,
4319 // but there are sometimes special circumstances. Typically
4320 // involving a template-id-expr.
4321 if (ArgType == S.Context.OverloadTy) {
4322 assert(Arg && "expected a non-null arg expression");
4323 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4324 ParamRefType != nullptr, FailedTSC);
4325 if (ArgType.isNull())
4326 return true;
4327 }
4328
4329 if (ParamRefType) {
4330 // If the argument has incomplete array type, try to complete its type.
4331 if (ArgType->isIncompleteArrayType()) {
4332 assert(Arg && "expected a non-null arg expression");
4333 ArgType = S.getCompletedType(Arg);
4334 }
4335
4336 // C++1z [temp.deduct.call]p3:
4337 // If P is a forwarding reference and the argument is an lvalue, the type
4338 // "lvalue reference to A" is used in place of A for type deduction.
4339 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4340 ArgClassification.isLValue()) {
4341 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4342 ArgType = S.Context.getAddrSpaceQualType(
4344 ArgType = S.Context.getLValueReferenceType(ArgType);
4345 }
4346 } else {
4347 // C++ [temp.deduct.call]p2:
4348 // If P is not a reference type:
4349 // - If A is an array type, the pointer type produced by the
4350 // array-to-pointer standard conversion (4.2) is used in place of
4351 // A for type deduction; otherwise,
4352 // - If A is a function type, the pointer type produced by the
4353 // function-to-pointer standard conversion (4.3) is used in place
4354 // of A for type deduction; otherwise,
4355 if (ArgType->canDecayToPointerType())
4356 ArgType = S.Context.getDecayedType(ArgType);
4357 else {
4358 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4359 // type are ignored for type deduction.
4360 ArgType = ArgType.getUnqualifiedType();
4361 }
4362 }
4363
4364 // C++0x [temp.deduct.call]p4:
4365 // In general, the deduction process attempts to find template argument
4366 // values that will make the deduced A identical to A (after the type A
4367 // is transformed as described above). [...]
4369
4370 // - If the original P is a reference type, the deduced A (i.e., the
4371 // type referred to by the reference) can be more cv-qualified than
4372 // the transformed A.
4373 if (ParamRefType)
4375 // - The transformed A can be another pointer or pointer to member
4376 // type that can be converted to the deduced A via a qualification
4377 // conversion (4.4).
4378 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4379 ArgType->isObjCObjectPointerType())
4380 TDF |= TDF_IgnoreQualifiers;
4381 // - If P is a class and P has the form simple-template-id, then the
4382 // transformed A can be a derived class of the deduced A. Likewise,
4383 // if P is a pointer to a class of the form simple-template-id, the
4384 // transformed A can be a pointer to a derived class pointed to by
4385 // the deduced A.
4386 if (isSimpleTemplateIdType(ParamType) ||
4387 (ParamType->getAs<PointerType>() &&
4389 ParamType->castAs<PointerType>()->getPointeeType())))
4390 TDF |= TDF_DerivedClass;
4391
4392 return false;
4393}
4394
4395static bool
4397 QualType T);
4398
4400 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4401 QualType ParamType, QualType ArgType,
4402 Expr::Classification ArgClassification, Expr *Arg,
4406 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4407 TemplateSpecCandidateSet *FailedTSC = nullptr);
4408
4409/// Attempt template argument deduction from an initializer list
4410/// deemed to be an argument in a function call.
4412 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4415 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4416 unsigned TDF) {
4417 // C++ [temp.deduct.call]p1: (CWG 1591)
4418 // If removing references and cv-qualifiers from P gives
4419 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4420 // a non-empty initializer list, then deduction is performed instead for
4421 // each element of the initializer list, taking P0 as a function template
4422 // parameter type and the initializer element as its argument
4423 //
4424 // We've already removed references and cv-qualifiers here.
4425 if (!ILE->getNumInits())
4427
4428 QualType ElTy;
4429 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4430 if (ArrTy)
4431 ElTy = ArrTy->getElementType();
4432 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4433 // Otherwise, an initializer list argument causes the parameter to be
4434 // considered a non-deduced context
4436 }
4437
4438 // Resolving a core issue: a braced-init-list containing any designators is
4439 // a non-deduced context.
4440 for (Expr *E : ILE->inits())
4441 if (isa<DesignatedInitExpr>(E))
4443
4444 // Deduction only needs to be done for dependent types.
4445 if (ElTy->isDependentType()) {
4446 for (Expr *E : ILE->inits()) {
4448 S, TemplateParams, 0, ElTy, E->getType(),
4449 E->Classify(S.getASTContext()), E, Info, Deduced,
4450 OriginalCallArgs, true, ArgIdx, TDF);
4452 return Result;
4453 }
4454 }
4455
4456 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4457 // from the length of the initializer list.
4458 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4459 // Determine the array bound is something we can deduce.
4461 Info, DependentArrTy->getSizeExpr())) {
4462 // We can perform template argument deduction for the given non-type
4463 // template parameter.
4464 // C++ [temp.deduct.type]p13:
4465 // The type of N in the type T[N] is std::size_t.
4467 llvm::APInt Size(S.Context.getIntWidth(T),
4470 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4471 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4472 /*HasDeducedAnyParam=*/nullptr);
4474 return Result;
4475 }
4476 }
4477
4479}
4480
4481/// Perform template argument deduction per [temp.deduct.call] for a
4482/// single parameter / argument pair.
4484 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4485 QualType ParamType, QualType ArgType,
4486 Expr::Classification ArgClassification, Expr *Arg,
4490 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4491 TemplateSpecCandidateSet *FailedTSC) {
4492
4493 QualType OrigParamType = ParamType;
4494
4495 // If P is a reference type [...]
4496 // If P is a cv-qualified type [...]
4498 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4499 ArgClassification, Arg, TDF, FailedTSC))
4501
4502 // If [...] the argument is a non-empty initializer list [...]
4503 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4504 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4505 Deduced, OriginalCallArgs, ArgIdx, TDF);
4506
4507 // [...] the deduction process attempts to find template argument values
4508 // that will make the deduced A identical to A
4509 //
4510 // Keep track of the argument type and corresponding parameter index,
4511 // so we can check for compatibility between the deduced A and A.
4512 if (Arg)
4513 OriginalCallArgs.push_back(
4514 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4516 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4517 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4518 /*HasDeducedAnyParam=*/nullptr);
4519}
4520
4523 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4525 bool PartialOverloading, bool AggregateDeductionCandidate,
4526 bool PartialOrdering, QualType ObjectType,
4527 Expr::Classification ObjectClassification,
4528 bool ForOverloadSetAddressResolution,
4529 llvm::function_ref<bool(ArrayRef<QualType>, bool)> CheckNonDependent) {
4530 if (FunctionTemplate->isInvalidDecl())
4532
4533 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4534 unsigned NumParams = Function->getNumParams();
4535 bool HasExplicitObject = false;
4536 int ExplicitObjectOffset = 0;
4537
4538 // [C++26] [over.call.func]p3
4539 // If the primary-expression is the address of an overload set,
4540 // the argument list is the same as the expression-list in the call.
4541 // Otherwise, the argument list is the expression-list in the call augmented
4542 // by the addition of an implied object argument as in a qualified function
4543 // call.
4544 if (!ForOverloadSetAddressResolution &&
4545 Function->hasCXXExplicitFunctionObjectParameter()) {
4546 HasExplicitObject = true;
4547 ExplicitObjectOffset = 1;
4548 }
4549
4550 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4551
4552 // C++ [temp.deduct.call]p1:
4553 // Template argument deduction is done by comparing each function template
4554 // parameter type (call it P) with the type of the corresponding argument
4555 // of the call (call it A) as described below.
4556 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4557 !PartialOverloading)
4559 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4560 PartialOverloading)) {
4561 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4562 if (Proto->isTemplateVariadic())
4563 /* Do nothing */;
4564 else if (!Proto->isVariadic())
4566 }
4567
4568 // The types of the parameters from which we will perform template argument
4569 // deduction.
4570 LocalInstantiationScope InstScope(*this);
4571 TemplateParameterList *TemplateParams
4572 = FunctionTemplate->getTemplateParameters();
4574 SmallVector<QualType, 8> ParamTypes;
4575 unsigned NumExplicitlySpecified = 0;
4576 if (ExplicitTemplateArgs) {
4579 Result = SubstituteExplicitTemplateArguments(
4580 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4581 Info);
4582 });
4584 return Result;
4585
4586 NumExplicitlySpecified = Deduced.size();
4587 } else {
4588 // Just fill in the parameter types from the function declaration.
4589 for (unsigned I = 0; I != NumParams; ++I)
4590 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4591 }
4592
4593 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4594
4595 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4596 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4597 bool ExplicitObjectArgument) {
4598 // C++ [demp.deduct.call]p1: (DR1391)
4599 // Template argument deduction is done by comparing each function template
4600 // parameter that contains template-parameters that participate in
4601 // template argument deduction ...
4602 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4604
4605 if (ExplicitObjectArgument) {
4606 // ... with the type of the corresponding argument
4608 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4609 ObjectClassification,
4610 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4611 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4612 }
4613
4614 // ... with the type of the corresponding argument
4616 *this, TemplateParams, FirstInnerIndex, ParamType,
4617 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4618 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4619 ArgIdx, /*TDF*/ 0);
4620 };
4621
4622 // Deduce template arguments from the function parameters.
4623 Deduced.resize(TemplateParams->size());
4624 SmallVector<QualType, 8> ParamTypesForArgChecking;
4625 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4626 ParamIdx != NumParamTypes; ++ParamIdx) {
4627 QualType ParamType = ParamTypes[ParamIdx];
4628
4629 const PackExpansionType *ParamExpansion =
4630 dyn_cast<PackExpansionType>(ParamType);
4631 if (!ParamExpansion) {
4632 // Simple case: matching a function parameter to a function argument.
4633 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4634 break;
4635
4636 ParamTypesForArgChecking.push_back(ParamType);
4637
4638 if (ParamIdx == 0 && HasExplicitObject) {
4639 if (ObjectType.isNull())
4641
4642 if (auto Result = DeduceCallArgument(ParamType, 0,
4643 /*ExplicitObjectArgument=*/true);
4645 return Result;
4646 continue;
4647 }
4648
4649 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4650 /*ExplicitObjectArgument=*/false);
4652 return Result;
4653
4654 continue;
4655 }
4656
4657 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4658
4659 QualType ParamPattern = ParamExpansion->getPattern();
4660 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4661 ParamPattern,
4662 AggregateDeductionCandidate && IsTrailingPack);
4663
4664 // C++0x [temp.deduct.call]p1:
4665 // For a function parameter pack that occurs at the end of the
4666 // parameter-declaration-list, the type A of each remaining argument of
4667 // the call is compared with the type P of the declarator-id of the
4668 // function parameter pack. Each comparison deduces template arguments
4669 // for subsequent positions in the template parameter packs expanded by
4670 // the function parameter pack. When a function parameter pack appears
4671 // in a non-deduced context [not at the end of the list], the type of
4672 // that parameter pack is never deduced.
4673 //
4674 // FIXME: The above rule allows the size of the parameter pack to change
4675 // after we skip it (in the non-deduced case). That makes no sense, so
4676 // we instead notionally deduce the pack against N arguments, where N is
4677 // the length of the explicitly-specified pack if it's expanded by the
4678 // parameter pack and 0 otherwise, and we treat each deduction as a
4679 // non-deduced context.
4680 if (IsTrailingPack || PackScope.hasFixedArity()) {
4681 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4682 PackScope.nextPackElement(), ++ArgIdx) {
4683 ParamTypesForArgChecking.push_back(ParamPattern);
4684 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4685 /*ExplicitObjectArgument=*/false);
4687 return Result;
4688 }
4689 } else {
4690 // If the parameter type contains an explicitly-specified pack that we
4691 // could not expand, skip the number of parameters notionally created
4692 // by the expansion.
4693 UnsignedOrNone NumExpansions = ParamExpansion->getNumExpansions();
4694 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4695 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4696 ++I, ++ArgIdx) {
4697 ParamTypesForArgChecking.push_back(ParamPattern);
4698 // FIXME: Should we add OriginalCallArgs for these? What if the
4699 // corresponding argument is a list?
4700 PackScope.nextPackElement();
4701 }
4702 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4703 PackScope.isDeducedFromEarlierParameter()) {
4704 // [temp.deduct.general#3]
4705 // When all template arguments have been deduced
4706 // or obtained from default template arguments, all uses of template
4707 // parameters in the template parameter list of the template are
4708 // replaced with the corresponding deduced or default argument values
4709 //
4710 // If we have a trailing parameter pack, that has been deduced
4711 // previously we substitute the pack here in a similar fashion as
4712 // above with the trailing parameter packs. The main difference here is
4713 // that, in this case we are not processing all of the remaining
4714 // arguments. We are only process as many arguments as we have in
4715 // the already deduced parameter.
4716 UnsignedOrNone ArgPosAfterSubstitution =
4717 PackScope.getSavedPackSizeIfAllEqual();
4718 if (!ArgPosAfterSubstitution)
4719 continue;
4720
4721 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4722 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4723 ParamTypesForArgChecking.push_back(ParamPattern);
4724 if (auto Result =
4725 DeduceCallArgument(ParamPattern, ArgIdx,
4726 /*ExplicitObjectArgument=*/false);
4728 return Result;
4729
4730 PackScope.nextPackElement();
4731 }
4732 }
4733 }
4734
4735 // Build argument packs for each of the parameter packs expanded by this
4736 // pack expansion.
4737 if (auto Result = PackScope.finish();
4739 return Result;
4740 }
4741
4742 // Capture the context in which the function call is made. This is the context
4743 // that is needed when the accessibility of template arguments is checked.
4744 DeclContext *CallingCtx = CurContext;
4745
4748 Result = FinishTemplateArgumentDeduction(
4749 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4750 &OriginalCallArgs, PartialOverloading, PartialOrdering,
4751 ForOverloadSetAddressResolution,
4752 [&, CallingCtx](bool OnlyInitializeNonUserDefinedConversions) {
4753 ContextRAII SavedContext(*this, CallingCtx);
4754 return CheckNonDependent(ParamTypesForArgChecking,
4755 OnlyInitializeNonUserDefinedConversions);
4756 });
4757 });
4758 return Result;
4759}
4760
4763 bool AdjustExceptionSpec) {
4764 if (ArgFunctionType.isNull())
4765 return ArgFunctionType;
4766
4767 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4768 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4769 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4770 bool Rebuild = false;
4771
4772 CallingConv CC = FunctionTypeP->getCallConv();
4773 if (EPI.ExtInfo.getCC() != CC) {
4774 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4775 Rebuild = true;
4776 }
4777
4778 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4779 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4780 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4781 Rebuild = true;
4782 }
4783
4784 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4785 ArgFunctionTypeP->hasExceptionSpec())) {
4786 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4787 Rebuild = true;
4788 }
4789
4790 if (!Rebuild)
4791 return ArgFunctionType;
4792
4793 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4794 ArgFunctionTypeP->getParamTypes(), EPI);
4795}
4796
4799 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4801 bool IsAddressOfFunction) {
4802 if (FunctionTemplate->isInvalidDecl())
4804
4805 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4806 TemplateParameterList *TemplateParams
4807 = FunctionTemplate->getTemplateParameters();
4808 QualType FunctionType = Function->getType();
4809
4810 // Substitute any explicit template arguments.
4811 LocalInstantiationScope InstScope(*this);
4813 unsigned NumExplicitlySpecified = 0;
4814 SmallVector<QualType, 4> ParamTypes;
4815 if (ExplicitTemplateArgs) {
4818 Result = SubstituteExplicitTemplateArguments(
4819 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4820 &FunctionType, Info);
4821 });
4823 return Result;
4824
4825 NumExplicitlySpecified = Deduced.size();
4826 }
4827
4828 // When taking the address of a function, we require convertibility of
4829 // the resulting function type. Otherwise, we allow arbitrary mismatches
4830 // of calling convention and noreturn.
4831 if (!IsAddressOfFunction)
4832 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4833 /*AdjustExceptionSpec*/false);
4834
4835 // Unevaluated SFINAE context.
4836 std::optional<EnterExpressionEvaluationContext> Unevaluated(
4838 SFINAETrap Trap(*this);
4839
4840 Deduced.resize(TemplateParams->size());
4841
4842 // If the function has a deduced return type, substitute it for a dependent
4843 // type so that we treat it as a non-deduced context in what follows.
4844 bool HasDeducedReturnType = false;
4845 if (getLangOpts().CPlusPlus14 &&
4846 Function->getReturnType()->getContainedAutoType()) {
4848 HasDeducedReturnType = true;
4849 }
4850
4851 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4852 unsigned TDF =
4854 // Deduce template arguments from the function type.
4856 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4857 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4858 /*HasDeducedAnyParam=*/nullptr);
4860 return Result;
4861 }
4862
4865 Result = FinishTemplateArgumentDeduction(
4866 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4867 /*OriginalCallArgs=*/nullptr, /*PartialOverloading=*/false,
4868 /*PartialOrdering=*/true, IsAddressOfFunction);
4869 });
4871 return Result;
4872
4873 // If the function has a deduced return type, deduce it now, so we can check
4874 // that the deduced function type matches the requested type.
4875 if (HasDeducedReturnType && IsAddressOfFunction &&
4876 Specialization->getReturnType()->isUndeducedType() &&
4879
4880 Unevaluated = std::nullopt;
4881 // [C++26][expr.const]/p17
4882 // An expression or conversion is immediate-escalating if it is not initially
4883 // in an immediate function context and it is [...]
4884 // a potentially-evaluated id-expression that denotes an immediate function.
4885 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4886 Specialization->isImmediateEscalating() &&
4887 currentEvaluationContext().isPotentiallyEvaluated() &&
4889 Info.getLocation()))
4891
4892 // Adjust the exception specification of the argument to match the
4893 // substituted and resolved type we just formed. (Calling convention and
4894 // noreturn can't be dependent, so we don't actually need this for them
4895 // right now.)
4896 QualType SpecializationType = Specialization->getType();
4897 if (!IsAddressOfFunction) {
4898 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4899 /*AdjustExceptionSpec*/true);
4900
4901 // Revert placeholder types in the return type back to undeduced types so
4902 // that the comparison below compares the declared return types.
4903 if (HasDeducedReturnType) {
4904 SpecializationType = SubstAutoType(SpecializationType, QualType());
4905 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4906 }
4907 }
4908
4909 // If the requested function type does not match the actual type of the
4910 // specialization with respect to arguments of compatible pointer to function
4911 // types, template argument deduction fails.
4912 if (!ArgFunctionType.isNull()) {
4913 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4914 SpecializationType, ArgFunctionType)
4916 SpecializationType, ArgFunctionType)) {
4917 Info.FirstArg = TemplateArgument(SpecializationType);
4918 Info.SecondArg = TemplateArgument(ArgFunctionType);
4920 }
4921 }
4922
4924}
4925
4927 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4928 Expr::Classification ObjectClassification, QualType A,
4930 if (ConversionTemplate->isInvalidDecl())
4932
4933 CXXConversionDecl *ConversionGeneric
4934 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4935
4936 QualType P = ConversionGeneric->getConversionType();
4937 bool IsReferenceP = P->isReferenceType();
4938 bool IsReferenceA = A->isReferenceType();
4939
4940 // C++0x [temp.deduct.conv]p2:
4941 // If P is a reference type, the type referred to by P is used for
4942 // type deduction.
4943 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4944 P = PRef->getPointeeType();
4945
4946 // C++0x [temp.deduct.conv]p4:
4947 // [...] If A is a reference type, the type referred to by A is used
4948 // for type deduction.
4949 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4950 A = ARef->getPointeeType();
4951 // We work around a defect in the standard here: cv-qualifiers are also
4952 // removed from P and A in this case, unless P was a reference type. This
4953 // seems to mostly match what other compilers are doing.
4954 if (!IsReferenceP) {
4955 A = A.getUnqualifiedType();
4956 P = P.getUnqualifiedType();
4957 }
4958
4959 // C++ [temp.deduct.conv]p3:
4960 //
4961 // If A is not a reference type:
4962 } else {
4963 assert(!A->isReferenceType() && "Reference types were handled above");
4964
4965 // - If P is an array type, the pointer type produced by the
4966 // array-to-pointer standard conversion (4.2) is used in place
4967 // of P for type deduction; otherwise,
4968 if (P->isArrayType())
4970 // - If P is a function type, the pointer type produced by the
4971 // function-to-pointer standard conversion (4.3) is used in
4972 // place of P for type deduction; otherwise,
4973 else if (P->isFunctionType())
4975 // - If P is a cv-qualified type, the top level cv-qualifiers of
4976 // P's type are ignored for type deduction.
4977 else
4978 P = P.getUnqualifiedType();
4979
4980 // C++0x [temp.deduct.conv]p4:
4981 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4982 // type are ignored for type deduction. If A is a reference type, the type
4983 // referred to by A is used for type deduction.
4984 A = A.getUnqualifiedType();
4985 }
4986
4987 // Unevaluated SFINAE context.
4990 SFINAETrap Trap(*this);
4991
4992 // C++ [temp.deduct.conv]p1:
4993 // Template argument deduction is done by comparing the return
4994 // type of the template conversion function (call it P) with the
4995 // type that is required as the result of the conversion (call it
4996 // A) as described in 14.8.2.4.
4997 TemplateParameterList *TemplateParams
4998 = ConversionTemplate->getTemplateParameters();
5000 Deduced.resize(TemplateParams->size());
5001
5002 // C++0x [temp.deduct.conv]p4:
5003 // In general, the deduction process attempts to find template
5004 // argument values that will make the deduced A identical to
5005 // A. However, there are two cases that allow a difference:
5006 unsigned TDF = 0;
5007 // - If the original A is a reference type, A can be more
5008 // cv-qualified than the deduced A (i.e., the type referred to
5009 // by the reference)
5010 if (IsReferenceA)
5012 // - The deduced A can be another pointer or pointer to member
5013 // type that can be converted to A via a qualification
5014 // conversion.
5015 //
5016 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
5017 // both P and A are pointers or member pointers. In this case, we
5018 // just ignore cv-qualifiers completely).
5019 if ((P->isPointerType() && A->isPointerType()) ||
5020 (P->isMemberPointerType() && A->isMemberPointerType()))
5021 TDF |= TDF_IgnoreQualifiers;
5022
5024 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
5025 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
5028 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
5029 ParamType, ObjectType, ObjectClassification,
5030 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
5031 /*Decomposed*/ false, 0, /*TDF*/ 0);
5033 return Result;
5034 }
5035
5037 *this, TemplateParams, P, A, Info, Deduced, TDF,
5038 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
5039 /*HasDeducedAnyParam=*/nullptr);
5041 return Result;
5042
5043 // Create an Instantiation Scope for finalizing the operator.
5044 LocalInstantiationScope InstScope(*this);
5045 // Finish template argument deduction.
5046 FunctionDecl *ConversionSpecialized = nullptr;
5049 Result = FinishTemplateArgumentDeduction(
5050 ConversionTemplate, Deduced, 0, ConversionSpecialized, Info,
5051 &OriginalCallArgs, /*PartialOverloading=*/false,
5052 /*PartialOrdering=*/false, /*ForOverloadSetAddressResolution*/ false);
5053 });
5054 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
5055 return Result;
5056}
5057
5060 TemplateArgumentListInfo *ExplicitTemplateArgs,
5063 bool IsAddressOfFunction) {
5064 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5065 QualType(), Specialization, Info,
5066 IsAddressOfFunction);
5067}
5068
5069namespace {
5070 struct DependentAuto { bool IsPack; };
5071
5072 /// Substitute the 'auto' specifier or deduced template specialization type
5073 /// specifier within a type for a given replacement type.
5074 class SubstituteDeducedTypeTransform :
5075 public TreeTransform<SubstituteDeducedTypeTransform> {
5076 QualType Replacement;
5077 bool ReplacementIsPack;
5078 bool UseTypeSugar;
5080
5081 public:
5082 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5083 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5084 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
5085
5086 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5087 bool UseTypeSugar = true)
5088 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5089 Replacement(Replacement), ReplacementIsPack(false),
5090 UseTypeSugar(UseTypeSugar) {}
5091
5092 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5093 assert(isa<TemplateTypeParmType>(Replacement) &&
5094 "unexpected unsugared replacement kind");
5095 QualType Result = Replacement;
5097 NewTL.setNameLoc(TL.getNameLoc());
5098 return Result;
5099 }
5100
5101 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5102 // If we're building the type pattern to deduce against, don't wrap the
5103 // substituted type in an AutoType. Certain template deduction rules
5104 // apply only when a template type parameter appears directly (and not if
5105 // the parameter is found through desugaring). For instance:
5106 // auto &&lref = lvalue;
5107 // must transform into "rvalue reference to T" not "rvalue reference to
5108 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5109 //
5110 // FIXME: Is this still necessary?
5111 if (!UseTypeSugar)
5112 return TransformDesugared(TLB, TL);
5113
5114 QualType Result = SemaRef.Context.getAutoType(
5115 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
5116 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
5118 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5119 NewTL.copy(TL);
5120 return Result;
5121 }
5122
5123 QualType TransformDeducedTemplateSpecializationType(
5125 if (!UseTypeSugar)
5126 return TransformDesugared(TLB, TL);
5127
5128 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
5130 Replacement, Replacement.isNull());
5131 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5132 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
5133 NewTL.setNameLoc(TL.getNameLoc());
5134 NewTL.setQualifierLoc(TL.getQualifierLoc());
5135 return Result;
5136 }
5137
5138 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5139 // Lambdas never need to be transformed.
5140 return E;
5141 }
5142 bool TransformExceptionSpec(SourceLocation Loc,
5144 SmallVectorImpl<QualType> &Exceptions,
5145 bool &Changed) {
5146 if (ESI.Type == EST_Uninstantiated) {
5147 ESI.instantiate();
5148 Changed = true;
5149 }
5150 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5151 }
5152
5153 QualType Apply(TypeLoc TL) {
5154 // Create some scratch storage for the transformed type locations.
5155 // FIXME: We're just going to throw this information away. Don't build it.
5156 TypeLocBuilder TLB;
5157 TLB.reserve(TL.getFullDataSize());
5158 return TransformType(TLB, TL);
5159 }
5160 };
5161
5162} // namespace
5163
5166 QualType Deduced) {
5167 ConstraintSatisfaction Satisfaction;
5168 ConceptDecl *Concept = cast<ConceptDecl>(Type.getTypeConstraintConcept());
5169 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5170 TypeLoc.getRAngleLoc());
5171 TemplateArgs.addArgument(
5174 Deduced, TypeLoc.getNameLoc())));
5175 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5176 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5177
5179 if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
5180 /*DefaultArgs=*/{},
5181 /*PartialTemplateArgs=*/false, CTAI))
5182 return true;
5184 /*Final=*/false);
5185 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5186 // that the template arguments of the constraint can be preserved. For
5187 // example:
5188 //
5189 // template <class T>
5190 // concept C = []<D U = void>() { return true; }();
5191 //
5192 // We need the argument for T while evaluating type constraint D in
5193 // building the CallExpr to the lambda.
5197 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5198 CTAI.CanonicalConverted));
5200 Concept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,
5201 TypeLoc.getLocalSourceRange(), Satisfaction))
5202 return true;
5203 if (!Satisfaction.IsSatisfied) {
5204 std::string Buf;
5205 llvm::raw_string_ostream OS(Buf);
5206 OS << "'" << Concept->getName();
5207 if (TypeLoc.hasExplicitTemplateArgs()) {
5209 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5210 Type.getTypeConstraintConcept()->getTemplateParameters());
5211 }
5212 OS << "'";
5213 S.Diag(TypeLoc.getConceptNameLoc(),
5214 diag::err_placeholder_constraints_not_satisfied)
5215 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5216 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5217 return true;
5218 }
5219 return false;
5220}
5221
5224 TemplateDeductionInfo &Info, bool DependentDeduction,
5225 bool IgnoreConstraints,
5226 TemplateSpecCandidateSet *FailedTSC) {
5227 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5228 if (Init->containsErrors())
5230
5231 const AutoType *AT = Type.getType()->getContainedAutoType();
5232 assert(AT);
5233
5234 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5235 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5236 if (NonPlaceholder.isInvalid())
5238 Init = NonPlaceholder.get();
5239 }
5240
5241 DependentAuto DependentResult = {
5242 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5243
5244 if (!DependentDeduction &&
5245 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5246 Init->containsUnexpandedParameterPack())) {
5247 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5248 assert(!Result.isNull() && "substituting DependentTy can't fail");
5250 }
5251
5252 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5253 auto *String = dyn_cast<StringLiteral>(Init);
5254 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5255 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5256 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5257 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5258 assert(!Result.isNull() && "substituting DependentTy can't fail");
5260 }
5261
5262 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5263 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5264 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5265 }
5266
5267 auto *InitList = dyn_cast<InitListExpr>(Init);
5268 if (!getLangOpts().CPlusPlus && InitList) {
5269 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5270 << (int)AT->getKeyword() << getLangOpts().C23;
5272 }
5273
5274 // Deduce type of TemplParam in Func(Init)
5276 Deduced.resize(1);
5277
5278 // If deduction failed, don't diagnose if the initializer is dependent; it
5279 // might acquire a matching type in the instantiation.
5280 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5281 if (Init->isTypeDependent()) {
5282 Result =
5283 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5284 assert(!Result.isNull() && "substituting DependentTy can't fail");
5286 }
5287 return TDK;
5288 };
5289
5290 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5291
5293 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5294 if (AT->isDecltypeAuto()) {
5295 if (InitList) {
5296 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5298 }
5299
5301 assert(!DeducedType.isNull());
5302 } else {
5303 LocalInstantiationScope InstScope(*this);
5304
5305 // Build template<class TemplParam> void Func(FuncParam);
5306 SourceLocation Loc = Init->getExprLoc();
5308 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5309 nullptr, false, false, false);
5310 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5311 NamedDecl *TemplParamPtr = TemplParam;
5313 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5314
5315 if (InitList) {
5316 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5317 // deduce against that. Such deduction only succeeds if removing
5318 // cv-qualifiers and references results in std::initializer_list<T>.
5319 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5321
5322 SourceRange DeducedFromInitRange;
5323 for (Expr *Init : InitList->inits()) {
5324 // Resolving a core issue: a braced-init-list containing any designators
5325 // is a non-deduced context.
5326 if (isa<DesignatedInitExpr>(Init))
5329 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5330 Init->Classify(getASTContext()), Init, Info, Deduced,
5331 OriginalCallArgs,
5332 /*Decomposed=*/true,
5333 /*ArgIdx=*/0, /*TDF=*/0);
5336 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5337 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5338 << Init->getSourceRange();
5339 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5340 }
5341 return DeductionFailed(TDK);
5342 }
5343
5344 if (DeducedFromInitRange.isInvalid() &&
5345 Deduced[0].getKind() != TemplateArgument::Null)
5346 DeducedFromInitRange = Init->getSourceRange();
5347 }
5348 } else {
5349 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5350 Diag(Loc, diag::err_auto_bitfield);
5352 }
5353 QualType FuncParam =
5354 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5355 assert(!FuncParam.isNull() &&
5356 "substituting template parameter for 'auto' failed");
5358 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5359 Init->Classify(getASTContext()), Init, Info, Deduced,
5360 OriginalCallArgs,
5361 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5363 return DeductionFailed(TDK);
5364 }
5365
5366 // Could be null if somehow 'auto' appears in a non-deduced context.
5367 if (Deduced[0].getKind() != TemplateArgument::Type)
5368 return DeductionFailed(TemplateDeductionResult::Incomplete);
5369 DeducedType = Deduced[0].getAsType();
5370
5371 if (InitList) {
5373 if (DeducedType.isNull())
5375 }
5376 }
5377
5378 if (!Result.isNull()) {
5380 Info.FirstArg = Result;
5381 Info.SecondArg = DeducedType;
5382 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5383 }
5385 }
5386
5387 if (AT->isConstrained() && !IgnoreConstraints &&
5389 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5391
5392 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5393 if (Result.isNull())
5395
5396 // Check that the deduced argument type is compatible with the original
5397 // argument type per C++ [temp.deduct.call]p4.
5398 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5399 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5400 assert((bool)InitList == OriginalArg.DecomposedParam &&
5401 "decomposed non-init-list in auto deduction?");
5402 if (auto TDK =
5403 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5405 Result = QualType();
5406 return DeductionFailed(TDK);
5407 }
5408 }
5409
5411}
5412
5414 QualType TypeToReplaceAuto) {
5415 assert(TypeToReplaceAuto != Context.DependentTy);
5416 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5417 .TransformType(TypeWithAuto);
5418}
5419
5421 QualType TypeToReplaceAuto) {
5422 assert(TypeToReplaceAuto != Context.DependentTy);
5423 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5424 .TransformType(TypeWithAuto);
5425}
5426
5428 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5429 .TransformType(TypeWithAuto);
5430}
5431
5434 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5435 .TransformType(TypeWithAuto);
5436}
5437
5439 QualType TypeToReplaceAuto) {
5440 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5441 /*UseTypeSugar*/ false)
5442 .TransformType(TypeWithAuto);
5443}
5444
5446 QualType TypeToReplaceAuto) {
5447 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5448 /*UseTypeSugar*/ false)
5449 .TransformType(TypeWithAuto);
5450}
5451
5453 const Expr *Init) {
5454 if (isa<InitListExpr>(Init))
5455 Diag(VDecl->getLocation(),
5456 VDecl->isInitCapture()
5457 ? diag::err_init_capture_deduction_failure_from_init_list
5458 : diag::err_auto_var_deduction_failure_from_init_list)
5459 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5460 else
5461 Diag(VDecl->getLocation(),
5462 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5463 : diag::err_auto_var_deduction_failure)
5464 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5465 << Init->getSourceRange();
5466}
5467
5469 bool Diagnose) {
5470 assert(FD->getReturnType()->isUndeducedType());
5471
5472 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5473 // within the return type from the call operator's type.
5475 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5476 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5477
5478 // For a generic lambda, instantiate the call operator if needed.
5479 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5481 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5482 if (!CallOp || CallOp->isInvalidDecl())
5483 return true;
5484
5485 // We might need to deduce the return type by instantiating the definition
5486 // of the operator() function.
5487 if (CallOp->getReturnType()->isUndeducedType()) {
5490 });
5491 }
5492 }
5493
5494 if (CallOp->isInvalidDecl())
5495 return true;
5496 assert(!CallOp->getReturnType()->isUndeducedType() &&
5497 "failed to deduce lambda return type");
5498
5499 // Build the new return type from scratch.
5500 CallingConv RetTyCC = FD->getReturnType()
5501 ->getPointeeType()
5502 ->castAs<FunctionType>()
5503 ->getCallConv();
5505 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5506 if (FD->getReturnType()->getAs<PointerType>())
5507 RetType = Context.getPointerType(RetType);
5508 else {
5509 assert(FD->getReturnType()->getAs<BlockPointerType>());
5510 RetType = Context.getBlockPointerType(RetType);
5511 }
5513 return false;
5514 }
5515
5519 });
5520 }
5521
5522 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5523 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5524 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5525 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5526 }
5527
5528 return StillUndeduced;
5529}
5530
5533 assert(FD->isImmediateEscalating());
5534
5536 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5537 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5538
5539 // For a generic lambda, instantiate the call operator if needed.
5540 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5542 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5543 if (!CallOp || CallOp->isInvalidDecl())
5544 return true;
5546 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5547 }
5548 return CallOp->isInvalidDecl();
5549 }
5550
5553 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5554 }
5555 return false;
5556}
5557
5559 const CXXMethodDecl *Method,
5560 QualType RawType,
5561 bool IsOtherRvr) {
5562 // C++20 [temp.func.order]p3.1, p3.2:
5563 // - The type X(M) is "rvalue reference to cv A" if the optional
5564 // ref-qualifier of M is && or if M has no ref-qualifier and the
5565 // positionally-corresponding parameter of the other transformed template
5566 // has rvalue reference type; if this determination depends recursively
5567 // upon whether X(M) is an rvalue reference type, it is not considered to
5568 // have rvalue reference type.
5569 //
5570 // - Otherwise, X(M) is "lvalue reference to cv A".
5571 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5572 "expected a member function with no explicit object parameter");
5573
5574 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5575 if (Method->getRefQualifier() == RQ_RValue ||
5576 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5577 return Context.getRValueReferenceType(RawType);
5578 return Context.getLValueReferenceType(RawType);
5579}
5580
5583 QualType A, ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5584 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5585 /*Final=*/true);
5587 S,
5588 ArgIdx ? ::getPackIndexForParam(S, FTD, MLTAL, *ArgIdx) : std::nullopt);
5589 bool IsIncompleteSubstitution = false;
5590 // FIXME: A substitution can be incomplete on a non-structural part of the
5591 // type. Use the canonical type for now, until the TemplateInstantiator can
5592 // deal with that.
5593
5594 // Workaround: Implicit deduction guides use InjectedClassNameTypes, whereas
5595 // the explicit guides don't. The substitution doesn't transform these types,
5596 // so let it transform their specializations instead.
5597 bool IsDeductionGuide = isa<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
5598 if (IsDeductionGuide) {
5599 if (auto *Injected = P->getAsCanonical<InjectedClassNameType>())
5600 P = Injected->getOriginalDecl()->getCanonicalTemplateSpecializationType(
5601 S.Context);
5602 }
5603 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5604 FTD->getDeclName(), &IsIncompleteSubstitution);
5605 if (InstP.isNull() && !IsIncompleteSubstitution)
5607 if (!CheckConsistency)
5609 if (IsIncompleteSubstitution)
5611
5612 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5613 // This handles just the cases that can appear when partial ordering.
5614 if (auto *PA = dyn_cast<PackExpansionType>(A);
5615 PA && !isa<PackExpansionType>(InstP))
5616 A = PA->getPattern();
5619 if (IsDeductionGuide) {
5620 if (auto *Injected = T1->getAsCanonical<InjectedClassNameType>())
5621 T1 = Injected->getOriginalDecl()->getCanonicalTemplateSpecializationType(
5622 S.Context);
5623 if (auto *Injected = T2->getAsCanonical<InjectedClassNameType>())
5624 T2 = Injected->getOriginalDecl()->getCanonicalTemplateSpecializationType(
5625 S.Context);
5626 }
5627 if (!S.Context.hasSameType(T1, T2))
5630}
5631
5632template <class T>
5634 Sema &S, FunctionTemplateDecl *FTD,
5639 Sema::SFINAETrap Trap(S);
5640
5641 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5642
5643 // C++26 [temp.deduct.type]p2:
5644 // [...] or if any template argument remains neither deduced nor
5645 // explicitly specified, template argument deduction fails.
5646 bool IsIncomplete = false;
5647 Sema::CheckTemplateArgumentInfo CTAI(/*PartialOrdering=*/true);
5649 S, FTD, FTD->getTemplateParameters(), /*IsDeduced=*/true, Deduced,
5650 Info, CTAI,
5651 /*CurrentInstantiationScope=*/nullptr,
5652 /*NumAlreadyConverted=*/0, &IsIncomplete);
5654 return Result;
5655
5656 // Form the template argument list from the deduced template arguments.
5657 TemplateArgumentList *SugaredDeducedArgumentList =
5659 TemplateArgumentList *CanonicalDeducedArgumentList =
5661
5662 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5663
5664 // Substitute the deduced template arguments into the argument
5665 // and verify that the instantiated argument is both valid
5666 // and equivalent to the parameter.
5667 LocalInstantiationScope InstScope(S);
5668
5669 if (auto TDR = CheckDeductionConsistency(S, FTD, CTAI.SugaredConverted);
5671 return TDR;
5672
5675}
5676
5677/// Determine whether the function template \p FT1 is at least as
5678/// specialized as \p FT2.
5682 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5683 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5684 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5685 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5686 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5687 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5688
5689 // C++26 [temp.deduct.partial]p3:
5690 // The types used to determine the ordering depend on the context in which
5691 // the partial ordering is done:
5692 // - In the context of a function call, the types used are those function
5693 // parameter types for which the function call has arguments.
5694 // - In the context of a call to a conversion operator, the return types
5695 // of the conversion function templates are used.
5696 // - In other contexts (14.6.6.2) the function template's function type
5697 // is used.
5698
5699 if (TPOC == TPOC_Other) {
5700 // We wouldn't be partial ordering these candidates if these didn't match.
5701 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5702 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5703 Proto1->isVariadic() == Proto2->isVariadic() &&
5704 "shouldn't partial order functions with different qualifiers in a "
5705 "context where the function type is used");
5706
5707 assert(Args1.empty() && Args2.empty() &&
5708 "Only call context should have arguments");
5709 Args1 = Proto1->getParamTypes();
5710 Args2 = Proto2->getParamTypes();
5711 }
5712
5713 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5714 SmallVector<DeducedTemplateArgument, 4> Deduced(TemplateParams->size());
5716
5717 bool HasDeducedAnyParamFromReturnType = false;
5718 if (TPOC != TPOC_Call) {
5720 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5721 Info, Deduced, TDF_None, PartialOrderingKind::Call,
5722 /*DeducedFromArrayBound=*/false,
5723 &HasDeducedAnyParamFromReturnType) !=
5725 return false;
5726 }
5727
5728 llvm::SmallBitVector HasDeducedParam;
5729 if (TPOC != TPOC_Conversion) {
5730 HasDeducedParam.resize(Args2.size());
5731 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5732 TDF_None, PartialOrderingKind::Call,
5733 /*HasDeducedAnyParam=*/nullptr,
5734 &HasDeducedParam) !=
5736 return false;
5737 }
5738
5739 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5741 S, Info.getLocation(), FT2, DeducedArgs,
5743 if (Inst.isInvalid())
5744 return false;
5745
5746 bool AtLeastAsSpecialized;
5748 AtLeastAsSpecialized =
5749 ::FinishTemplateArgumentDeduction(
5750 S, FT2, Deduced, Info,
5751 [&](Sema &S, FunctionTemplateDecl *FTD,
5752 ArrayRef<TemplateArgument> DeducedArgs) {
5753 // As a provisional fix for a core issue that does not
5754 // exist yet, which may be related to CWG2160, only check the
5755 // consistency of parameters and return types which participated
5756 // in deduction. We will still try to substitute them though.
5757 if (TPOC != TPOC_Call) {
5758 if (auto TDR = ::CheckDeductionConsistency(
5759 S, FTD, /*ArgIdx=*/std::nullopt,
5760 Proto2->getReturnType(), Proto1->getReturnType(),
5761 DeducedArgs,
5762 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5763 TDR != TemplateDeductionResult::Success)
5764 return TDR;
5765 }
5766
5767 if (TPOC == TPOC_Conversion)
5768 return TemplateDeductionResult::Success;
5769
5770 return ::DeduceForEachType(
5771 S, TemplateParams, Args2, Args1, Info, Deduced,
5772 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5773 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5774 UnsignedOrNone ArgIdx, QualType P, QualType A,
5775 TemplateDeductionInfo &Info,
5776 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5777 PartialOrderingKind) {
5778 if (ArgIdx && *ArgIdx >= static_cast<unsigned>(Args1Offset))
5779 ArgIdx = *ArgIdx - Args1Offset;
5780 else
5781 ArgIdx = std::nullopt;
5782 return ::CheckDeductionConsistency(
5783 S, FTD, ArgIdx, P, A, DeducedArgs,
5784 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5785 });
5787 });
5788 if (!AtLeastAsSpecialized)
5789 return false;
5790
5791 // C++0x [temp.deduct.partial]p11:
5792 // In most cases, all template parameters must have values in order for
5793 // deduction to succeed, but for partial ordering purposes a template
5794 // parameter may remain without a value provided it is not used in the
5795 // types being used for partial ordering. [ Note: a template parameter used
5796 // in a non-deduced context is considered used. -end note]
5797 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5798 for (; ArgIdx != NumArgs; ++ArgIdx)
5799 if (Deduced[ArgIdx].isNull())
5800 break;
5801
5802 if (ArgIdx == NumArgs) {
5803 // All template arguments were deduced. FT1 is at least as specialized
5804 // as FT2.
5805 return true;
5806 }
5807
5808 // Figure out which template parameters were used.
5809 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5810 switch (TPOC) {
5811 case TPOC_Call:
5812 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5813 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5814 TemplateParams->getDepth(), UsedParameters);
5815 break;
5816
5817 case TPOC_Conversion:
5818 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5819 /*OnlyDeduced=*/false,
5820 TemplateParams->getDepth(), UsedParameters);
5821 break;
5822
5823 case TPOC_Other:
5824 // We do not deduce template arguments from the exception specification
5825 // when determining the primary template of a function template
5826 // specialization or when taking the address of a function template.
5827 // Therefore, we do not mark template parameters in the exception
5828 // specification as used during partial ordering to prevent the following
5829 // from being ambiguous:
5830 //
5831 // template<typename T, typename U>
5832 // void f(U) noexcept(noexcept(T())); // #1
5833 //
5834 // template<typename T>
5835 // void f(T*) noexcept; // #2
5836 //
5837 // template<>
5838 // void f<int>(int*) noexcept; // explicit specialization of #2
5839 //
5840 // Although there is no corresponding wording in the standard, this seems
5841 // to be the intended behavior given the definition of
5842 // 'deduction substitution loci' in [temp.deduct].
5844 S.Context,
5846 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5847 break;
5848 }
5849
5850 for (; ArgIdx != NumArgs; ++ArgIdx)
5851 // If this argument had no value deduced but was used in one of the types
5852 // used for partial ordering, then deduction fails.
5853 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5854 return false;
5855
5856 return true;
5857}
5858
5860
5861// This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5862// there is no wording or even resolution for this issue.
5865 const TemplateSpecializationType *TST1,
5866 const TemplateSpecializationType *TST2) {
5868 As2 = TST2->template_arguments();
5869 const TemplateArgument &TA1 = As1.back(), &TA2 = As2.back();
5870 bool IsPack = TA1.getKind() == TemplateArgument::Pack;
5871 assert(IsPack == (TA2.getKind() == TemplateArgument::Pack));
5872 if (!IsPack)
5873 return MoreSpecializedTrailingPackTieBreakerResult::Equal;
5874 assert(As1.size() == As2.size());
5875
5876 unsigned PackSize1 = TA1.pack_size(), PackSize2 = TA2.pack_size();
5877 bool IsPackExpansion1 =
5878 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5879 bool IsPackExpansion2 =
5880 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5881 if (PackSize1 == PackSize2 && IsPackExpansion1 == IsPackExpansion2)
5882 return MoreSpecializedTrailingPackTieBreakerResult::Equal;
5883 if (PackSize1 > PackSize2 && IsPackExpansion1)
5884 return MoreSpecializedTrailingPackTieBreakerResult::More;
5885 if (PackSize1 < PackSize2 && IsPackExpansion2)
5886 return MoreSpecializedTrailingPackTieBreakerResult::Less;
5887 return MoreSpecializedTrailingPackTieBreakerResult::Equal;
5888}
5889
5892 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5893 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed,
5894 bool PartialOverloading) {
5897 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5898 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5899 bool ShouldConvert1 = false;
5900 bool ShouldConvert2 = false;
5901 bool Args1Offset = false;
5902 bool Args2Offset = false;
5903 QualType Obj1Ty;
5904 QualType Obj2Ty;
5905 if (TPOC == TPOC_Call) {
5906 const FunctionProtoType *Proto1 =
5907 FD1->getType()->castAs<FunctionProtoType>();
5908 const FunctionProtoType *Proto2 =
5909 FD2->getType()->castAs<FunctionProtoType>();
5910
5911 // - In the context of a function call, the function parameter types are
5912 // used.
5913 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5914 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5915 // C++20 [temp.func.order]p3
5916 // [...] Each function template M that is a member function is
5917 // considered to have a new first parameter of type
5918 // X(M), described below, inserted in its function parameter list.
5919 //
5920 // Note that we interpret "that is a member function" as
5921 // "that is a member function with no expicit object argument".
5922 // Otherwise the ordering rules for methods with expicit objet arguments
5923 // against anything else make no sense.
5924
5925 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
5926 NonStaticMethod2 = Method2 && !Method2->isStatic();
5927
5928 auto Params1Begin = Proto1->param_type_begin(),
5929 Params2Begin = Proto2->param_type_begin();
5930
5931 size_t NumComparedArguments = NumCallArguments1;
5932
5933 if (auto OO = FD1->getOverloadedOperator();
5934 (NonStaticMethod1 && NonStaticMethod2) ||
5935 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
5936 ShouldConvert1 =
5937 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
5938 ShouldConvert2 =
5939 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
5940 NumComparedArguments += 1;
5941
5942 if (ShouldConvert1) {
5943 bool IsRValRef2 =
5944 ShouldConvert2
5945 ? Method2->getRefQualifier() == RQ_RValue
5946 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5947 // Compare 'this' from Method1 against first parameter from Method2.
5948 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
5949 RawObj1Ty, IsRValRef2);
5950 Args1.push_back(Obj1Ty);
5951 Args1Offset = true;
5952 }
5953 if (ShouldConvert2) {
5954 bool IsRValRef1 =
5955 ShouldConvert1
5956 ? Method1->getRefQualifier() == RQ_RValue
5957 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5958 // Compare 'this' from Method2 against first parameter from Method1.
5959 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
5960 RawObj2Ty, IsRValRef1);
5961 Args2.push_back(Obj2Ty);
5962 Args2Offset = true;
5963 }
5964 } else {
5965 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
5966 Params1Begin += 1;
5967 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
5968 Params2Begin += 1;
5969 }
5970 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
5971 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
5972
5973 // C++ [temp.func.order]p5:
5974 // The presence of unused ellipsis and default arguments has no effect on
5975 // the partial ordering of function templates.
5976 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5977 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5978
5979 if (Reversed)
5980 std::reverse(Args2.begin(), Args2.end());
5981 } else {
5982 assert(!Reversed && "Only call context could have reversed arguments");
5983 }
5984 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
5985 Args2, Args2Offset);
5986 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
5987 Args1, Args1Offset);
5988 // C++ [temp.deduct.partial]p10:
5989 // F is more specialized than G if F is at least as specialized as G and G
5990 // is not at least as specialized as F.
5991 if (Better1 != Better2) // We have a clear winner
5992 return Better1 ? FT1 : FT2;
5993
5994 if (!Better1 && !Better2) // Neither is better than the other
5995 return nullptr;
5996
5997 // C++ [temp.deduct.partial]p11:
5998 // ... and if G has a trailing function parameter pack for which F does not
5999 // have a corresponding parameter, and if F does not have a trailing
6000 // function parameter pack, then F is more specialized than G.
6001
6002 SmallVector<QualType> Param1;
6003 Param1.reserve(FD1->param_size() + ShouldConvert1);
6004 if (ShouldConvert1)
6005 Param1.push_back(Obj1Ty);
6006 for (const auto &P : FD1->parameters())
6007 Param1.push_back(P->getType());
6008
6009 SmallVector<QualType> Param2;
6010 Param2.reserve(FD2->param_size() + ShouldConvert2);
6011 if (ShouldConvert2)
6012 Param2.push_back(Obj2Ty);
6013 for (const auto &P : FD2->parameters())
6014 Param2.push_back(P->getType());
6015
6016 unsigned NumParams1 = Param1.size();
6017 unsigned NumParams2 = Param2.size();
6018
6019 bool Variadic1 =
6020 FD1->param_size() && FD1->parameters().back()->isParameterPack();
6021 bool Variadic2 =
6022 FD2->param_size() && FD2->parameters().back()->isParameterPack();
6023 if (Variadic1 != Variadic2) {
6024 if (Variadic1 && NumParams1 > NumParams2)
6025 return FT2;
6026 if (Variadic2 && NumParams2 > NumParams1)
6027 return FT1;
6028 }
6029
6030 // Skip this tie breaker if we are performing overload resolution with partial
6031 // arguments, as this breaks some assumptions about how closely related the
6032 // candidates are.
6033 for (int i = 0, e = std::min(NumParams1, NumParams2);
6034 !PartialOverloading && i < e; ++i) {
6035 QualType T1 = Param1[i].getCanonicalType();
6036 QualType T2 = Param2[i].getCanonicalType();
6037 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
6038 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
6039 if (!TST1 || !TST2)
6040 continue;
6041 switch (getMoreSpecializedTrailingPackTieBreaker(TST1, TST2)) {
6042 case MoreSpecializedTrailingPackTieBreakerResult::Less:
6043 return FT1;
6044 case MoreSpecializedTrailingPackTieBreakerResult::More:
6045 return FT2;
6046 case MoreSpecializedTrailingPackTieBreakerResult::Equal:
6047 continue;
6048 }
6049 llvm_unreachable(
6050 "unknown MoreSpecializedTrailingPackTieBreakerResult value");
6051 }
6052
6053 if (!Context.getLangOpts().CPlusPlus20)
6054 return nullptr;
6055
6056 // Match GCC on not implementing [temp.func.order]p6.2.1.
6057
6058 // C++20 [temp.func.order]p6:
6059 // If deduction against the other template succeeds for both transformed
6060 // templates, constraints can be considered as follows:
6061
6062 // C++20 [temp.func.order]p6.1:
6063 // If their template-parameter-lists (possibly including template-parameters
6064 // invented for an abbreviated function template ([dcl.fct])) or function
6065 // parameter lists differ in length, neither template is more specialized
6066 // than the other.
6069 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
6070 return nullptr;
6071
6072 // C++20 [temp.func.order]p6.2.2:
6073 // Otherwise, if the corresponding template-parameters of the
6074 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6075 // function parameters that positionally correspond between the two
6076 // templates are not of the same type, neither template is more specialized
6077 // than the other.
6078 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
6080 return nullptr;
6081
6082 // [dcl.fct]p5:
6083 // Any top-level cv-qualifiers modifying a parameter type are deleted when
6084 // forming the function type.
6085 for (unsigned i = 0; i < NumParams1; ++i)
6086 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
6087 return nullptr;
6088
6089 // C++20 [temp.func.order]p6.3:
6090 // Otherwise, if the context in which the partial ordering is done is
6091 // that of a call to a conversion function and the return types of the
6092 // templates are not the same, then neither template is more specialized
6093 // than the other.
6094 if (TPOC == TPOC_Conversion &&
6096 return nullptr;
6097
6099 FT1->getAssociatedConstraints(AC1);
6100 FT2->getAssociatedConstraints(AC2);
6101 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6102 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
6103 return nullptr;
6104 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
6105 return nullptr;
6106 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6107 return nullptr;
6108 return AtLeastAsConstrained1 ? FT1 : FT2;
6109}
6110
6113 TemplateSpecCandidateSet &FailedCandidates,
6114 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
6115 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
6116 bool Complain, QualType TargetType) {
6117 if (SpecBegin == SpecEnd) {
6118 if (Complain) {
6119 Diag(Loc, NoneDiag);
6120 FailedCandidates.NoteCandidates(*this, Loc);
6121 }
6122 return SpecEnd;
6123 }
6124
6125 if (SpecBegin + 1 == SpecEnd)
6126 return SpecBegin;
6127
6128 // Find the function template that is better than all of the templates it
6129 // has been compared to.
6130 UnresolvedSetIterator Best = SpecBegin;
6131 FunctionTemplateDecl *BestTemplate
6132 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6133 assert(BestTemplate && "Not a function template specialization?");
6134 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6135 FunctionTemplateDecl *Challenger
6136 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6137 assert(Challenger && "Not a function template specialization?");
6138 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6139 Loc, TPOC_Other, 0),
6140 Challenger)) {
6141 Best = I;
6142 BestTemplate = Challenger;
6143 }
6144 }
6145
6146 // Make sure that the "best" function template is more specialized than all
6147 // of the others.
6148 bool Ambiguous = false;
6149 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6150 FunctionTemplateDecl *Challenger
6151 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6152 if (I != Best &&
6153 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6154 Loc, TPOC_Other, 0),
6155 BestTemplate)) {
6156 Ambiguous = true;
6157 break;
6158 }
6159 }
6160
6161 if (!Ambiguous) {
6162 // We found an answer. Return it.
6163 return Best;
6164 }
6165
6166 // Diagnose the ambiguity.
6167 if (Complain) {
6168 Diag(Loc, AmbigDiag);
6169
6170 // FIXME: Can we order the candidates in some sane way?
6171 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6172 PartialDiagnostic PD = CandidateDiag;
6173 const auto *FD = cast<FunctionDecl>(*I);
6175 FD->getPrimaryTemplate()->getTemplateParameters(),
6176 *FD->getTemplateSpecializationArgs());
6177 if (!TargetType.isNull())
6178 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6179 Diag((*I)->getLocation(), PD);
6180 }
6181 }
6182
6183 return SpecEnd;
6184}
6185
6187 FunctionDecl *FD2) {
6188 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6189 "not for function templates");
6190 assert(!FD1->isFunctionTemplateSpecialization() ||
6191 (isa<CXXConversionDecl, CXXConstructorDecl>(FD1)));
6192 assert(!FD2->isFunctionTemplateSpecialization() ||
6193 (isa<CXXConversionDecl, CXXConstructorDecl>(FD2)));
6194
6195 FunctionDecl *F1 = FD1;
6197 F1 = P;
6198
6199 FunctionDecl *F2 = FD2;
6201 F2 = P;
6202
6204 F1->getAssociatedConstraints(AC1);
6205 F2->getAssociatedConstraints(AC2);
6206 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6207 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6208 return nullptr;
6209 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6210 return nullptr;
6211 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6212 return nullptr;
6213 return AtLeastAsConstrained1 ? FD1 : FD2;
6214}
6215
6216/// Determine whether one template specialization, P1, is at least as
6217/// specialized than another, P2.
6218///
6219/// \tparam TemplateLikeDecl The kind of P2, which must be a
6220/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6221/// \param T1 The injected-class-name of P1 (faked for a variable template).
6222/// \param T2 The injected-class-name of P2 (faked for a variable template).
6223/// \param Template The primary template of P2, in case it is a partial
6224/// specialization, the same as P2 otherwise.
6225template <typename TemplateLikeDecl>
6227 TemplateLikeDecl *P2,
6229 TemplateDeductionInfo &Info) {
6230 // C++ [temp.class.order]p1:
6231 // For two class template partial specializations, the first is at least as
6232 // specialized as the second if, given the following rewrite to two
6233 // function templates, the first function template is at least as
6234 // specialized as the second according to the ordering rules for function
6235 // templates (14.6.6.2):
6236 // - the first function template has the same template parameters as the
6237 // first partial specialization and has a single function parameter
6238 // whose type is a class template specialization with the template
6239 // arguments of the first partial specialization, and
6240 // - the second function template has the same template parameters as the
6241 // second partial specialization and has a single function parameter
6242 // whose type is a class template specialization with the template
6243 // arguments of the second partial specialization.
6244 //
6245 // Rather than synthesize function templates, we merely perform the
6246 // equivalent partial ordering by performing deduction directly on
6247 // the template arguments of the class template partial
6248 // specializations. This computation is slightly simpler than the
6249 // general problem of function template partial ordering, because
6250 // class template partial specializations are more constrained. We
6251 // know that every template parameter is deducible from the class
6252 // template partial specialization's template arguments, for
6253 // example.
6255
6256 // Determine whether P1 is at least as specialized as P2.
6257 Deduced.resize(P2->getTemplateParameters()->size());
6259 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6260 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6261 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6262 return false;
6263
6264 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
6265 Deduced.end());
6266 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
6267 Info);
6268 if (Inst.isInvalid())
6269 return false;
6270
6272 Ps = cast<TemplateSpecializationType>(T2)->template_arguments(),
6273 As = cast<TemplateSpecializationType>(T1)->template_arguments();
6274
6275 Sema::SFINAETrap Trap(S);
6276
6279 Result = ::FinishTemplateArgumentDeduction(
6280 S, P2, P2->getTemplateParameters(), Template,
6281 /*IsPartialOrdering=*/true, Ps, As, Deduced, Info,
6282 /*CopyDeducedArgs=*/false);
6283 });
6284
6286 return false;
6287
6288 if (Trap.hasErrorOccurred())
6289 return false;
6290
6291 return true;
6292}
6293
6294namespace {
6295// A dummy class to return nullptr instead of P2 when performing "more
6296// specialized than primary" check.
6297struct GetP2 {
6298 template <typename T1, typename T2,
6299 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6300 T2 *operator()(T1 *, T2 *P2) {
6301 return P2;
6302 }
6303 template <typename T1, typename T2,
6304 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6305 T1 *operator()(T1 *, T2 *) {
6306 return nullptr;
6307 }
6308};
6309
6310// The assumption is that two template argument lists have the same size.
6311struct TemplateArgumentListAreEqual {
6312 ASTContext &Ctx;
6313 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6314
6315 template <typename T1, typename T2,
6316 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6317 bool operator()(T1 *PS1, T2 *PS2) {
6318 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6319 Args2 = PS2->getTemplateArgs().asArray();
6320
6321 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6322 // We use profile, instead of structural comparison of the arguments,
6323 // because canonicalization can't do the right thing for dependent
6324 // expressions.
6325 llvm::FoldingSetNodeID IDA, IDB;
6326 Args1[I].Profile(IDA, Ctx);
6327 Args2[I].Profile(IDB, Ctx);
6328 if (IDA != IDB)
6329 return false;
6330 }
6331 return true;
6332 }
6333
6334 template <typename T1, typename T2,
6335 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6336 bool operator()(T1 *Spec, T2 *Primary) {
6337 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6338 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6339
6340 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6341 // We use profile, instead of structural comparison of the arguments,
6342 // because canonicalization can't do the right thing for dependent
6343 // expressions.
6344 llvm::FoldingSetNodeID IDA, IDB;
6345 Args1[I].Profile(IDA, Ctx);
6346 // Unlike the specialization arguments, the injected arguments are not
6347 // always canonical.
6348 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6349 if (IDA != IDB)
6350 return false;
6351 }
6352 return true;
6353 }
6354};
6355} // namespace
6356
6357/// Returns the more specialized template specialization between T1/P1 and
6358/// T2/P2.
6359/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6360/// specialization and T2/P2 is the primary template.
6361/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6362///
6363/// \param T1 the type of the first template partial specialization
6364///
6365/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6366/// template partial specialization; otherwise, the type of the
6367/// primary template.
6368///
6369/// \param P1 the first template partial specialization
6370///
6371/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6372/// partial specialization; otherwise, the primary template.
6373///
6374/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6375/// more specialized, returns nullptr if P1 is not more specialized.
6376/// - otherwise, returns the more specialized template partial
6377/// specialization. If neither partial specialization is more
6378/// specialized, returns NULL.
6379template <typename TemplateLikeDecl, typename PrimaryDel>
6380static TemplateLikeDecl *
6381getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6382 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6383 constexpr bool IsMoreSpecialThanPrimaryCheck =
6384 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6385
6386 TemplateDecl *P2T;
6387 if constexpr (IsMoreSpecialThanPrimaryCheck)
6388 P2T = P2;
6389 else
6390 P2T = P2->getSpecializedTemplate();
6391
6392 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, P2T, Info);
6393 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6394 return nullptr;
6395
6396 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1,
6397 P1->getSpecializedTemplate(), Info);
6398 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6399 return P1;
6400
6401 // C++ [temp.deduct.partial]p10:
6402 // F is more specialized than G if F is at least as specialized as G and G
6403 // is not at least as specialized as F.
6404 if (Better1 != Better2) // We have a clear winner
6405 return Better1 ? P1 : GetP2()(P1, P2);
6406
6407 if (!Better1 && !Better2)
6408 return nullptr;
6409
6411 cast<TemplateSpecializationType>(T1),
6412 cast<TemplateSpecializationType>(T2))) {
6413 case MoreSpecializedTrailingPackTieBreakerResult::Less:
6414 return P1;
6415 case MoreSpecializedTrailingPackTieBreakerResult::More:
6416 return GetP2()(P1, P2);
6417 case MoreSpecializedTrailingPackTieBreakerResult::Equal:
6418 break;
6419 }
6420
6421 if (!S.Context.getLangOpts().CPlusPlus20)
6422 return nullptr;
6423
6424 // Match GCC on not implementing [temp.func.order]p6.2.1.
6425
6426 // C++20 [temp.func.order]p6:
6427 // If deduction against the other template succeeds for both transformed
6428 // templates, constraints can be considered as follows:
6429
6430 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6431 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6432 if (TPL1->size() != TPL2->size())
6433 return nullptr;
6434
6435 // C++20 [temp.func.order]p6.2.2:
6436 // Otherwise, if the corresponding template-parameters of the
6437 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6438 // function parameters that positionally correspond between the two
6439 // templates are not of the same type, neither template is more specialized
6440 // than the other.
6441 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6443 return nullptr;
6444
6445 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6446 return nullptr;
6447
6449 P1->getAssociatedConstraints(AC1);
6450 P2->getAssociatedConstraints(AC2);
6451 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6452 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6453 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6454 return nullptr;
6455 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6456 return nullptr;
6457 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6458 return nullptr;
6459 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6460}
6461
6469
6471 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6472}
6473
6476 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6479
6481 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6482 if (MaybeSpec)
6483 Info.clearSFINAEDiagnostic();
6484 return MaybeSpec;
6485}
6486
6491 // Pretend the variable template specializations are class template
6492 // specializations and form a fake injected class name type for comparison.
6493 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6494 "the partial specializations being compared should specialize"
6495 " the same template.");
6498 Name, PS1->getTemplateArgs().asArray());
6500 Name, PS2->getTemplateArgs().asArray());
6501
6503 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6504}
6505
6508 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6509 TemplateName Name(Primary->getCanonicalDecl());
6510
6511 SmallVector<TemplateArgument, 8> PrimaryCanonArgs(
6513 Context.canonicalizeTemplateArguments(PrimaryCanonArgs);
6514
6515 QualType PrimaryT =
6516 Context.getCanonicalTemplateSpecializationType(Name, PrimaryCanonArgs);
6518 Name, Spec->getTemplateArgs().asArray());
6519
6521 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6522 if (MaybeSpec)
6523 Info.clearSFINAEDiagnostic();
6524 return MaybeSpec;
6525}
6526
6529 const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
6530 bool PartialOrdering, bool *StrictPackMatch) {
6531 // C++1z [temp.arg.template]p4: (DR 150)
6532 // A template template-parameter P is at least as specialized as a
6533 // template template-argument A if, given the following rewrite to two
6534 // function templates...
6535
6536 // Rather than synthesize function templates, we merely perform the
6537 // equivalent partial ordering by performing deduction directly on
6538 // the template parameter lists of the template template parameters.
6539 //
6541
6544 SourceRange(P->getTemplateLoc(), P->getRAngleLoc()));
6545 if (Inst.isInvalid())
6546 return false;
6547
6548 // Given an invented class template X with the template parameter list of
6549 // A (including default arguments):
6550 // - Each function template has a single function parameter whose type is
6551 // a specialization of X with template arguments corresponding to the
6552 // template parameters from the respective function template
6554
6555 // Check P's arguments against A's parameter list. This will fill in default
6556 // template arguments as needed. AArgs are already correct by construction.
6557 // We can't just use CheckTemplateIdType because that will expand alias
6558 // templates.
6559 SmallVector<TemplateArgument, 4> PArgs(P->getInjectedTemplateArgs(Context));
6560 {
6561 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6562 P->getRAngleLoc());
6563 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6564 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6565 // expansions, to form an "as written" argument list.
6566 TemplateArgument Arg = PArgs[I];
6567 if (Arg.getKind() == TemplateArgument::Pack) {
6568 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6569 Arg = *Arg.pack_begin();
6570 }
6572 Arg, QualType(), P->getParam(I)->getLocation()));
6573 }
6574 PArgs.clear();
6575
6576 // C++1z [temp.arg.template]p3:
6577 // If the rewrite produces an invalid type, then P is not at least as
6578 // specialized as A.
6580 /*PartialOrdering=*/false, /*MatchingTTP=*/true);
6581 CTAI.SugaredConverted = std::move(PArgs);
6582 if (CheckTemplateArgumentList(AArg, ArgLoc, PArgList, DefaultArgs,
6583 /*PartialTemplateArgs=*/false, CTAI,
6584 /*UpdateArgsWithConversions=*/true,
6585 /*ConstraintsNotSatisfied=*/nullptr))
6586 return false;
6587 PArgs = std::move(CTAI.SugaredConverted);
6588 if (StrictPackMatch)
6589 *StrictPackMatch |= CTAI.StrictPackMatch;
6590 }
6591
6592 // Determine whether P1 is at least as specialized as P2.
6593 TemplateDeductionInfo Info(ArgLoc, A->getDepth());
6595 Deduced.resize(A->size());
6596
6597 // ... the function template corresponding to P is at least as specialized
6598 // as the function template corresponding to A according to the partial
6599 // ordering rules for function templates.
6600
6601 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6602 // applying the partial ordering rules for function templates on
6603 // the rewritten template template parameters:
6604 // - In a deduced context, the matching of packs versus fixed-size needs to
6605 // be inverted between Ps and As. On non-deduced context, matching needs to
6606 // happen both ways, according to [temp.arg.template]p3, but this is
6607 // currently implemented as a special case elsewhere.
6609 *this, A, AArgs, PArgs, Info, Deduced,
6610 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/true,
6611 PartialOrdering ? PackFold::ArgumentToParameter : PackFold::Both,
6612 /*HasDeducedAnyParam=*/nullptr)) {
6614 if (StrictPackMatch && Info.hasStrictPackMatch())
6615 *StrictPackMatch = true;
6616 break;
6617
6619 Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
6620 << (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
6621 << SourceRange(A->getTemplateLoc(), P->getRAngleLoc());
6622 return false;
6624 Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
6625 << Info.FirstArg << Info.SecondArg;
6626 return false;
6629 diag::err_inconsistent_deduction)
6630 << Info.FirstArg << Info.SecondArg;
6631 return false;
6633 return false;
6634
6635 // None of these should happen for a plain deduction.
6650 llvm_unreachable("Unexpected Result");
6651 }
6652
6655 TDK = ::FinishTemplateArgumentDeduction(
6656 *this, AArg, AArg->getTemplateParameters(), AArg, PartialOrdering,
6657 AArgs, PArgs, Deduced, Info, /*CopyDeducedArgs=*/false);
6658 });
6659 switch (TDK) {
6661 return true;
6662
6663 // It doesn't seem possible to get a non-deduced mismatch when partial
6664 // ordering TTPs, except with an invalid template parameter list which has
6665 // a parameter after a pack.
6667 assert(PArg->isInvalidDecl() && "Unexpected NonDeducedMismatch");
6668 return false;
6669
6670 // Substitution failures should have already been diagnosed.
6674 return false;
6675
6676 // None of these should happen when just converting deduced arguments.
6691 llvm_unreachable("Unexpected Result");
6692 }
6693 llvm_unreachable("Unexpected TDK");
6694}
6695
6696namespace {
6697struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6698 llvm::SmallBitVector &Used;
6699 unsigned Depth;
6700
6701 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6702 unsigned Depth)
6703 : Used(Used), Depth(Depth) { }
6704
6705 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6706 if (T->getDepth() == Depth)
6707 Used[T->getIndex()] = true;
6708 return true;
6709 }
6710
6711 bool TraverseTemplateName(TemplateName Template) override {
6712 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6713 Template.getAsTemplateDecl()))
6714 if (TTP->getDepth() == Depth)
6715 Used[TTP->getIndex()] = true;
6717 return true;
6718 }
6719
6720 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6721 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6722 if (NTTP->getDepth() == Depth)
6723 Used[NTTP->getIndex()] = true;
6724 return true;
6725 }
6726
6727 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
6728 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
6729 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
6730 if (TTP->getDepth() == Depth)
6731 Used[TTP->getIndex()] = true;
6732 }
6733 for (auto &TLoc : ULE->template_arguments())
6735 }
6736 return true;
6737 }
6738};
6739}
6740
6741/// Mark the template parameters that are used by the given
6742/// expression.
6743static void
6745 const Expr *E,
6746 bool OnlyDeduced,
6747 unsigned Depth,
6748 llvm::SmallBitVector &Used) {
6749 if (!OnlyDeduced) {
6750 MarkUsedTemplateParameterVisitor(Used, Depth)
6751 .TraverseStmt(const_cast<Expr *>(E));
6752 return;
6753 }
6754
6755 // We can deduce from a pack expansion.
6756 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6757 E = Expansion->getPattern();
6758
6760 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E);
6761 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
6762 if (const auto *TTP = ULE->getTemplateTemplateDecl())
6763 Used[TTP->getIndex()] = true;
6764 for (auto &TLoc : ULE->template_arguments())
6765 MarkUsedTemplateParameters(Ctx, TLoc.getArgument(), OnlyDeduced, Depth,
6766 Used);
6767 return;
6768 }
6769
6770 const NonTypeOrVarTemplateParmDecl NTTP =
6772 if (!NTTP)
6773 return;
6774 if (NTTP.getDepth() == Depth)
6775 Used[NTTP.getIndex()] = true;
6776
6777 // In C++17 mode, additional arguments may be deduced from the type of a
6778 // non-type argument.
6779 if (Ctx.getLangOpts().CPlusPlus17)
6780 MarkUsedTemplateParameters(Ctx, NTTP.getType(), OnlyDeduced, Depth, Used);
6781}
6782
6783/// Mark the template parameters that are used by the given
6784/// nested name specifier.
6786 bool OnlyDeduced, unsigned Depth,
6787 llvm::SmallBitVector &Used) {
6789 return;
6790 MarkUsedTemplateParameters(Ctx, QualType(NNS.getAsType(), 0), OnlyDeduced,
6791 Depth, Used);
6792}
6793
6794/// Mark the template parameters that are used by the given
6795/// template name.
6796static void
6798 TemplateName Name,
6799 bool OnlyDeduced,
6800 unsigned Depth,
6801 llvm::SmallBitVector &Used) {
6802 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6804 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6805 if (TTP->getDepth() == Depth)
6806 Used[TTP->getIndex()] = true;
6807 }
6808 return;
6809 }
6810
6811 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6812 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6813 Depth, Used);
6814 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6815 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6816 Depth, Used);
6817}
6818
6819/// Mark the template parameters that are used by the given
6820/// type.
6821static void
6823 bool OnlyDeduced,
6824 unsigned Depth,
6825 llvm::SmallBitVector &Used) {
6826 if (T.isNull())
6827 return;
6828
6829 // Non-dependent types have nothing deducible
6830 if (!T->isDependentType())
6831 return;
6832
6833 T = Ctx.getCanonicalType(T);
6834 switch (T->getTypeClass()) {
6835 case Type::Pointer:
6837 cast<PointerType>(T)->getPointeeType(),
6838 OnlyDeduced,
6839 Depth,
6840 Used);
6841 break;
6842
6843 case Type::BlockPointer:
6845 cast<BlockPointerType>(T)->getPointeeType(),
6846 OnlyDeduced,
6847 Depth,
6848 Used);
6849 break;
6850
6851 case Type::LValueReference:
6852 case Type::RValueReference:
6854 cast<ReferenceType>(T)->getPointeeType(),
6855 OnlyDeduced,
6856 Depth,
6857 Used);
6858 break;
6859
6860 case Type::MemberPointer: {
6861 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6862 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6863 Depth, Used);
6865 QualType(MemPtr->getQualifier().getAsType(), 0),
6866 OnlyDeduced, Depth, Used);
6867 break;
6868 }
6869
6870 case Type::DependentSizedArray:
6872 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6873 OnlyDeduced, Depth, Used);
6874 // Fall through to check the element type
6875 [[fallthrough]];
6876
6877 case Type::ConstantArray:
6878 case Type::IncompleteArray:
6879 case Type::ArrayParameter:
6881 cast<ArrayType>(T)->getElementType(),
6882 OnlyDeduced, Depth, Used);
6883 break;
6884 case Type::Vector:
6885 case Type::ExtVector:
6887 cast<VectorType>(T)->getElementType(),
6888 OnlyDeduced, Depth, Used);
6889 break;
6890
6891 case Type::DependentVector: {
6892 const auto *VecType = cast<DependentVectorType>(T);
6893 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6894 Depth, Used);
6895 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6896 Used);
6897 break;
6898 }
6899 case Type::DependentSizedExtVector: {
6900 const DependentSizedExtVectorType *VecType
6901 = cast<DependentSizedExtVectorType>(T);
6902 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6903 Depth, Used);
6904 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6905 Depth, Used);
6906 break;
6907 }
6908
6909 case Type::DependentAddressSpace: {
6910 const DependentAddressSpaceType *DependentASType =
6911 cast<DependentAddressSpaceType>(T);
6912 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6913 OnlyDeduced, Depth, Used);
6915 DependentASType->getAddrSpaceExpr(),
6916 OnlyDeduced, Depth, Used);
6917 break;
6918 }
6919
6920 case Type::ConstantMatrix: {
6921 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6922 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6923 Depth, Used);
6924 break;
6925 }
6926
6927 case Type::DependentSizedMatrix: {
6928 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6929 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6930 Depth, Used);
6931 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6932 Used);
6933 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6934 Depth, Used);
6935 break;
6936 }
6937
6938 case Type::FunctionProto: {
6939 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6940 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6941 Used);
6942 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6943 // C++17 [temp.deduct.type]p5:
6944 // The non-deduced contexts are: [...]
6945 // -- A function parameter pack that does not occur at the end of the
6946 // parameter-declaration-list.
6947 if (!OnlyDeduced || I + 1 == N ||
6948 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6949 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6950 Depth, Used);
6951 } else {
6952 // FIXME: C++17 [temp.deduct.call]p1:
6953 // When a function parameter pack appears in a non-deduced context,
6954 // the type of that pack is never deduced.
6955 //
6956 // We should also track a set of "never deduced" parameters, and
6957 // subtract that from the list of deduced parameters after marking.
6958 }
6959 }
6960 if (auto *E = Proto->getNoexceptExpr())
6961 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6962 break;
6963 }
6964
6965 case Type::TemplateTypeParm: {
6966 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6967 if (TTP->getDepth() == Depth)
6968 Used[TTP->getIndex()] = true;
6969 break;
6970 }
6971
6972 case Type::SubstTemplateTypeParmPack: {
6974 = cast<SubstTemplateTypeParmPackType>(T);
6975 if (Subst->getReplacedParameter()->getDepth() == Depth)
6976 Used[Subst->getIndex()] = true;
6977 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(), OnlyDeduced,
6978 Depth, Used);
6979 break;
6980 }
6981 case Type::SubstBuiltinTemplatePack: {
6982 MarkUsedTemplateParameters(Ctx, cast<SubstPackType>(T)->getArgumentPack(),
6983 OnlyDeduced, Depth, Used);
6984 break;
6985 }
6986
6987 case Type::InjectedClassName:
6988 T = cast<InjectedClassNameType>(T)
6989 ->getOriginalDecl()
6990 ->getCanonicalTemplateSpecializationType(Ctx);
6991 [[fallthrough]];
6992
6993 case Type::TemplateSpecialization: {
6994 const TemplateSpecializationType *Spec
6995 = cast<TemplateSpecializationType>(T);
6996 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6997 Depth, Used);
6998
6999 // C++0x [temp.deduct.type]p9:
7000 // If the template argument list of P contains a pack expansion that is
7001 // not the last template argument, the entire template argument list is a
7002 // non-deduced context.
7003 if (OnlyDeduced &&
7005 break;
7006
7007 for (const auto &Arg : Spec->template_arguments())
7008 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
7009 break;
7010 }
7011
7012 case Type::Complex:
7013 if (!OnlyDeduced)
7015 cast<ComplexType>(T)->getElementType(),
7016 OnlyDeduced, Depth, Used);
7017 break;
7018
7019 case Type::Atomic:
7020 if (!OnlyDeduced)
7022 cast<AtomicType>(T)->getValueType(),
7023 OnlyDeduced, Depth, Used);
7024 break;
7025
7026 case Type::DependentName:
7027 if (!OnlyDeduced)
7029 cast<DependentNameType>(T)->getQualifier(),
7030 OnlyDeduced, Depth, Used);
7031 break;
7032
7033 case Type::DependentTemplateSpecialization: {
7034 // C++14 [temp.deduct.type]p5:
7035 // The non-deduced contexts are:
7036 // -- The nested-name-specifier of a type that was specified using a
7037 // qualified-id
7038 //
7039 // C++14 [temp.deduct.type]p6:
7040 // When a type name is specified in a way that includes a non-deduced
7041 // context, all of the types that comprise that type name are also
7042 // non-deduced.
7043 if (OnlyDeduced)
7044 break;
7045
7047 = cast<DependentTemplateSpecializationType>(T);
7048
7051 OnlyDeduced, Depth, Used);
7052
7053 for (const auto &Arg : Spec->template_arguments())
7054 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
7055 break;
7056 }
7057
7058 case Type::TypeOf:
7059 if (!OnlyDeduced)
7060 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
7061 OnlyDeduced, Depth, Used);
7062 break;
7063
7064 case Type::TypeOfExpr:
7065 if (!OnlyDeduced)
7067 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
7068 OnlyDeduced, Depth, Used);
7069 break;
7070
7071 case Type::Decltype:
7072 if (!OnlyDeduced)
7074 cast<DecltypeType>(T)->getUnderlyingExpr(),
7075 OnlyDeduced, Depth, Used);
7076 break;
7077
7078 case Type::PackIndexing:
7079 if (!OnlyDeduced) {
7080 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
7081 OnlyDeduced, Depth, Used);
7082 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
7083 OnlyDeduced, Depth, Used);
7084 }
7085 break;
7086
7087 case Type::UnaryTransform:
7088 if (!OnlyDeduced)
7090 cast<UnaryTransformType>(T)->getUnderlyingType(),
7091 OnlyDeduced, Depth, Used);
7092 break;
7093
7094 case Type::PackExpansion:
7096 cast<PackExpansionType>(T)->getPattern(),
7097 OnlyDeduced, Depth, Used);
7098 break;
7099
7100 case Type::Auto:
7101 case Type::DeducedTemplateSpecialization:
7103 cast<DeducedType>(T)->getDeducedType(),
7104 OnlyDeduced, Depth, Used);
7105 break;
7106 case Type::DependentBitInt:
7108 cast<DependentBitIntType>(T)->getNumBitsExpr(),
7109 OnlyDeduced, Depth, Used);
7110 break;
7111
7112 case Type::HLSLAttributedResource:
7114 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
7115 Depth, Used);
7116 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
7118 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
7119 OnlyDeduced, Depth, Used);
7120 break;
7121
7122 // None of these types have any template parameters in them.
7123 case Type::Builtin:
7124 case Type::VariableArray:
7125 case Type::FunctionNoProto:
7126 case Type::Record:
7127 case Type::Enum:
7128 case Type::ObjCInterface:
7129 case Type::ObjCObject:
7130 case Type::ObjCObjectPointer:
7131 case Type::UnresolvedUsing:
7132 case Type::Pipe:
7133 case Type::BitInt:
7134 case Type::HLSLInlineSpirv:
7135#define TYPE(Class, Base)
7136#define ABSTRACT_TYPE(Class, Base)
7137#define DEPENDENT_TYPE(Class, Base)
7138#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7139#include "clang/AST/TypeNodes.inc"
7140 break;
7141 }
7142}
7143
7144/// Mark the template parameters that are used by this
7145/// template argument.
7146static void
7149 bool OnlyDeduced,
7150 unsigned Depth,
7151 llvm::SmallBitVector &Used) {
7152 switch (TemplateArg.getKind()) {
7158 break;
7159
7161 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
7162 Depth, Used);
7163 break;
7164
7168 TemplateArg.getAsTemplateOrTemplatePattern(),
7169 OnlyDeduced, Depth, Used);
7170 break;
7171
7173 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
7174 Depth, Used);
7175 break;
7176
7178 for (const auto &P : TemplateArg.pack_elements())
7179 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
7180 break;
7181 }
7182}
7183
7184void
7185Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
7186 unsigned Depth,
7187 llvm::SmallBitVector &Used) {
7188 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
7189}
7190
7191void
7193 bool OnlyDeduced, unsigned Depth,
7194 llvm::SmallBitVector &Used) {
7195 // C++0x [temp.deduct.type]p9:
7196 // If the template argument list of P contains a pack expansion that is not
7197 // the last template argument, the entire template argument list is a
7198 // non-deduced context.
7199 if (OnlyDeduced &&
7200 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
7201 return;
7202
7203 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7204 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
7205 Depth, Used);
7206}
7207
7209 unsigned Depth,
7210 llvm::SmallBitVector &Used) {
7211 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7212 ::MarkUsedTemplateParameters(Context, TemplateArgs[I],
7213 /*OnlyDeduced=*/false, Depth, Used);
7214}
7215
7218 llvm::SmallBitVector &Deduced) {
7219 TemplateParameterList *TemplateParams
7220 = FunctionTemplate->getTemplateParameters();
7221 Deduced.clear();
7222 Deduced.resize(TemplateParams->size());
7223
7224 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
7225 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
7226 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
7227 true, TemplateParams->getDepth(), Deduced);
7228}
7229
7232 QualType T) {
7233 if (!T->isDependentType())
7234 return false;
7235
7236 TemplateParameterList *TemplateParams
7237 = FunctionTemplate->getTemplateParameters();
7238 llvm::SmallBitVector Deduced(TemplateParams->size());
7239 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
7240 Deduced);
7241
7242 return Deduced.any();
7243}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Provides definitions for the various language-specific address spaces.
const Decl * D
Expr * E
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1192
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.
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:145
#define X(type, name)
Definition: Value.h:145
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 QualType getUnderlyingType(const SubRegion *R)
SourceLocation Loc
Definition: SemaObjC.cpp:754
static TemplateDeductionResult DeduceNullPtrTemplateArgument(Sema &S, TemplateParameterList *TemplateParams, NonTypeOrVarTemplateParmDecl NTTP, QualType NullPtrType, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Deduce the value of the given non-type template parameter from the given null pointer template argume...
static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, TemplateDeductionInfo &Info, bool IsDeduced, Sema::CheckTemplateArgumentInfo &CTAI)
Convert the given deduced template argument and add it to the set of fully-converted template argumen...
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static TemplateDeductionResult DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams, const QualType P, QualType A, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(Sema &S, TemplateParameterList *TemplateParams, QualType Param, QualType Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF, PartialOrderingKind POK, bool DeducedFromArrayBound, bool *HasDeducedAnyParam)
Deduce the template arguments by comparing the parameter type and the argument type (C++ [temp....
static TemplateDeductionResult CheckDeductionConsistency(Sema &S, FunctionTemplateDecl *FTD, UnsignedOrNone ArgIdx, QualType P, QualType A, ArrayRef< TemplateArgument > DeducedArgs, bool CheckConsistency)
static PartialOrderingKind degradeCallPartialOrderingKind(PartialOrderingKind POK)
When propagating a partial ordering kind into a NonCall context, this is used to downgrade a 'Call' i...
static MoreSpecializedTrailingPackTieBreakerResult getMoreSpecializedTrailingPackTieBreaker(const TemplateSpecializationType *TST1, const TemplateSpecializationType *TST2)
static TemplateLikeDecl * getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1, PrimaryDel *P2, TemplateDeductionInfo &Info)
Returns the more specialized template specialization between T1/P1 and T2/P2.
static DeducedTemplateArgument checkDeducedTemplateArguments(ASTContext &Context, const DeducedTemplateArgument &X, const DeducedTemplateArgument &Y, bool AggregateCandidateDeduction=false)
Verify that the given, deduced template arguments are compatible.
static const Expr * unwrapExpressionForDeduction(const Expr *E)
static bool isSameDeclaration(Decl *X, Decl *Y)
Determine whether two declaration pointers refer to the same declaration.
static NonTypeOrVarTemplateParmDecl getDeducedNTTParameterFromExpr(const Expr *E, unsigned Depth)
If the given expression is of a form that permits the deduction of a non-type template parameter,...
static TemplateDeductionResult DeduceForEachType(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< QualType > Params, ArrayRef< QualType > Args, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, PartialOrderingKind POK, bool FinishingDeduction, T &&DeductFunc)
static TemplateDeductionResult DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD, TemplateParameterList *TemplateParams, QualType P, TemplateDeductionInfo &Info, bool PartialOrdering, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool *HasDeducedAnyParam)
Attempt to deduce the template arguments by checking the base types according to (C++20 [temp....
static bool hasTemplateArgumentForDeduction(ArrayRef< TemplateArgument > &Args, unsigned &ArgIdx)
Determine whether there is a template argument to be used for deduction.
static DeclContext * getAsDeclContextOrEnclosing(Decl *D)
static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, QualType ArgType)
Determine whether the parameter has qualifiers that the argument lacks.
static void MarkUsedTemplateParameters(ASTContext &Ctx, const TemplateArgument &TemplateArg, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark the template parameters that are used by this template argument.
static UnsignedOrNone getPackIndexForParam(Sema &S, FunctionTemplateDecl *FunctionTemplate, const MultiLevelTemplateArgumentList &Args, unsigned ParamIdx)
Find the pack index for a particular parameter index in an instantiation of a function template with ...
static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, FunctionDecl *Fn)
Gets the type of a function for template-argument-deducton purposes when it's considered as part of a...
static bool hasPackExpansionBeforeEnd(ArrayRef< TemplateArgument > Args)
Determine whether the given set of template arguments has a pack expansion that is not the last templ...
static bool isSimpleTemplateIdType(QualType T)
Determine whether the given type T is a simple-template-id type.
PartialOrderingKind
The kind of PartialOrdering we're performing template argument deduction for (C++11 [temp....
MoreSpecializedTrailingPackTieBreakerResult
static TemplateParameter makeTemplateParameter(Decl *D)
Helper function to build a TemplateParameter when we don't know its type statically.
static TemplateDeductionResult CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info, Sema::OriginalCallArg OriginalArg, QualType DeducedA)
Check whether the deduced argument type for a call to a function template matches the actual argument...
static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType &ParamType, QualType &ArgType, Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform the adjustments to the parameter and argument types described in C++ [temp....
static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex, QualType ParamType, QualType ArgType, Expr::Classification ArgClassification, Expr *Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, bool DecomposedParam, unsigned ArgIdx, unsigned TDF, TemplateSpecCandidateSet *FailedTSC=nullptr)
Perform template argument deduction per [temp.deduct.call] for a single parameter / argument pair.
static bool isAtLeastAsSpecializedAs(Sema &S, SourceLocation Loc, FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC, ArrayRef< QualType > Args1, ArrayRef< QualType > Args2, bool Args1Offset)
Determine whether the function template FT1 is at least as specialized as FT2.
static QualType GetImplicitObjectParameterType(ASTContext &Context, const CXXMethodDecl *Method, QualType RawType, bool IsOtherRvr)
static TemplateDeductionResult DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, InitListExpr *ILE, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< Sema::OriginalCallArg > &OriginalCallArgs, unsigned ArgIdx, unsigned TDF)
Attempt template argument deduction from an initializer list deemed to be an argument in a function c...
static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD)
Get the index of the first template parameter that was originally from the innermost template-paramet...
PackFold
What directions packs are allowed to match non-packs.
@ ArgumentToParameter
@ ParameterToArgument
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.
C Language Family Type Representation.
__device__ int
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:188
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:3056
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 getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg) const
Retrieve the "canonical" template argument.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2851
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2867
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > CanonicalArgs) const
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
Definition: ASTContext.h:3062
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
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
Definition: ASTContext.h:1250
CanQualType NullPtrTy
Definition: ASTContext.h:1249
const LangOptions & getLangOpts() const
Definition: ASTContext.h:894
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
CanQualType BoolTy
Definition: ASTContext.h:1223
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
Definition: ASTContext.h:1231
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2442
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
Definition: ASTContext.h:1599
CanQualType OverloadTy
Definition: ASTContext.h:1250
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2898
TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl) const
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.
Definition: ASTContext.h:2625
CanQualType UnsignedIntTy
Definition: ASTContext.h:1232
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1750
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 ...
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 ...
QualType getUnconstrainedType(QualType T) const
Remove any type constraints from a template parameter type, for equivalence comparison of template pa...
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.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
bool canonicalizeTemplateArguments(MutableArrayRef< TemplateArgument > Args) const
Canonicalize the given template argument list.
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 getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
const DependentSizedArrayType * getAsDependentSizedArrayType(QualType T) const
Definition: ASTContext.h:3065
The result of parsing/analyzing an expression, statement etc.
Definition: Ownership.h:154
PtrTy get() const
Definition: Ownership.h:171
bool isInvalid() const
Definition: Ownership.h:167
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: TypeBase.h:7180
ArrayRef< TemplateArgument > getTypeConstraintArguments() const
Definition: TypeBase.h:7190
bool isDecltypeAuto() const
Definition: TypeBase.h:7203
AutoTypeKeyword getKeyword() const
Definition: TypeBase.h:7211
bool isConstrained() const
Definition: TypeBase.h:7199
TemplateDecl * getTypeConstraintConcept() const
Definition: TypeBase.h:7195
A fixed int type of a specified bitwidth.
Definition: TypeBase.h:8195
Pointer to a block type.
Definition: TypeBase.h:3558
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2937
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2977
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2129
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:2703
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2305
bool isStatic() const
Definition: DeclCXX.cpp:2401
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:768
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:1736
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:3293
Declaration of a C++20 concept.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:438
Represents a concrete matrix type with constant number of rows and columns.
Definition: TypeBase.h:4389
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: TypeBase.h:4410
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: TypeBase.h:4407
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:37
A POD class for pairing a NamedDecl* with an access specifier.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2109
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1272
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:263
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:524
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:244
bool isInvalidDecl() const
Definition: DeclBase.h:588
SourceLocation getLocation() const
Definition: DeclBase.h:439
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack.
Definition: DeclBase.cpp:234
DeclContext * getDeclContext()
Definition: DeclBase.h:448
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:978
Kind getKind() const
Definition: DeclBase.h:442
Captures a template argument whose value has been deduced via c++ template argument deduction.
Definition: Template.h:327
void setDeducedFromArrayBound(bool Deduced)
Specify whether the given non-type template argument was deduced from an array bound.
Definition: Template.h:354
bool wasDeducedFromArrayBound() const
For a non-type template argument, determine whether the template argument was deduced from an array b...
Definition: Template.h:350
SourceLocation getElaboratedKeywordLoc() const
Definition: TypeLoc.h:2489
NestedNameSpecifierLoc getQualifierLoc() const
Definition: TypeLoc.h:2501
TemplateName getTemplateName() const
Retrieve the name of the template that we are deducing.
Definition: TypeBase.h:7248
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: TypeBase.h:7146
Represents an extended address space qualifier where the input address space value is dependent.
Definition: TypeBase.h:4077
QualType getPointeeType() const
Definition: TypeBase.h:4089
Represents an extended vector type where either the type or size is dependent.
Definition: TypeBase.h:4117
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: TypeBase.h:4448
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: TypeBase.h:7465
const DependentTemplateStorage & getDependentTemplateName() const
Definition: TypeBase.h:7476
ArrayRef< TemplateArgument > template_arguments() const
Definition: TypeBase.h:7480
NestedNameSpecifier getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:607
Represents a vector type where either the type or size is dependent.
Definition: TypeBase.h:4243
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc)
Recursively visit a template argument location and dispatch to the appropriate method for the argumen...
virtual bool TraverseTemplateName(TemplateName Template)
Recursively visit a template name and dispatch to the appropriate method.
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1924
bool isInvalid() const
Determine if the explicit specifier is invalid.
Definition: DeclCXX.h:1953
const Expr * getExpr() const
Definition: DeclCXX.h:1933
The return type of classify().
Definition: Expr.h:337
bool isLValue() const
Definition: Expr.h:387
This represents one expression.
Definition: Expr.h:112
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:177
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:273
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:412
QualType getType() const
Definition: Expr.h:144
ExtVectorType - Extended vector type.
Definition: TypeBase.h:4283
Stores a list of template parameters and the associated requires-clause (if any) for a TemplateDecl a...
Definition: DeclTemplate.h:228
Represents a function declaration or definition.
Definition: Decl.h:1999
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2794
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4146
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4134
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3806
QualType getReturnType() const
Definition: Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2771
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:4205
void getAssociatedConstraints(SmallVectorImpl< AssociatedConstraint > &ACs) const
Get the associated-constraints of this function declaration.
Definition: Decl.h:2749
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4270
bool isImmediateEscalating() const
Definition: Decl.cpp:3303
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:4071
size_t param_size() const
Definition: Decl.h:2787
Represents a prototype with parameter type info, e.g.
Definition: TypeBase.h:5282
param_type_iterator param_type_begin() const
Definition: TypeBase.h:5726
const ExtParameterInfo * getExtParameterInfosOrNull() const
Return a pointer to the beginning of the array of extra parameter information, if present,...
Definition: TypeBase.h:5764
unsigned getNumParams() const
Definition: TypeBase.h:5560
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: TypeBase.h:5702
Qualifiers getMethodQuals() const
Definition: TypeBase.h:5708
QualType getParamType(unsigned i) const
Definition: TypeBase.h:5562
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: TypeBase.h:5595
bool isVariadic() const
Whether this function prototype is variadic.
Definition: TypeBase.h:5686
ExtProtoInfo getExtProtoInfo() const
Definition: TypeBase.h:5571
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: TypeBase.h:5647
param_type_iterator param_type_end() const
Definition: TypeBase.h:5730
ArrayRef< QualType > getParamTypes() const
Definition: TypeBase.h:5567
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: TypeBase.h:5716
Declaration of a template function.
Definition: DeclTemplate.h:952
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:998
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: TypeBase.h:4478
QualType getReturnType() const
Definition: TypeBase.h:4818
static ImplicitConceptSpecializationDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation SL, ArrayRef< TemplateArgument > ConvertedArgs)
Describes an C or C++ initializer list.
Definition: Expr.h:5235
unsigned getNumInits() const
Definition: Expr.h:5265
unsigned getNumInitsWithEmbedExpanded() const
getNumInits but if the list has an EmbedExpr inside includes full length of embedded data.
Definition: Expr.h:5269
ArrayRef< Expr * > inits()
Definition: Expr.h:5285
The injected class name of a C++ class template or class template partial specialization.
Definition: TypeBase.h:6553
ElaboratedTypeKeyword getKeyword() const
Definition: TypeBase.h:5959
An lvalue reference type, per C++11 [dcl.ref].
Definition: TypeBase.h:3633
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1970
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
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:553
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: TypeBase.h:4353
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: TypeBase.h:4367
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: TypeBase.h:3669
NestedNameSpecifier getQualifier() const
Definition: TypeBase.h:3701
QualType getPointeeType() const
Definition: TypeBase.h:3687
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args)
Replaces the current 'innermost' level with the provided argument list.
Definition: Template.h:237
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:273
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:339
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>::".
@ Type
A type, stored as a Type*.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents a pointer to an Objective C object.
Definition: TypeBase.h:7961
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:3122
bool isVarDeclReference() const
Definition: ExprCXX.h:3296
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:3274
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3183
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:3235
decls_iterator decls_begin() const
Definition: ExprCXX.h:3215
TemplateTemplateParmDecl * getTemplateTemplateDecl() const
Definition: ExprCXX.h:3312
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:3336
bool isConceptReference() const
Definition: ExprCXX.h:3285
decls_iterator decls_end() const
Definition: ExprCXX.h:3218
ArrayRef< TemplateArgumentLoc > template_arguments() const
Definition: ExprCXX.h:3331
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4357
Represents a pack expansion of types.
Definition: TypeBase.h:7524
UnsignedOrNone getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: TypeBase.h:7549
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: TypeBase.h:7545
bool hasSelectedType() const
Definition: TypeBase.h:6348
QualType getSelectedType() const
Definition: TypeBase.h:6341
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:256
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: TypeBase.h:3346
QualType getPointeeType() const
Definition: TypeBase.h:3356
A (possibly-)qualified type.
Definition: TypeBase.h:937
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: TypeBase.h:8432
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: TypeBase.h:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition: TypeBase.h:8469
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: TypeBase.h:8383
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:8528
QualType getCanonicalType() const
Definition: TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: TypeBase.h:8437
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: TypeBase.h:8464
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: TypeBase.h:8389
Represents a template name as written in source code.
Definition: TemplateName.h:504
The collection of all-type qualifiers we support.
Definition: TypeBase.h:331
unsigned getCVRQualifiers() const
Definition: TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition: TypeBase.h:495
GC getObjCGCAttr() const
Definition: TypeBase.h:519
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition: TypeBase.h:350
void removeObjCLifetime()
Definition: TypeBase.h:551
bool isStrictSupersetOf(Qualifiers Other) const
Determine whether this set of qualifiers is a strict superset of another set of qualifiers,...
Definition: Type.cpp:57
bool hasConst() const
Definition: TypeBase.h:457
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition: TypeBase.h:559
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition: TypeBase.h:727
bool hasAddressSpace() const
Definition: TypeBase.h:570
void removeObjCGCAttr()
Definition: TypeBase.h:523
void removeAddressSpace()
Definition: TypeBase.h:596
bool hasObjCGCAttr() const
Definition: TypeBase.h:518
void setCVRQualifiers(unsigned mask)
Definition: TypeBase.h:491
bool hasObjCLifetime() const
Definition: TypeBase.h:544
ObjCLifetime getObjCLifetime() const
Definition: TypeBase.h:545
Qualifiers withoutObjCLifetime() const
Definition: TypeBase.h:533
LangAS getAddressSpace() const
Definition: TypeBase.h:571
void setObjCLifetime(ObjCLifetime type)
Definition: TypeBase.h:548
An rvalue reference type, per C++11 [dcl.ref].
Definition: TypeBase.h:3651
ArrayRef< TemplateArgument > getInjectedTemplateArgs(const ASTContext &Context) const
Retrieve the "injected" template arguments that correspond to the template parameters of this templat...
Definition: DeclTemplate.h:915
Base for LValueReferenceType and RValueReferenceType.
Definition: TypeBase.h:3589
QualType getPointeeType() const
Definition: TypeBase.h:3607
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, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:61
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13496
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8393
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3468
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12907
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:12926
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12359
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12392
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:850
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:12936
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
TemplateDeductionResult DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType, sema::TemplateDeductionInfo &Info)
Deduce the template arguments of the given template from FromType.
QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement)
Completely replace the auto in TypeWithAuto by Replacement.
SemaCUDA & CUDA()
Definition: Sema.h:1438
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:6882
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:11903
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11895
@ CTAK_Deduced
The template argument was deduced via template argument deduction.
Definition: Sema.h:11899
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition: Sema.h:1276
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2642
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ASTContext & getASTContext() const
Definition: Sema.h:918
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:756
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:1184
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
@ TPL_TemplateParamsEquivalent
We are determining whether the template-parameters are equivalent according to C++ [temp....
Definition: Sema.h:12093
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:911
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14709
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
UnsignedOrNone getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs)
Determine the number of arguments in the given pack expansion type.
ExplicitSpecifier instantiateExplicitSpecifier(const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES)
TemplateDeductionResult SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< QualType > &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info)
Substitute the explicitly-provided template arguments into the given function template according to C...
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl * > Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1411
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:12425
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.
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...
Definition: SemaType.cpp:9740
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21316
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateKWLoc, SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param, ArrayRef< TemplateArgument > SugaredConverted, ArrayRef< TemplateArgument > CanonicalConverted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto)
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:15279
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.
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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,...
Definition: SemaType.cpp:9216
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:627
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
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 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
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.
Definition: SemaType.cpp:8231
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:12779
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.
TemplateArgument getArgumentPack() const
Definition: Type.cpp:4532
Represents the result of substituting a set of types for a template type parameter pack.
Definition: TypeBase.h:7091
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TypeBase.h:7117
const TemplateTypeParmDecl * getReplacedParameter() const
Gets the template parameter declaration that was substituted for.
Definition: Type.cpp:4569
A convenient class for passing around template argument information.
Definition: TemplateBase.h:634
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:669
A template argument list.
Definition: DeclTemplate.h:250
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.
Definition: DeclTemplate.h:286
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:271
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:528
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:334
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:411
pack_iterator pack_end() const
Iterator referencing one past the last argument of a template argument pack.
Definition: TemplateBase.h:433
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:426
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.
Definition: TemplateBase.h:322
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:366
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:340
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.
Definition: TemplateBase.h:346
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.
Definition: TemplateBase.h:299
static TemplateArgument getEmptyPack()
Definition: TemplateBase.h:286
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:446
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.
Definition: TemplateBase.h:329
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:440
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:296
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,...
Definition: TemplateBase.h:353
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:396
void getAssociatedConstraints(llvm::SmallVectorImpl< AssociatedConstraint > &AC) const
Get the total constraint-expression associated with this template, including constraint-expressions d...
bool isTypeAlias() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclTemplate.h:441
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:415
Represents a C++ template name within the type system.
Definition: TemplateName.h:222
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:74
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:146
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
Definition: DeclTemplate.h:207
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:206
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:143
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
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...
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: TypeBase.h:7290
ArrayRef< TemplateArgument > template_arguments() const
Definition: TypeBase.h:7357
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: TypeBase.h:7355
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
TemplateNameKind templateParameterKind() const
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
unsigned getDepth() const
Retrieve the depth of the template parameter.
Wrapper for template type parameters.
Definition: TypeLoc.h:890
unsigned getIndex() const
Definition: TypeBase.h:6932
unsigned getDepth() const
Definition: TypeBase.h:6931
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
const Type * getTypeForDecl() const
Definition: Decl.h:3535
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:160
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:165
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition: TypeLoc.cpp:169
A container of type source information.
Definition: TypeBase.h:8314
SourceLocation getNameLoc() const
Definition: TypeLoc.h:552
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:556
The base class of the type hierarchy.
Definition: TypeBase.h:1833
bool isVoidType() const
Definition: TypeBase.h:8936
const TemplateSpecializationType * getAsNonAliasTemplateSpecializationType() const
Look through sugar for an instance of TemplateSpecializationType which is not a type alias,...
Definition: Type.cpp:1921
bool isIncompleteArrayType() const
Definition: TypeBase.h:8687
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:8912
bool isRValueReferenceType() const
Definition: TypeBase.h:8612
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 canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: TypeBase.h:9096
bool isArrayType() const
Definition: TypeBase.h:8679
bool isFunctionPointerType() const
Definition: TypeBase.h:8647
bool isPointerType() const
Definition: TypeBase.h:8580
const T * castAs() const
Member-template castAs<specific type>.
Definition: TypeBase.h:9226
bool isReferenceType() const
Definition: TypeBase.h:8604
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:752
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: TypeBase.h:2917
bool isLValueReferenceType() const
Definition: TypeBase.h:8608
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: TypeBase.h:2800
QualType getCanonicalTypeInternal() const
Definition: TypeBase.h:3137
bool isMemberPointerType() const
Definition: TypeBase.h:8661
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5355
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: TypeBase.h:9072
bool isFunctionType() const
Definition: TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition: TypeBase.h:8749
bool isMemberFunctionPointerType() const
Definition: TypeBase.h:8665
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition: TypeBase.h:2946
bool isAnyPointerType() const
Definition: TypeBase.h:8588
TypeClass getTypeClass() const
Definition: TypeBase.h:2403
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: TypeBase.h:2429
const T * getAs() const
Member-template getAs<specific type>'.
Definition: TypeBase.h:9159
bool isRecordType() const
Definition: TypeBase.h:8707
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3384
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
QualType getType() const
Definition: Decl.h:722
QualType getType() const
Definition: Value.cpp:237
Represents a variable declaration or definition.
Definition: Decl.h:925
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1577
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:4191
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.
#define bool
Definition: gpuintrin.h:32
__inline void unsigned int _2
Definition: larchintrin.h:181
The JSON file list parser is used to communicate input to InstallAPI.
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ Match
This is not an overload because the signature exactly matches an existing declaration.
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
@ RQ_None
No ref-qualifier was provided.
Definition: TypeBase.h:1782
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: TypeBase.h:1788
NamedDecl * getAsNamedDecl(TemplateParameter P)
bool isPackProducingBuiltinTemplateName(TemplateName N)
UnsignedOrNone getExpandedPackSize(const NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:85
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
@ Result
The result type of a method or function.
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:62
@ Template
We are parsing a template declaration.
@ FunctionTemplate
The name was classified as a function template name.
@ Concept
The name was classified as a concept name.
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:66
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition: ASTLambda.h:69
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
@ TNK_Concept_template
The name refers to a concept.
Definition: TemplateKinds.h:52
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
TPOC
The context in which partial ordering of function templates occurs.
Definition: Template.h:298
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:304
@ TPOC_Other
Partial ordering of function templates in other contexts, e.g., taking the address of a function temp...
Definition: Template.h:309
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition: Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:366
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
@ CUDATargetMismatch
CUDA Target attributes do not match.
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
@ Invalid
The declaration was invalid; do nothing.
@ Success
Template argument deduction was successful.
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ None
The alignment was not explicit in code.
@ Noexcept
Condition in a noexcept(bool) specifier.
@ 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...
ActionResult< CXXBaseSpecifier * > BaseResult
Definition: Ownership.h:252
#define true
Definition: stdbool.h:25
#define false
Definition: stdbool.h:26
A pack that we're currently deducing.
SmallVector< DeducedTemplateArgument, 4 > New
DeducedTemplateArgument Saved
DeducedTemplateArgument DeferredDeduction
Holds information about the various types of exception specification.
Definition: TypeBase.h:5339
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: TypeBase.h:5341
Extra information about a function prototype.
Definition: TypeBase.h:5367
const ExtParameterInfo * ExtParameterInfos
Definition: TypeBase.h:5372
bool StrictPackMatch
Is set to true when, in the context of TTP matching, a pack parameter matches non-pack arguments.
Definition: Sema.h:11930
bool MatchingTTP
If true, assume these template arguments are the injected template arguments for a template template ...
Definition: Sema.h:11926
bool PartialOrdering
The check is being performed in the context of partial ordering.
Definition: Sema.h:11919
SmallVector< TemplateArgument, 4 > SugaredConverted
The checked, converted argument will be added to the end of these vectors.
Definition: Sema.h:11916
SmallVector< TemplateArgument, 4 > CanonicalConverted
Definition: Sema.h:11916
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12974
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12981
A stack object to be created when performing template instantiation.
Definition: Sema.h:13144
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13304
brief A function argument from which we performed template argument
Definition: Sema.h:12525
Location information for a TemplateArgument.
Definition: TemplateBase.h:480