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