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