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