Reland [OffloadBundler] Compress bundles over 4GB (#122307)
[llvm-project.git] / clang / lib / Sema / SemaTemplateDeduction.cpp
blob1c1f6e30ab7b837ab83ec9ac2405f237e656bb0d
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.
11 //===----------------------------------------------------------------------===//
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/Sema/EnterExpressionEvaluationContext.h"
41 #include "clang/Sema/Ownership.h"
42 #include "clang/Sema/Sema.h"
43 #include "clang/Sema/Template.h"
44 #include "clang/Sema/TemplateDeduction.h"
45 #include "llvm/ADT/APInt.h"
46 #include "llvm/ADT/APSInt.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/FoldingSet.h"
50 #include "llvm/ADT/SmallBitVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallVector.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include <algorithm>
57 #include <cassert>
58 #include <optional>
59 #include <tuple>
60 #include <type_traits>
61 #include <utility>
63 namespace clang {
65 /// Various flags that control template argument deduction.
66 ///
67 /// These flags can be bitwise-OR'd together.
68 enum TemplateDeductionFlags {
69 /// No template argument deduction flags, which indicates the
70 /// strictest results for template argument deduction (as used for, e.g.,
71 /// matching class template partial specializations).
72 TDF_None = 0,
74 /// Within template argument deduction from a function call, we are
75 /// matching with a parameter type for which the original parameter was
76 /// a reference.
77 TDF_ParamWithReferenceType = 0x1,
79 /// Within template argument deduction from a function call, we
80 /// are matching in a case where we ignore cv-qualifiers.
81 TDF_IgnoreQualifiers = 0x02,
83 /// Within template argument deduction from a function call,
84 /// we are matching in a case where we can perform template argument
85 /// deduction from a template-id of a derived class of the argument type.
86 TDF_DerivedClass = 0x04,
88 /// Allow non-dependent types to differ, e.g., when performing
89 /// template argument deduction from a function call where conversions
90 /// may apply.
91 TDF_SkipNonDependent = 0x08,
93 /// Whether we are performing template argument deduction for
94 /// parameters and arguments in a top-level template argument
95 TDF_TopLevelParameterTypeList = 0x10,
97 /// Within template argument deduction from overload resolution per
98 /// C++ [over.over] allow matching function types that are compatible in
99 /// terms of noreturn and default calling convention adjustments, or
100 /// similarly matching a declared template specialization against a
101 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
102 /// deduction where the parameter is a function type that can be converted
103 /// to the argument type.
104 TDF_AllowCompatibleFunctionType = 0x20,
106 /// Within template argument deduction for a conversion function, we are
107 /// matching with an argument type for which the original argument was
108 /// a reference.
109 TDF_ArgWithReferenceType = 0x40,
113 using namespace clang;
114 using namespace sema;
116 /// Compare two APSInts, extending and switching the sign as
117 /// necessary to compare their values regardless of underlying type.
118 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
119 if (Y.getBitWidth() > X.getBitWidth())
120 X = X.extend(Y.getBitWidth());
121 else if (Y.getBitWidth() < X.getBitWidth())
122 Y = Y.extend(X.getBitWidth());
124 // If there is a signedness mismatch, correct it.
125 if (X.isSigned() != Y.isSigned()) {
126 // If the signed value is negative, then the values cannot be the same.
127 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
128 return false;
130 Y.setIsSigned(true);
131 X.setIsSigned(true);
134 return X == Y;
137 /// The kind of PartialOrdering we're performing template argument deduction
138 /// for (C++11 [temp.deduct.partial]).
139 enum class PartialOrderingKind { None, NonCall, Call };
141 static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
142 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
143 QualType Arg, TemplateDeductionInfo &Info,
144 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
145 PartialOrderingKind POK, bool DeducedFromArrayBound,
146 bool *HasDeducedAnyParam);
148 enum class PackFold { ParameterToArgument, ArgumentToParameter };
149 static TemplateDeductionResult
150 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
151 ArrayRef<TemplateArgument> Ps,
152 ArrayRef<TemplateArgument> As,
153 TemplateDeductionInfo &Info,
154 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
155 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
156 PackFold PackFold, bool *HasDeducedAnyParam);
158 static void MarkUsedTemplateParameters(ASTContext &Ctx,
159 const TemplateArgument &TemplateArg,
160 bool OnlyDeduced, unsigned Depth,
161 llvm::SmallBitVector &Used);
163 static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
164 bool OnlyDeduced, unsigned Level,
165 llvm::SmallBitVector &Deduced);
167 /// If the given expression is of a form that permits the deduction
168 /// of a non-type template parameter, return the declaration of that
169 /// non-type template parameter.
170 static const NonTypeTemplateParmDecl *
171 getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
172 // If we are within an alias template, the expression may have undergone
173 // any number of parameter substitutions already.
174 while (true) {
175 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
176 E = IC->getSubExpr();
177 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
178 E = CE->getSubExpr();
179 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
180 E = Subst->getReplacement();
181 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
182 // Look through implicit copy construction from an lvalue of the same type.
183 if (CCE->getParenOrBraceRange().isValid())
184 break;
185 // Note, there could be default arguments.
186 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
187 E = CCE->getArg(0);
188 } else
189 break;
192 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
193 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
194 if (NTTP->getDepth() == Depth)
195 return NTTP;
197 return nullptr;
200 static const NonTypeTemplateParmDecl *
201 getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
202 return getDeducedParameterFromExpr(E, Info.getDeducedDepth());
205 /// Determine whether two declaration pointers refer to the same
206 /// declaration.
207 static bool isSameDeclaration(Decl *X, Decl *Y) {
208 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
209 X = NX->getUnderlyingDecl();
210 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
211 Y = NY->getUnderlyingDecl();
213 return X->getCanonicalDecl() == Y->getCanonicalDecl();
216 /// Verify that the given, deduced template arguments are compatible.
218 /// \returns The deduced template argument, or a NULL template argument if
219 /// the deduced template arguments were incompatible.
220 static DeducedTemplateArgument
221 checkDeducedTemplateArguments(ASTContext &Context,
222 const DeducedTemplateArgument &X,
223 const DeducedTemplateArgument &Y,
224 bool AggregateCandidateDeduction = false) {
225 // We have no deduction for one or both of the arguments; they're compatible.
226 if (X.isNull())
227 return Y;
228 if (Y.isNull())
229 return X;
231 // If we have two non-type template argument values deduced for the same
232 // parameter, they must both match the type of the parameter, and thus must
233 // match each other's type. As we're only keeping one of them, we must check
234 // for that now. The exception is that if either was deduced from an array
235 // bound, the type is permitted to differ.
236 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
237 QualType XType = X.getNonTypeTemplateArgumentType();
238 if (!XType.isNull()) {
239 QualType YType = Y.getNonTypeTemplateArgumentType();
240 if (YType.isNull() || !Context.hasSameType(XType, YType))
241 return DeducedTemplateArgument();
245 switch (X.getKind()) {
246 case TemplateArgument::Null:
247 llvm_unreachable("Non-deduced template arguments handled above");
249 case TemplateArgument::Type: {
250 // If two template type arguments have the same type, they're compatible.
251 QualType TX = X.getAsType(), TY = Y.getAsType();
252 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
253 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
254 X.wasDeducedFromArrayBound() ||
255 Y.wasDeducedFromArrayBound());
257 // If one of the two arguments was deduced from an array bound, the other
258 // supersedes it.
259 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
260 return X.wasDeducedFromArrayBound() ? Y : X;
262 // The arguments are not compatible.
263 return DeducedTemplateArgument();
266 case TemplateArgument::Integral:
267 // If we deduced a constant in one case and either a dependent expression or
268 // declaration in another case, keep the integral constant.
269 // If both are integral constants with the same value, keep that value.
270 if (Y.getKind() == TemplateArgument::Expression ||
271 Y.getKind() == TemplateArgument::Declaration ||
272 (Y.getKind() == TemplateArgument::Integral &&
273 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
274 return X.wasDeducedFromArrayBound() ? Y : X;
276 // All other combinations are incompatible.
277 return DeducedTemplateArgument();
279 case TemplateArgument::StructuralValue:
280 // If we deduced a value and a dependent expression, keep the value.
281 if (Y.getKind() == TemplateArgument::Expression ||
282 (Y.getKind() == TemplateArgument::StructuralValue &&
283 X.structurallyEquals(Y)))
284 return X;
286 // All other combinations are incompatible.
287 return DeducedTemplateArgument();
289 case TemplateArgument::Template:
290 if (Y.getKind() == TemplateArgument::Template &&
291 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
292 return X;
294 // All other combinations are incompatible.
295 return DeducedTemplateArgument();
297 case TemplateArgument::TemplateExpansion:
298 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
299 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
300 Y.getAsTemplateOrTemplatePattern()))
301 return X;
303 // All other combinations are incompatible.
304 return DeducedTemplateArgument();
306 case TemplateArgument::Expression: {
307 if (Y.getKind() != TemplateArgument::Expression)
308 return checkDeducedTemplateArguments(Context, Y, X);
310 // Compare the expressions for equality
311 llvm::FoldingSetNodeID ID1, ID2;
312 X.getAsExpr()->Profile(ID1, Context, true);
313 Y.getAsExpr()->Profile(ID2, Context, true);
314 if (ID1 == ID2)
315 return X.wasDeducedFromArrayBound() ? Y : X;
317 // Differing dependent expressions are incompatible.
318 return DeducedTemplateArgument();
321 case TemplateArgument::Declaration:
322 assert(!X.wasDeducedFromArrayBound());
324 // If we deduced a declaration and a dependent expression, keep the
325 // declaration.
326 if (Y.getKind() == TemplateArgument::Expression)
327 return X;
329 // If we deduced a declaration and an integral constant, keep the
330 // integral constant and whichever type did not come from an array
331 // bound.
332 if (Y.getKind() == TemplateArgument::Integral) {
333 if (Y.wasDeducedFromArrayBound())
334 return TemplateArgument(Context, Y.getAsIntegral(),
335 X.getParamTypeForDecl());
336 return Y;
339 // If we deduced two declarations, make sure that they refer to the
340 // same declaration.
341 if (Y.getKind() == TemplateArgument::Declaration &&
342 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
343 return X;
345 // All other combinations are incompatible.
346 return DeducedTemplateArgument();
348 case TemplateArgument::NullPtr:
349 // If we deduced a null pointer and a dependent expression, keep the
350 // null pointer.
351 if (Y.getKind() == TemplateArgument::Expression)
352 return TemplateArgument(Context.getCommonSugaredType(
353 X.getNullPtrType(), Y.getAsExpr()->getType()),
354 true);
356 // If we deduced a null pointer and an integral constant, keep the
357 // integral constant.
358 if (Y.getKind() == TemplateArgument::Integral)
359 return Y;
361 // If we deduced two null pointers, they are the same.
362 if (Y.getKind() == TemplateArgument::NullPtr)
363 return TemplateArgument(
364 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
365 true);
367 // All other combinations are incompatible.
368 return DeducedTemplateArgument();
370 case TemplateArgument::Pack: {
371 if (Y.getKind() != TemplateArgument::Pack ||
372 (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
373 return DeducedTemplateArgument();
375 llvm::SmallVector<TemplateArgument, 8> NewPack;
376 for (TemplateArgument::pack_iterator
377 XA = X.pack_begin(),
378 XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
379 XA != XAEnd; ++XA) {
380 if (YA != YAEnd) {
381 TemplateArgument Merged = checkDeducedTemplateArguments(
382 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
383 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
384 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
385 return DeducedTemplateArgument();
386 NewPack.push_back(Merged);
387 ++YA;
388 } else {
389 NewPack.push_back(*XA);
393 return DeducedTemplateArgument(
394 TemplateArgument::CreatePackCopy(Context, NewPack),
395 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
399 llvm_unreachable("Invalid TemplateArgument Kind!");
402 /// Deduce the value of the given non-type template parameter
403 /// as the given deduced template argument. All non-type template parameter
404 /// deduction is funneled through here.
405 static TemplateDeductionResult
406 DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams,
407 const NonTypeTemplateParmDecl *NTTP,
408 const DeducedTemplateArgument &NewDeduced,
409 QualType ValueType, TemplateDeductionInfo &Info,
410 bool PartialOrdering,
411 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
412 bool *HasDeducedAnyParam) {
413 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
414 "deducing non-type template argument with wrong depth");
416 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
417 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
418 if (Result.isNull()) {
419 Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
420 Info.FirstArg = Deduced[NTTP->getIndex()];
421 Info.SecondArg = NewDeduced;
422 return TemplateDeductionResult::Inconsistent;
425 Deduced[NTTP->getIndex()] = Result;
426 if (!S.getLangOpts().CPlusPlus17)
427 return TemplateDeductionResult::Success;
429 if (NTTP->isExpandedParameterPack())
430 // FIXME: We may still need to deduce parts of the type here! But we
431 // don't have any way to find which slice of the type to use, and the
432 // type stored on the NTTP itself is nonsense. Perhaps the type of an
433 // expanded NTTP should be a pack expansion type?
434 return TemplateDeductionResult::Success;
436 // Get the type of the parameter for deduction. If it's a (dependent) array
437 // or function type, we will not have decayed it yet, so do that now.
438 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
439 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
440 ParamType = Expansion->getPattern();
442 // FIXME: It's not clear how deduction of a parameter of reference
443 // type from an argument (of non-reference type) should be performed.
444 // For now, we just make the argument have same reference type as the
445 // parameter.
446 if (ParamType->isReferenceType() && !ValueType->isReferenceType()) {
447 if (ParamType->isRValueReferenceType())
448 ValueType = S.Context.getRValueReferenceType(ValueType);
449 else
450 ValueType = S.Context.getLValueReferenceType(ValueType);
453 return DeduceTemplateArgumentsByTypeMatch(
454 S, TemplateParams, ParamType, ValueType, Info, Deduced,
455 TDF_SkipNonDependent | TDF_IgnoreQualifiers,
456 PartialOrdering ? PartialOrderingKind::NonCall
457 : PartialOrderingKind::None,
458 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound(), HasDeducedAnyParam);
461 /// Deduce the value of the given non-type template parameter
462 /// from the given integral constant.
463 static TemplateDeductionResult DeduceNonTypeTemplateArgument(
464 Sema &S, TemplateParameterList *TemplateParams,
465 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
466 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
467 bool PartialOrdering, SmallVectorImpl<DeducedTemplateArgument> &Deduced,
468 bool *HasDeducedAnyParam) {
469 return DeduceNonTypeTemplateArgument(
470 S, TemplateParams, NTTP,
471 DeducedTemplateArgument(S.Context, Value, ValueType,
472 DeducedFromArrayBound),
473 ValueType, Info, PartialOrdering, Deduced, HasDeducedAnyParam);
476 /// Deduce the value of the given non-type template parameter
477 /// from the given null pointer template argument type.
478 static TemplateDeductionResult
479 DeduceNullPtrTemplateArgument(Sema &S, TemplateParameterList *TemplateParams,
480 const NonTypeTemplateParmDecl *NTTP,
481 QualType NullPtrType, TemplateDeductionInfo &Info,
482 bool PartialOrdering,
483 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
484 bool *HasDeducedAnyParam) {
485 Expr *Value = S.ImpCastExprToType(
486 new (S.Context) CXXNullPtrLiteralExpr(S.Context.NullPtrTy,
487 NTTP->getLocation()),
488 NullPtrType,
489 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
490 : CK_NullToPointer)
491 .get();
492 return DeduceNonTypeTemplateArgument(
493 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
494 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
497 /// Deduce the value of the given non-type template parameter
498 /// from the given type- or value-dependent expression.
500 /// \returns true if deduction succeeded, false otherwise.
501 static TemplateDeductionResult
502 DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams,
503 const NonTypeTemplateParmDecl *NTTP, Expr *Value,
504 TemplateDeductionInfo &Info, bool PartialOrdering,
505 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
506 bool *HasDeducedAnyParam) {
507 return DeduceNonTypeTemplateArgument(
508 S, TemplateParams, NTTP, DeducedTemplateArgument(Value), Value->getType(),
509 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
512 /// Deduce the value of the given non-type template parameter
513 /// from the given declaration.
515 /// \returns true if deduction succeeded, false otherwise.
516 static TemplateDeductionResult
517 DeduceNonTypeTemplateArgument(Sema &S, TemplateParameterList *TemplateParams,
518 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D,
519 QualType T, TemplateDeductionInfo &Info,
520 bool PartialOrdering,
521 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
522 bool *HasDeducedAnyParam) {
523 TemplateArgument New(D, T);
524 return DeduceNonTypeTemplateArgument(
525 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info,
526 PartialOrdering, Deduced, HasDeducedAnyParam);
529 static TemplateDeductionResult DeduceTemplateArguments(
530 Sema &S, TemplateParameterList *TemplateParams, TemplateName Param,
531 TemplateName Arg, TemplateDeductionInfo &Info,
532 ArrayRef<TemplateArgument> DefaultArguments, bool PartialOrdering,
533 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
534 bool *HasDeducedAnyParam) {
535 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
536 if (!ParamDecl) {
537 // The parameter type is dependent and is not a template template parameter,
538 // so there is nothing that we can deduce.
539 return TemplateDeductionResult::Success;
542 if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
543 // If we're not deducing at this depth, there's nothing to deduce.
544 if (TempParam->getDepth() != Info.getDeducedDepth())
545 return TemplateDeductionResult::Success;
547 ArrayRef<NamedDecl *> Params =
548 ParamDecl->getTemplateParameters()->asArray();
549 unsigned StartPos = 0;
550 for (unsigned I = 0, E = std::min(Params.size(), DefaultArguments.size());
551 I < E; ++I) {
552 if (Params[I]->isParameterPack()) {
553 StartPos = DefaultArguments.size();
554 break;
556 StartPos = I + 1;
559 // Provisional resolution for CWG2398: If Arg names a template
560 // specialization, then we deduce a synthesized template name
561 // based on A, but using the TS's extra arguments, relative to P, as
562 // defaults.
563 DeducedTemplateArgument NewDeduced =
564 PartialOrdering
565 ? TemplateArgument(S.Context.getDeducedTemplateName(
566 Arg, {StartPos, DefaultArguments.drop_front(StartPos)}))
567 : Arg;
569 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
570 S.Context, Deduced[TempParam->getIndex()], NewDeduced);
571 if (Result.isNull()) {
572 Info.Param = TempParam;
573 Info.FirstArg = Deduced[TempParam->getIndex()];
574 Info.SecondArg = NewDeduced;
575 return TemplateDeductionResult::Inconsistent;
578 Deduced[TempParam->getIndex()] = Result;
579 if (HasDeducedAnyParam)
580 *HasDeducedAnyParam = true;
581 return TemplateDeductionResult::Success;
584 // Verify that the two template names are equivalent.
585 if (S.Context.hasSameTemplateName(
586 Param, Arg, /*IgnoreDeduced=*/DefaultArguments.size() != 0))
587 return TemplateDeductionResult::Success;
589 // Mismatch of non-dependent template parameter to argument.
590 Info.FirstArg = TemplateArgument(Param);
591 Info.SecondArg = TemplateArgument(Arg);
592 return TemplateDeductionResult::NonDeducedMismatch;
595 /// Deduce the template arguments by comparing the template parameter
596 /// type (which is a template-id) with the template argument type.
598 /// \param S the Sema
600 /// \param TemplateParams the template parameters that we are deducing
602 /// \param P the parameter type
604 /// \param A the argument type
606 /// \param Info information about the template argument deduction itself
608 /// \param Deduced the deduced template arguments
610 /// \returns the result of template argument deduction so far. Note that a
611 /// "success" result means that template argument deduction has not yet failed,
612 /// but it may still fail, later, for other reasons.
614 static const TemplateSpecializationType *getLastTemplateSpecType(QualType QT) {
615 for (const Type *T = QT.getTypePtr(); /**/; /**/) {
616 const TemplateSpecializationType *TST =
617 T->getAs<TemplateSpecializationType>();
618 assert(TST && "Expected a TemplateSpecializationType");
619 if (!TST->isSugared())
620 return TST;
621 T = TST->desugar().getTypePtr();
625 static TemplateDeductionResult
626 DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams,
627 const QualType P, QualType A,
628 TemplateDeductionInfo &Info, bool PartialOrdering,
629 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
630 bool *HasDeducedAnyParam) {
631 QualType UP = P;
632 if (const auto *IP = P->getAs<InjectedClassNameType>())
633 UP = IP->getInjectedSpecializationType();
635 assert(isa<TemplateSpecializationType>(UP.getCanonicalType()));
636 const TemplateSpecializationType *TP = ::getLastTemplateSpecType(UP);
637 TemplateName TNP = TP->getTemplateName();
639 // If the parameter is an alias template, there is nothing to deduce.
640 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
641 return TemplateDeductionResult::Success;
643 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
644 // arguments.
645 ArrayRef<TemplateArgument> PResolved =
646 TP->getCanonicalTypeInternal()
647 ->castAs<TemplateSpecializationType>()
648 ->template_arguments();
650 QualType UA = A;
651 std::optional<NestedNameSpecifier *> NNS;
652 // Treat an injected-class-name as its underlying template-id.
653 if (const auto *Elaborated = A->getAs<ElaboratedType>()) {
654 NNS = Elaborated->getQualifier();
655 } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) {
656 UA = Injected->getInjectedSpecializationType();
657 NNS = nullptr;
660 // Check whether the template argument is a dependent template-id.
661 if (isa<TemplateSpecializationType>(UA.getCanonicalType())) {
662 const TemplateSpecializationType *SA = ::getLastTemplateSpecType(UA);
663 TemplateName TNA = SA->getTemplateName();
665 // If the argument is an alias template, there is nothing to deduce.
666 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
667 return TemplateDeductionResult::Success;
669 // FIXME: To preserve sugar, the TST needs to carry sugared resolved
670 // arguments.
671 ArrayRef<TemplateArgument> AResolved =
672 SA->getCanonicalTypeInternal()
673 ->castAs<TemplateSpecializationType>()
674 ->template_arguments();
676 // Perform template argument deduction for the template name.
677 if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
678 /*DefaultArguments=*/AResolved,
679 PartialOrdering, Deduced,
680 HasDeducedAnyParam);
681 Result != TemplateDeductionResult::Success)
682 return Result;
684 // Perform template argument deduction on each template
685 // argument. Ignore any missing/extra arguments, since they could be
686 // filled in by default arguments.
687 return DeduceTemplateArguments(
688 S, TemplateParams, PResolved, AResolved, Info, Deduced,
689 /*NumberOfArgumentsMustMatch=*/false, PartialOrdering,
690 PackFold::ParameterToArgument, HasDeducedAnyParam);
693 // If the argument type is a class template specialization, we
694 // perform template argument deduction using its template
695 // arguments.
696 const auto *RA = UA->getAs<RecordType>();
697 const auto *SA =
698 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
699 if (!SA) {
700 Info.FirstArg = TemplateArgument(P);
701 Info.SecondArg = TemplateArgument(A);
702 return TemplateDeductionResult::NonDeducedMismatch;
705 TemplateName TNA = TemplateName(SA->getSpecializedTemplate());
706 if (NNS)
707 TNA = S.Context.getQualifiedTemplateName(
708 *NNS, false, TemplateName(SA->getSpecializedTemplate()));
710 // Perform template argument deduction for the template name.
711 if (auto Result = DeduceTemplateArguments(
712 S, TemplateParams, TNP, TNA, Info,
713 /*DefaultArguments=*/SA->getTemplateArgs().asArray(), PartialOrdering,
714 Deduced, HasDeducedAnyParam);
715 Result != TemplateDeductionResult::Success)
716 return Result;
718 // Perform template argument deduction for the template arguments.
719 return DeduceTemplateArguments(S, TemplateParams, PResolved,
720 SA->getTemplateArgs().asArray(), Info, Deduced,
721 /*NumberOfArgumentsMustMatch=*/true,
722 PartialOrdering, PackFold::ParameterToArgument,
723 HasDeducedAnyParam);
726 static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T) {
727 assert(T->isCanonicalUnqualified());
729 switch (T->getTypeClass()) {
730 case Type::TypeOfExpr:
731 case Type::TypeOf:
732 case Type::DependentName:
733 case Type::Decltype:
734 case Type::PackIndexing:
735 case Type::UnresolvedUsing:
736 case Type::TemplateTypeParm:
737 case Type::Auto:
738 return true;
740 case Type::ConstantArray:
741 case Type::IncompleteArray:
742 case Type::VariableArray:
743 case Type::DependentSizedArray:
744 return IsPossiblyOpaquelyQualifiedTypeInternal(
745 cast<ArrayType>(T)->getElementType().getTypePtr());
747 default:
748 return false;
752 /// Determines whether the given type is an opaque type that
753 /// might be more qualified when instantiated.
754 static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
755 return IsPossiblyOpaquelyQualifiedTypeInternal(
756 T->getCanonicalTypeInternal().getTypePtr());
759 /// Helper function to build a TemplateParameter when we don't
760 /// know its type statically.
761 static TemplateParameter makeTemplateParameter(Decl *D) {
762 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
763 return TemplateParameter(TTP);
764 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
765 return TemplateParameter(NTTP);
767 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
770 /// A pack that we're currently deducing.
771 struct clang::DeducedPack {
772 // The index of the pack.
773 unsigned Index;
775 // The old value of the pack before we started deducing it.
776 DeducedTemplateArgument Saved;
778 // A deferred value of this pack from an inner deduction, that couldn't be
779 // deduced because this deduction hadn't happened yet.
780 DeducedTemplateArgument DeferredDeduction;
782 // The new value of the pack.
783 SmallVector<DeducedTemplateArgument, 4> New;
785 // The outer deduction for this pack, if any.
786 DeducedPack *Outer = nullptr;
788 DeducedPack(unsigned Index) : Index(Index) {}
791 namespace {
793 /// A scope in which we're performing pack deduction.
794 class PackDeductionScope {
795 public:
796 /// Prepare to deduce the packs named within Pattern.
797 /// \param FinishingDeduction Don't attempt to deduce the pack. Useful when
798 /// just checking a previous deduction of the pack.
799 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
800 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
801 TemplateDeductionInfo &Info, TemplateArgument Pattern,
802 bool DeducePackIfNotAlreadyDeduced = false,
803 bool FinishingDeduction = false)
804 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
805 DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced),
806 FinishingDeduction(FinishingDeduction) {
807 unsigned NumNamedPacks = addPacks(Pattern);
808 finishConstruction(NumNamedPacks);
811 /// Prepare to directly deduce arguments of the parameter with index \p Index.
812 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
813 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
814 TemplateDeductionInfo &Info, unsigned Index)
815 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
816 addPack(Index);
817 finishConstruction(1);
820 private:
821 void addPack(unsigned Index) {
822 // Save the deduced template argument for the parameter pack expanded
823 // by this pack expansion, then clear out the deduction.
824 DeducedFromEarlierParameter = !Deduced[Index].isNull();
825 DeducedPack Pack(Index);
826 if (!FinishingDeduction) {
827 Pack.Saved = Deduced[Index];
828 Deduced[Index] = TemplateArgument();
831 // FIXME: What if we encounter multiple packs with different numbers of
832 // pre-expanded expansions? (This should already have been diagnosed
833 // during substitution.)
834 if (std::optional<unsigned> ExpandedPackExpansions =
835 getExpandedPackSize(TemplateParams->getParam(Index)))
836 FixedNumExpansions = ExpandedPackExpansions;
838 Packs.push_back(Pack);
841 unsigned addPacks(TemplateArgument Pattern) {
842 // Compute the set of template parameter indices that correspond to
843 // parameter packs expanded by the pack expansion.
844 llvm::SmallBitVector SawIndices(TemplateParams->size());
845 llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
847 auto AddPack = [&](unsigned Index) {
848 if (SawIndices[Index])
849 return;
850 SawIndices[Index] = true;
851 addPack(Index);
853 // Deducing a parameter pack that is a pack expansion also constrains the
854 // packs appearing in that parameter to have the same deduced arity. Also,
855 // in C++17 onwards, deducing a non-type template parameter deduces its
856 // type, so we need to collect the pending deduced values for those packs.
857 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
858 TemplateParams->getParam(Index))) {
859 if (!NTTP->isExpandedParameterPack())
860 // FIXME: CWG2982 suggests a type-constraint forms a non-deduced
861 // context, however it is not yet resolved.
862 if (auto *Expansion = dyn_cast<PackExpansionType>(
863 S.Context.getUnconstrainedType(NTTP->getType())))
864 ExtraDeductions.push_back(Expansion->getPattern());
866 // FIXME: Also collect the unexpanded packs in any type and template
867 // parameter packs that are pack expansions.
870 auto Collect = [&](TemplateArgument Pattern) {
871 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
872 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
873 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
874 unsigned Depth, Index;
875 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
876 if (Depth == Info.getDeducedDepth())
877 AddPack(Index);
881 // Look for unexpanded packs in the pattern.
882 Collect(Pattern);
883 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
885 unsigned NumNamedPacks = Packs.size();
887 // Also look for unexpanded packs that are indirectly deduced by deducing
888 // the sizes of the packs in this pattern.
889 while (!ExtraDeductions.empty())
890 Collect(ExtraDeductions.pop_back_val());
892 return NumNamedPacks;
895 void finishConstruction(unsigned NumNamedPacks) {
896 // Dig out the partially-substituted pack, if there is one.
897 const TemplateArgument *PartialPackArgs = nullptr;
898 unsigned NumPartialPackArgs = 0;
899 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
900 if (auto *Scope = S.CurrentInstantiationScope)
901 if (auto *Partial = Scope->getPartiallySubstitutedPack(
902 &PartialPackArgs, &NumPartialPackArgs))
903 PartialPackDepthIndex = getDepthAndIndex(Partial);
905 // This pack expansion will have been partially or fully expanded if
906 // it only names explicitly-specified parameter packs (including the
907 // partially-substituted one, if any).
908 bool IsExpanded = true;
909 for (unsigned I = 0; I != NumNamedPacks; ++I) {
910 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
911 IsExpanded = false;
912 IsPartiallyExpanded = false;
913 break;
915 if (PartialPackDepthIndex ==
916 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
917 IsPartiallyExpanded = true;
921 // Skip over the pack elements that were expanded into separate arguments.
922 // If we partially expanded, this is the number of partial arguments.
923 // FIXME: `&& FixedNumExpansions` is a workaround for UB described in
924 // https://github.com/llvm/llvm-project/issues/100095
925 if (IsPartiallyExpanded)
926 PackElements += NumPartialPackArgs;
927 else if (IsExpanded && FixedNumExpansions)
928 PackElements += *FixedNumExpansions;
930 for (auto &Pack : Packs) {
931 if (Info.PendingDeducedPacks.size() > Pack.Index)
932 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
933 else
934 Info.PendingDeducedPacks.resize(Pack.Index + 1);
935 Info.PendingDeducedPacks[Pack.Index] = &Pack;
937 if (PartialPackDepthIndex ==
938 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
939 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
940 // We pre-populate the deduced value of the partially-substituted
941 // pack with the specified value. This is not entirely correct: the
942 // value is supposed to have been substituted, not deduced, but the
943 // cases where this is observable require an exact type match anyway.
945 // FIXME: If we could represent a "depth i, index j, pack elem k"
946 // parameter, we could substitute the partially-substituted pack
947 // everywhere and avoid this.
948 if (!FinishingDeduction && !IsPartiallyExpanded)
949 Deduced[Pack.Index] = Pack.New[PackElements];
954 public:
955 ~PackDeductionScope() {
956 for (auto &Pack : Packs)
957 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
960 // Return the size of the saved packs if all of them has the same size.
961 std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
962 unsigned PackSize = Packs[0].Saved.pack_size();
964 if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
965 return P.Saved.pack_size() == PackSize;
967 return PackSize;
968 return {};
971 /// Determine whether this pack has already been deduced from a previous
972 /// argument.
973 bool isDeducedFromEarlierParameter() const {
974 return DeducedFromEarlierParameter;
977 /// Determine whether this pack has already been partially expanded into a
978 /// sequence of (prior) function parameters / template arguments.
979 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
981 /// Determine whether this pack expansion scope has a known, fixed arity.
982 /// This happens if it involves a pack from an outer template that has
983 /// (notionally) already been expanded.
984 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
986 /// Determine whether the next element of the argument is still part of this
987 /// pack. This is the case unless the pack is already expanded to a fixed
988 /// length.
989 bool hasNextElement() {
990 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
993 /// Move to deducing the next element in each pack that is being deduced.
994 void nextPackElement() {
995 // Capture the deduced template arguments for each parameter pack expanded
996 // by this pack expansion, add them to the list of arguments we've deduced
997 // for that pack, then clear out the deduced argument.
998 if (!FinishingDeduction) {
999 for (auto &Pack : Packs) {
1000 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
1001 if (!Pack.New.empty() || !DeducedArg.isNull()) {
1002 while (Pack.New.size() < PackElements)
1003 Pack.New.push_back(DeducedTemplateArgument());
1004 if (Pack.New.size() == PackElements)
1005 Pack.New.push_back(DeducedArg);
1006 else
1007 Pack.New[PackElements] = DeducedArg;
1008 DeducedArg = Pack.New.size() > PackElements + 1
1009 ? Pack.New[PackElements + 1]
1010 : DeducedTemplateArgument();
1014 ++PackElements;
1017 /// Finish template argument deduction for a set of argument packs,
1018 /// producing the argument packs and checking for consistency with prior
1019 /// deductions.
1020 TemplateDeductionResult finish() {
1021 if (FinishingDeduction)
1022 return TemplateDeductionResult::Success;
1023 // Build argument packs for each of the parameter packs expanded by this
1024 // pack expansion.
1025 for (auto &Pack : Packs) {
1026 // Put back the old value for this pack.
1027 if (!FinishingDeduction)
1028 Deduced[Pack.Index] = Pack.Saved;
1030 // Always make sure the size of this pack is correct, even if we didn't
1031 // deduce any values for it.
1033 // FIXME: This isn't required by the normative wording, but substitution
1034 // and post-substitution checking will always fail if the arity of any
1035 // pack is not equal to the number of elements we processed. (Either that
1036 // or something else has gone *very* wrong.) We're permitted to skip any
1037 // hard errors from those follow-on steps by the intent (but not the
1038 // wording) of C++ [temp.inst]p8:
1040 // If the function selected by overload resolution can be determined
1041 // without instantiating a class template definition, it is unspecified
1042 // whether that instantiation actually takes place
1043 Pack.New.resize(PackElements);
1045 // Build or find a new value for this pack.
1046 DeducedTemplateArgument NewPack;
1047 if (Pack.New.empty()) {
1048 // If we deduced an empty argument pack, create it now.
1049 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
1050 } else {
1051 TemplateArgument *ArgumentPack =
1052 new (S.Context) TemplateArgument[Pack.New.size()];
1053 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
1054 NewPack = DeducedTemplateArgument(
1055 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
1056 // FIXME: This is wrong, it's possible that some pack elements are
1057 // deduced from an array bound and others are not:
1058 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
1059 // g({1, 2, 3}, {{}, {}});
1060 // ... should deduce T = {int, size_t (from array bound)}.
1061 Pack.New[0].wasDeducedFromArrayBound());
1064 // Pick where we're going to put the merged pack.
1065 DeducedTemplateArgument *Loc;
1066 if (Pack.Outer) {
1067 if (Pack.Outer->DeferredDeduction.isNull()) {
1068 // Defer checking this pack until we have a complete pack to compare
1069 // it against.
1070 Pack.Outer->DeferredDeduction = NewPack;
1071 continue;
1073 Loc = &Pack.Outer->DeferredDeduction;
1074 } else {
1075 Loc = &Deduced[Pack.Index];
1078 // Check the new pack matches any previous value.
1079 DeducedTemplateArgument OldPack = *Loc;
1080 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
1081 S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
1083 Info.AggregateDeductionCandidateHasMismatchedArity =
1084 OldPack.getKind() == TemplateArgument::Pack &&
1085 NewPack.getKind() == TemplateArgument::Pack &&
1086 OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
1088 // If we deferred a deduction of this pack, check that one now too.
1089 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
1090 OldPack = Result;
1091 NewPack = Pack.DeferredDeduction;
1092 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
1095 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
1096 if (Result.isNull()) {
1097 Info.Param = makeTemplateParameter(Param);
1098 Info.FirstArg = OldPack;
1099 Info.SecondArg = NewPack;
1100 return TemplateDeductionResult::Inconsistent;
1103 // If we have a pre-expanded pack and we didn't deduce enough elements
1104 // for it, fail deduction.
1105 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
1106 if (*Expansions != PackElements) {
1107 Info.Param = makeTemplateParameter(Param);
1108 Info.FirstArg = Result;
1109 return TemplateDeductionResult::IncompletePack;
1113 *Loc = Result;
1116 return TemplateDeductionResult::Success;
1119 private:
1120 Sema &S;
1121 TemplateParameterList *TemplateParams;
1122 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
1123 TemplateDeductionInfo &Info;
1124 unsigned PackElements = 0;
1125 bool IsPartiallyExpanded = false;
1126 bool DeducePackIfNotAlreadyDeduced = false;
1127 bool DeducedFromEarlierParameter = false;
1128 bool FinishingDeduction = false;
1129 /// The number of expansions, if we have a fully-expanded pack in this scope.
1130 std::optional<unsigned> FixedNumExpansions;
1132 SmallVector<DeducedPack, 2> Packs;
1135 } // namespace
1137 template <class T>
1138 static TemplateDeductionResult DeduceForEachType(
1139 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1140 ArrayRef<QualType> Args, TemplateDeductionInfo &Info,
1141 SmallVectorImpl<DeducedTemplateArgument> &Deduced, PartialOrderingKind POK,
1142 bool FinishingDeduction, T &&DeductFunc) {
1143 // C++0x [temp.deduct.type]p10:
1144 // Similarly, if P has a form that contains (T), then each parameter type
1145 // Pi of the respective parameter-type- list of P is compared with the
1146 // corresponding parameter type Ai of the corresponding parameter-type-list
1147 // of A. [...]
1148 unsigned ArgIdx = 0, ParamIdx = 0;
1149 for (; ParamIdx != Params.size(); ++ParamIdx) {
1150 // Check argument types.
1151 const PackExpansionType *Expansion
1152 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1153 if (!Expansion) {
1154 // Simple case: compare the parameter and argument types at this point.
1156 // Make sure we have an argument.
1157 if (ArgIdx >= Args.size())
1158 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1160 if (isa<PackExpansionType>(Args[ArgIdx])) {
1161 // C++0x [temp.deduct.type]p22:
1162 // If the original function parameter associated with A is a function
1163 // parameter pack and the function parameter associated with P is not
1164 // a function parameter pack, then template argument deduction fails.
1165 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1168 if (TemplateDeductionResult Result =
1169 DeductFunc(S, TemplateParams, ParamIdx, ArgIdx,
1170 Params[ParamIdx].getUnqualifiedType(),
1171 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, POK);
1172 Result != TemplateDeductionResult::Success)
1173 return Result;
1175 ++ArgIdx;
1176 continue;
1179 // C++0x [temp.deduct.type]p10:
1180 // If the parameter-declaration corresponding to Pi is a function
1181 // parameter pack, then the type of its declarator- id is compared with
1182 // each remaining parameter type in the parameter-type-list of A. Each
1183 // comparison deduces template arguments for subsequent positions in the
1184 // template parameter packs expanded by the function parameter pack.
1186 QualType Pattern = Expansion->getPattern();
1187 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern,
1188 /*DeducePackIfNotAlreadyDeduced=*/false,
1189 FinishingDeduction);
1191 // A pack scope with fixed arity is not really a pack any more, so is not
1192 // a non-deduced context.
1193 if (ParamIdx + 1 == Params.size() || PackScope.hasFixedArity()) {
1194 for (; ArgIdx < Args.size() && PackScope.hasNextElement(); ++ArgIdx) {
1195 // Deduce template arguments from the pattern.
1196 if (TemplateDeductionResult Result = DeductFunc(
1197 S, TemplateParams, ParamIdx, ArgIdx,
1198 Pattern.getUnqualifiedType(), Args[ArgIdx].getUnqualifiedType(),
1199 Info, Deduced, POK);
1200 Result != TemplateDeductionResult::Success)
1201 return Result;
1202 PackScope.nextPackElement();
1204 } else {
1205 // C++0x [temp.deduct.type]p5:
1206 // The non-deduced contexts are:
1207 // - A function parameter pack that does not occur at the end of the
1208 // parameter-declaration-clause.
1210 // FIXME: There is no wording to say what we should do in this case. We
1211 // choose to resolve this by applying the same rule that is applied for a
1212 // function call: that is, deduce all contained packs to their
1213 // explicitly-specified values (or to <> if there is no such value).
1215 // This is seemingly-arbitrarily different from the case of a template-id
1216 // with a non-trailing pack-expansion in its arguments, which renders the
1217 // entire template-argument-list a non-deduced context.
1219 // If the parameter type contains an explicitly-specified pack that we
1220 // could not expand, skip the number of parameters notionally created
1221 // by the expansion.
1222 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1223 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1224 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
1225 ++I, ++ArgIdx)
1226 PackScope.nextPackElement();
1230 // Build argument packs for each of the parameter packs expanded by this
1231 // pack expansion.
1232 if (auto Result = PackScope.finish();
1233 Result != TemplateDeductionResult::Success)
1234 return Result;
1237 // DR692, DR1395
1238 // C++0x [temp.deduct.type]p10:
1239 // If the parameter-declaration corresponding to P_i ...
1240 // During partial ordering, if Ai was originally a function parameter pack:
1241 // - if P does not contain a function parameter type corresponding to Ai then
1242 // Ai is ignored;
1243 if (POK == PartialOrderingKind::Call && ArgIdx + 1 == Args.size() &&
1244 isa<PackExpansionType>(Args[ArgIdx]))
1245 return TemplateDeductionResult::Success;
1247 // Make sure we don't have any extra arguments.
1248 if (ArgIdx < Args.size())
1249 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1251 return TemplateDeductionResult::Success;
1254 /// Deduce the template arguments by comparing the list of parameter
1255 /// types to the list of argument types, as in the parameter-type-lists of
1256 /// function types (C++ [temp.deduct.type]p10).
1258 /// \param S The semantic analysis object within which we are deducing
1260 /// \param TemplateParams The template parameters that we are deducing
1262 /// \param Params The list of parameter types
1264 /// \param Args The list of argument types
1266 /// \param Info information about the template argument deduction itself
1268 /// \param Deduced the deduced template arguments
1270 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1271 /// how template argument deduction is performed.
1273 /// \param PartialOrdering If true, we are performing template argument
1274 /// deduction for during partial ordering for a call
1275 /// (C++0x [temp.deduct.partial]).
1277 /// \param HasDeducedAnyParam If set, the object pointed at will indicate
1278 /// whether any template parameter was deduced.
1280 /// \param HasDeducedParam If set, the bit vector will be used to represent
1281 /// which template parameters were deduced, in order.
1283 /// \returns the result of template argument deduction so far. Note that a
1284 /// "success" result means that template argument deduction has not yet failed,
1285 /// but it may still fail, later, for other reasons.
1286 static TemplateDeductionResult DeduceTemplateArguments(
1287 Sema &S, TemplateParameterList *TemplateParams, ArrayRef<QualType> Params,
1288 ArrayRef<QualType> Args, TemplateDeductionInfo &Info,
1289 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1290 PartialOrderingKind POK, bool *HasDeducedAnyParam,
1291 llvm::SmallBitVector *HasDeducedParam) {
1292 return ::DeduceForEachType(
1293 S, TemplateParams, Params, Args, Info, Deduced, POK,
1294 /*FinishingDeduction=*/false,
1295 [&](Sema &S, TemplateParameterList *TemplateParams, int ParamIdx,
1296 int ArgIdx, QualType P, QualType A, TemplateDeductionInfo &Info,
1297 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1298 PartialOrderingKind POK) {
1299 bool HasDeducedAnyParamCopy = false;
1300 TemplateDeductionResult TDR = DeduceTemplateArgumentsByTypeMatch(
1301 S, TemplateParams, P, A, Info, Deduced, TDF, POK,
1302 /*DeducedFromArrayBound=*/false, &HasDeducedAnyParamCopy);
1303 if (HasDeducedAnyParam && HasDeducedAnyParamCopy)
1304 *HasDeducedAnyParam = true;
1305 if (HasDeducedParam && HasDeducedAnyParamCopy)
1306 (*HasDeducedParam)[ParamIdx] = true;
1307 return TDR;
1311 /// Determine whether the parameter has qualifiers that the argument
1312 /// lacks. Put another way, determine whether there is no way to add
1313 /// a deduced set of qualifiers to the ParamType that would result in
1314 /// its qualifiers matching those of the ArgType.
1315 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1316 QualType ArgType) {
1317 Qualifiers ParamQs = ParamType.getQualifiers();
1318 Qualifiers ArgQs = ArgType.getQualifiers();
1320 if (ParamQs == ArgQs)
1321 return false;
1323 // Mismatched (but not missing) Objective-C GC attributes.
1324 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1325 ParamQs.hasObjCGCAttr())
1326 return true;
1328 // Mismatched (but not missing) address spaces.
1329 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1330 ParamQs.hasAddressSpace())
1331 return true;
1333 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1334 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1335 ParamQs.hasObjCLifetime())
1336 return true;
1338 // CVR qualifiers inconsistent or a superset.
1339 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1342 bool Sema::isSameOrCompatibleFunctionType(QualType P, QualType A) {
1343 const FunctionType *PF = P->getAs<FunctionType>(),
1344 *AF = A->getAs<FunctionType>();
1346 // Just compare if not functions.
1347 if (!PF || !AF)
1348 return Context.hasSameType(P, A);
1350 // Noreturn and noexcept adjustment.
1351 if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1352 P = AdjustedParam;
1354 // FIXME: Compatible calling conventions.
1355 return Context.hasSameFunctionTypeIgnoringExceptionSpec(P, A);
1358 /// Get the index of the first template parameter that was originally from the
1359 /// innermost template-parameter-list. This is 0 except when we concatenate
1360 /// the template parameter lists of a class template and a constructor template
1361 /// when forming an implicit deduction guide.
1362 static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
1363 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1364 if (!Guide || !Guide->isImplicit())
1365 return 0;
1366 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1369 /// Determine whether a type denotes a forwarding reference.
1370 static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1371 // C++1z [temp.deduct.call]p3:
1372 // A forwarding reference is an rvalue reference to a cv-unqualified
1373 // template parameter that does not represent a template parameter of a
1374 // class template.
1375 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1376 if (ParamRef->getPointeeType().getQualifiers())
1377 return false;
1378 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1379 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1381 return false;
1384 /// Attempt to deduce the template arguments by checking the base types
1385 /// according to (C++20 [temp.deduct.call] p4b3.
1387 /// \param S the semantic analysis object within which we are deducing.
1389 /// \param RD the top level record object we are deducing against.
1391 /// \param TemplateParams the template parameters that we are deducing.
1393 /// \param P the template specialization parameter type.
1395 /// \param Info information about the template argument deduction itself.
1397 /// \param Deduced the deduced template arguments.
1399 /// \returns the result of template argument deduction with the bases. "invalid"
1400 /// means no matches, "success" found a single item, and the
1401 /// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1402 static TemplateDeductionResult
1403 DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD,
1404 TemplateParameterList *TemplateParams, QualType P,
1405 TemplateDeductionInfo &Info, bool PartialOrdering,
1406 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1407 bool *HasDeducedAnyParam) {
1408 // C++14 [temp.deduct.call] p4b3:
1409 // If P is a class and P has the form simple-template-id, then the
1410 // transformed A can be a derived class of the deduced A. Likewise if
1411 // P is a pointer to a class of the form simple-template-id, the
1412 // transformed A can be a pointer to a derived class pointed to by the
1413 // deduced A. However, if there is a class C that is a (direct or
1414 // indirect) base class of D and derived (directly or indirectly) from a
1415 // class B and that would be a valid deduced A, the deduced A cannot be
1416 // B or pointer to B, respectively.
1418 // These alternatives are considered only if type deduction would
1419 // otherwise fail. If they yield more than one possible deduced A, the
1420 // type deduction fails.
1422 // Use a breadth-first search through the bases to collect the set of
1423 // successful matches. Visited contains the set of nodes we have already
1424 // visited, while ToVisit is our stack of records that we still need to
1425 // visit. Matches contains a list of matches that have yet to be
1426 // disqualified.
1427 llvm::SmallPtrSet<const CXXRecordDecl *, 8> Visited;
1428 SmallVector<QualType, 8> ToVisit;
1429 // We iterate over this later, so we have to use MapVector to ensure
1430 // determinism.
1431 struct MatchValue {
1432 SmallVector<DeducedTemplateArgument, 8> Deduced;
1433 bool HasDeducedAnyParam;
1435 llvm::MapVector<const CXXRecordDecl *, MatchValue> Matches;
1437 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1438 for (const auto &Base : RD->bases()) {
1439 QualType T = Base.getType();
1440 assert(T->isRecordType() && "Base class that isn't a record?");
1441 if (Visited.insert(T->getAsCXXRecordDecl()).second)
1442 ToVisit.push_back(T);
1446 // Set up the loop by adding all the bases.
1447 AddBases(RD);
1449 // Search each path of bases until we either run into a successful match
1450 // (where all bases of it are invalid), or we run out of bases.
1451 while (!ToVisit.empty()) {
1452 QualType NextT = ToVisit.pop_back_val();
1454 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1455 Deduced.end());
1456 TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info);
1457 bool HasDeducedAnyParamCopy = false;
1458 TemplateDeductionResult BaseResult = DeduceTemplateSpecArguments(
1459 S, TemplateParams, P, NextT, BaseInfo, PartialOrdering, DeducedCopy,
1460 &HasDeducedAnyParamCopy);
1462 // If this was a successful deduction, add it to the list of matches,
1463 // otherwise we need to continue searching its bases.
1464 const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
1465 if (BaseResult == TemplateDeductionResult::Success)
1466 Matches.insert({RD, {DeducedCopy, HasDeducedAnyParamCopy}});
1467 else
1468 AddBases(RD);
1471 // At this point, 'Matches' contains a list of seemingly valid bases, however
1472 // in the event that we have more than 1 match, it is possible that the base
1473 // of one of the matches might be disqualified for being a base of another
1474 // valid match. We can count on cyclical instantiations being invalid to
1475 // simplify the disqualifications. That is, if A & B are both matches, and B
1476 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1477 if (Matches.size() > 1) {
1478 Visited.clear();
1479 for (const auto &Match : Matches)
1480 AddBases(Match.first);
1482 // We can give up once we have a single item (or have run out of things to
1483 // search) since cyclical inheritance isn't valid.
1484 while (Matches.size() > 1 && !ToVisit.empty()) {
1485 const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
1486 Matches.erase(RD);
1488 // Always add all bases, since the inheritance tree can contain
1489 // disqualifications for multiple matches.
1490 AddBases(RD);
1494 if (Matches.empty())
1495 return TemplateDeductionResult::Invalid;
1496 if (Matches.size() > 1)
1497 return TemplateDeductionResult::MiscellaneousDeductionFailure;
1499 std::swap(Matches.front().second.Deduced, Deduced);
1500 if (bool HasDeducedAnyParamCopy = Matches.front().second.HasDeducedAnyParam;
1501 HasDeducedAnyParamCopy && HasDeducedAnyParam)
1502 *HasDeducedAnyParam = HasDeducedAnyParamCopy;
1503 return TemplateDeductionResult::Success;
1506 /// When propagating a partial ordering kind into a NonCall context,
1507 /// this is used to downgrade a 'Call' into a 'NonCall', so that
1508 /// the kind still reflects whether we are in a partial ordering context.
1509 static PartialOrderingKind
1510 degradeCallPartialOrderingKind(PartialOrderingKind POK) {
1511 return std::min(POK, PartialOrderingKind::NonCall);
1514 /// Deduce the template arguments by comparing the parameter type and
1515 /// the argument type (C++ [temp.deduct.type]).
1517 /// \param S the semantic analysis object within which we are deducing
1519 /// \param TemplateParams the template parameters that we are deducing
1521 /// \param P the parameter type
1523 /// \param A the argument type
1525 /// \param Info information about the template argument deduction itself
1527 /// \param Deduced the deduced template arguments
1529 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1530 /// how template argument deduction is performed.
1532 /// \param PartialOrdering Whether we're performing template argument deduction
1533 /// in the context of partial ordering (C++0x [temp.deduct.partial]).
1535 /// \returns the result of template argument deduction so far. Note that a
1536 /// "success" result means that template argument deduction has not yet failed,
1537 /// but it may still fail, later, for other reasons.
1538 static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
1539 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1540 TemplateDeductionInfo &Info,
1541 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1542 PartialOrderingKind POK, bool DeducedFromArrayBound,
1543 bool *HasDeducedAnyParam) {
1545 // If the argument type is a pack expansion, look at its pattern.
1546 // This isn't explicitly called out
1547 if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1548 A = AExp->getPattern();
1549 assert(!isa<PackExpansionType>(A.getCanonicalType()));
1551 if (POK == PartialOrderingKind::Call) {
1552 // C++11 [temp.deduct.partial]p5:
1553 // Before the partial ordering is done, certain transformations are
1554 // performed on the types used for partial ordering:
1555 // - If P is a reference type, P is replaced by the type referred to.
1556 const ReferenceType *PRef = P->getAs<ReferenceType>();
1557 if (PRef)
1558 P = PRef->getPointeeType();
1560 // - If A is a reference type, A is replaced by the type referred to.
1561 const ReferenceType *ARef = A->getAs<ReferenceType>();
1562 if (ARef)
1563 A = A->getPointeeType();
1565 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1566 // C++11 [temp.deduct.partial]p9:
1567 // If, for a given type, deduction succeeds in both directions (i.e.,
1568 // the types are identical after the transformations above) and both
1569 // P and A were reference types [...]:
1570 // - if [one type] was an lvalue reference and [the other type] was
1571 // not, [the other type] is not considered to be at least as
1572 // specialized as [the first type]
1573 // - if [one type] is more cv-qualified than [the other type],
1574 // [the other type] is not considered to be at least as specialized
1575 // as [the first type]
1576 // Objective-C ARC adds:
1577 // - [one type] has non-trivial lifetime, [the other type] has
1578 // __unsafe_unretained lifetime, and the types are otherwise
1579 // identical
1581 // A is "considered to be at least as specialized" as P iff deduction
1582 // succeeds, so we model this as a deduction failure. Note that
1583 // [the first type] is P and [the other type] is A here; the standard
1584 // gets this backwards.
1585 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1586 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1587 PQuals.isStrictSupersetOf(AQuals) ||
1588 (PQuals.hasNonTrivialObjCLifetime() &&
1589 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1590 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1591 Info.FirstArg = TemplateArgument(P);
1592 Info.SecondArg = TemplateArgument(A);
1593 return TemplateDeductionResult::NonDeducedMismatch;
1596 Qualifiers DiscardedQuals;
1597 // C++11 [temp.deduct.partial]p7:
1598 // Remove any top-level cv-qualifiers:
1599 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1600 // version of P.
1601 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1602 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1603 // version of A.
1604 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1605 } else {
1606 // C++0x [temp.deduct.call]p4 bullet 1:
1607 // - If the original P is a reference type, the deduced A (i.e., the type
1608 // referred to by the reference) can be more cv-qualified than the
1609 // transformed A.
1610 if (TDF & TDF_ParamWithReferenceType) {
1611 Qualifiers Quals;
1612 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1613 Quals.setCVRQualifiers(Quals.getCVRQualifiers() & A.getCVRQualifiers());
1614 P = S.Context.getQualifiedType(UnqualP, Quals);
1617 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
1618 // C++0x [temp.deduct.type]p10:
1619 // If P and A are function types that originated from deduction when
1620 // taking the address of a function template (14.8.2.2) or when deducing
1621 // template arguments from a function declaration (14.8.2.6) and Pi and
1622 // Ai are parameters of the top-level parameter-type-list of P and A,
1623 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1624 // is an lvalue reference, in
1625 // which case the type of Pi is changed to be the template parameter
1626 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1627 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1628 // deduced as X&. - end note ]
1629 TDF &= ~TDF_TopLevelParameterTypeList;
1630 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1631 A->isLValueReferenceType())
1632 P = P->getPointeeType();
1636 // C++ [temp.deduct.type]p9:
1637 // A template type argument T, a template template argument TT or a
1638 // template non-type argument i can be deduced if P and A have one of
1639 // the following forms:
1641 // T
1642 // cv-list T
1643 if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
1644 // Just skip any attempts to deduce from a placeholder type or a parameter
1645 // at a different depth.
1646 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1647 return TemplateDeductionResult::Success;
1649 unsigned Index = TTP->getIndex();
1651 // If the argument type is an array type, move the qualifiers up to the
1652 // top level, so they can be matched with the qualifiers on the parameter.
1653 if (A->isArrayType()) {
1654 Qualifiers Quals;
1655 A = S.Context.getUnqualifiedArrayType(A, Quals);
1656 if (Quals)
1657 A = S.Context.getQualifiedType(A, Quals);
1660 // The argument type can not be less qualified than the parameter
1661 // type.
1662 if (!(TDF & TDF_IgnoreQualifiers) &&
1663 hasInconsistentOrSupersetQualifiersOf(P, A)) {
1664 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1665 Info.FirstArg = TemplateArgument(P);
1666 Info.SecondArg = TemplateArgument(A);
1667 return TemplateDeductionResult::Underqualified;
1670 // Do not match a function type with a cv-qualified type.
1671 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1672 if (A->isFunctionType() && P.hasQualifiers())
1673 return TemplateDeductionResult::NonDeducedMismatch;
1675 assert(TTP->getDepth() == Info.getDeducedDepth() &&
1676 "saw template type parameter with wrong depth");
1677 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1678 "Unresolved overloaded function");
1679 QualType DeducedType = A;
1681 // Remove any qualifiers on the parameter from the deduced type.
1682 // We checked the qualifiers for consistency above.
1683 Qualifiers DeducedQs = DeducedType.getQualifiers();
1684 Qualifiers ParamQs = P.getQualifiers();
1685 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1686 if (ParamQs.hasObjCGCAttr())
1687 DeducedQs.removeObjCGCAttr();
1688 if (ParamQs.hasAddressSpace())
1689 DeducedQs.removeAddressSpace();
1690 if (ParamQs.hasObjCLifetime())
1691 DeducedQs.removeObjCLifetime();
1693 // Objective-C ARC:
1694 // If template deduction would produce a lifetime qualifier on a type
1695 // that is not a lifetime type, template argument deduction fails.
1696 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1697 !DeducedType->isDependentType()) {
1698 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1699 Info.FirstArg = TemplateArgument(P);
1700 Info.SecondArg = TemplateArgument(A);
1701 return TemplateDeductionResult::Underqualified;
1704 // Objective-C ARC:
1705 // If template deduction would produce an argument type with lifetime type
1706 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1707 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1708 !DeducedQs.hasObjCLifetime())
1709 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1711 DeducedType =
1712 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1714 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1715 DeducedTemplateArgument Result =
1716 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1717 if (Result.isNull()) {
1718 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1719 Info.FirstArg = Deduced[Index];
1720 Info.SecondArg = NewDeduced;
1721 return TemplateDeductionResult::Inconsistent;
1724 Deduced[Index] = Result;
1725 if (HasDeducedAnyParam)
1726 *HasDeducedAnyParam = true;
1727 return TemplateDeductionResult::Success;
1730 // Set up the template argument deduction information for a failure.
1731 Info.FirstArg = TemplateArgument(P);
1732 Info.SecondArg = TemplateArgument(A);
1734 // If the parameter is an already-substituted template parameter
1735 // pack, do nothing: we don't know which of its arguments to look
1736 // at, so we have to wait until all of the parameter packs in this
1737 // expansion have arguments.
1738 if (P->getAs<SubstTemplateTypeParmPackType>())
1739 return TemplateDeductionResult::Success;
1741 // Check the cv-qualifiers on the parameter and argument types.
1742 if (!(TDF & TDF_IgnoreQualifiers)) {
1743 if (TDF & TDF_ParamWithReferenceType) {
1744 if (hasInconsistentOrSupersetQualifiersOf(P, A))
1745 return TemplateDeductionResult::NonDeducedMismatch;
1746 } else if (TDF & TDF_ArgWithReferenceType) {
1747 // C++ [temp.deduct.conv]p4:
1748 // If the original A is a reference type, A can be more cv-qualified
1749 // than the deduced A
1750 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers(),
1751 S.getASTContext()))
1752 return TemplateDeductionResult::NonDeducedMismatch;
1754 // Strip out all extra qualifiers from the argument to figure out the
1755 // type we're converting to, prior to the qualification conversion.
1756 Qualifiers Quals;
1757 A = S.Context.getUnqualifiedArrayType(A, Quals);
1758 A = S.Context.getQualifiedType(A, P.getQualifiers());
1759 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1760 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1761 return TemplateDeductionResult::NonDeducedMismatch;
1765 // If the parameter type is not dependent, there is nothing to deduce.
1766 if (!P->isDependentType()) {
1767 if (TDF & TDF_SkipNonDependent)
1768 return TemplateDeductionResult::Success;
1769 if ((TDF & TDF_IgnoreQualifiers) ? S.Context.hasSameUnqualifiedType(P, A)
1770 : S.Context.hasSameType(P, A))
1771 return TemplateDeductionResult::Success;
1772 if (TDF & TDF_AllowCompatibleFunctionType &&
1773 S.isSameOrCompatibleFunctionType(P, A))
1774 return TemplateDeductionResult::Success;
1775 if (!(TDF & TDF_IgnoreQualifiers))
1776 return TemplateDeductionResult::NonDeducedMismatch;
1777 // Otherwise, when ignoring qualifiers, the types not having the same
1778 // unqualified type does not mean they do not match, so in this case we
1779 // must keep going and analyze with a non-dependent parameter type.
1782 switch (P.getCanonicalType()->getTypeClass()) {
1783 // Non-canonical types cannot appear here.
1784 #define NON_CANONICAL_TYPE(Class, Base) \
1785 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1786 #define TYPE(Class, Base)
1787 #include "clang/AST/TypeNodes.inc"
1789 case Type::TemplateTypeParm:
1790 case Type::SubstTemplateTypeParmPack:
1791 llvm_unreachable("Type nodes handled above");
1793 case Type::Auto:
1794 // C++23 [temp.deduct.funcaddr]/3:
1795 // A placeholder type in the return type of a function template is a
1796 // non-deduced context.
1797 // There's no corresponding wording for [temp.deduct.decl], but we treat
1798 // it the same to match other compilers.
1799 if (P->isDependentType())
1800 return TemplateDeductionResult::Success;
1801 [[fallthrough]];
1802 case Type::Builtin:
1803 case Type::VariableArray:
1804 case Type::Vector:
1805 case Type::FunctionNoProto:
1806 case Type::Record:
1807 case Type::Enum:
1808 case Type::ObjCObject:
1809 case Type::ObjCInterface:
1810 case Type::ObjCObjectPointer:
1811 case Type::BitInt:
1812 return (TDF & TDF_SkipNonDependent) ||
1813 ((TDF & TDF_IgnoreQualifiers)
1814 ? S.Context.hasSameUnqualifiedType(P, A)
1815 : S.Context.hasSameType(P, A))
1816 ? TemplateDeductionResult::Success
1817 : TemplateDeductionResult::NonDeducedMismatch;
1819 // _Complex T [placeholder extension]
1820 case Type::Complex: {
1821 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1822 if (!CA)
1823 return TemplateDeductionResult::NonDeducedMismatch;
1824 return DeduceTemplateArgumentsByTypeMatch(
1825 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1826 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1827 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1830 // _Atomic T [extension]
1831 case Type::Atomic: {
1832 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1833 if (!AA)
1834 return TemplateDeductionResult::NonDeducedMismatch;
1835 return DeduceTemplateArgumentsByTypeMatch(
1836 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1837 Deduced, TDF, degradeCallPartialOrderingKind(POK),
1838 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1841 // T *
1842 case Type::Pointer: {
1843 QualType PointeeType;
1844 if (const auto *PA = A->getAs<PointerType>()) {
1845 PointeeType = PA->getPointeeType();
1846 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1847 PointeeType = PA->getPointeeType();
1848 } else {
1849 return TemplateDeductionResult::NonDeducedMismatch;
1851 return DeduceTemplateArgumentsByTypeMatch(
1852 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1853 PointeeType, Info, Deduced,
1854 TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass),
1855 degradeCallPartialOrderingKind(POK),
1856 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1859 // T &
1860 case Type::LValueReference: {
1861 const auto *RP = P->castAs<LValueReferenceType>(),
1862 *RA = A->getAs<LValueReferenceType>();
1863 if (!RA)
1864 return TemplateDeductionResult::NonDeducedMismatch;
1866 return DeduceTemplateArgumentsByTypeMatch(
1867 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1868 Deduced, 0, degradeCallPartialOrderingKind(POK),
1869 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1872 // T && [C++0x]
1873 case Type::RValueReference: {
1874 const auto *RP = P->castAs<RValueReferenceType>(),
1875 *RA = A->getAs<RValueReferenceType>();
1876 if (!RA)
1877 return TemplateDeductionResult::NonDeducedMismatch;
1879 return DeduceTemplateArgumentsByTypeMatch(
1880 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1881 Deduced, 0, degradeCallPartialOrderingKind(POK),
1882 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1885 // T [] (implied, but not stated explicitly)
1886 case Type::IncompleteArray: {
1887 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1888 if (!IAA)
1889 return TemplateDeductionResult::NonDeducedMismatch;
1891 const auto *IAP = S.Context.getAsIncompleteArrayType(P);
1892 assert(IAP && "Template parameter not of incomplete array type");
1894 return DeduceTemplateArgumentsByTypeMatch(
1895 S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
1896 Deduced, TDF & TDF_IgnoreQualifiers,
1897 degradeCallPartialOrderingKind(POK),
1898 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1901 // T [integer-constant]
1902 case Type::ConstantArray: {
1903 const auto *CAA = S.Context.getAsConstantArrayType(A),
1904 *CAP = S.Context.getAsConstantArrayType(P);
1905 assert(CAP);
1906 if (!CAA || CAA->getSize() != CAP->getSize())
1907 return TemplateDeductionResult::NonDeducedMismatch;
1909 return DeduceTemplateArgumentsByTypeMatch(
1910 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1911 Deduced, TDF & TDF_IgnoreQualifiers,
1912 degradeCallPartialOrderingKind(POK),
1913 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1916 // type [i]
1917 case Type::DependentSizedArray: {
1918 const auto *AA = S.Context.getAsArrayType(A);
1919 if (!AA)
1920 return TemplateDeductionResult::NonDeducedMismatch;
1922 // Check the element type of the arrays
1923 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1924 assert(DAP);
1925 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1926 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1927 Info, Deduced, TDF & TDF_IgnoreQualifiers,
1928 degradeCallPartialOrderingKind(POK),
1929 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1930 Result != TemplateDeductionResult::Success)
1931 return Result;
1933 // Determine the array bound is something we can deduce.
1934 const NonTypeTemplateParmDecl *NTTP =
1935 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1936 if (!NTTP)
1937 return TemplateDeductionResult::Success;
1939 // We can perform template argument deduction for the given non-type
1940 // template parameter.
1941 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1942 "saw non-type template parameter with wrong depth");
1943 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1944 llvm::APSInt Size(CAA->getSize());
1945 return DeduceNonTypeTemplateArgument(
1946 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1947 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
1948 Deduced, HasDeducedAnyParam);
1950 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1951 if (DAA->getSizeExpr())
1952 return DeduceNonTypeTemplateArgument(
1953 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info,
1954 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
1956 // Incomplete type does not match a dependently-sized array type
1957 return TemplateDeductionResult::NonDeducedMismatch;
1960 // type(*)(T)
1961 // T(*)()
1962 // T(*)(T)
1963 case Type::FunctionProto: {
1964 const auto *FPP = P->castAs<FunctionProtoType>(),
1965 *FPA = A->getAs<FunctionProtoType>();
1966 if (!FPA)
1967 return TemplateDeductionResult::NonDeducedMismatch;
1969 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1970 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1971 FPP->isVariadic() != FPA->isVariadic())
1972 return TemplateDeductionResult::NonDeducedMismatch;
1974 // Check return types.
1975 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1976 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1977 Info, Deduced, 0, degradeCallPartialOrderingKind(POK),
1978 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
1979 Result != TemplateDeductionResult::Success)
1980 return Result;
1982 // Check parameter types.
1983 if (auto Result = DeduceTemplateArguments(
1984 S, TemplateParams, FPP->param_types(), FPA->param_types(), Info,
1985 Deduced, TDF & TDF_TopLevelParameterTypeList, POK,
1986 HasDeducedAnyParam,
1987 /*HasDeducedParam=*/nullptr);
1988 Result != TemplateDeductionResult::Success)
1989 return Result;
1991 if (TDF & TDF_AllowCompatibleFunctionType)
1992 return TemplateDeductionResult::Success;
1994 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1995 // deducing through the noexcept-specifier if it's part of the canonical
1996 // type. libstdc++ relies on this.
1997 Expr *NoexceptExpr = FPP->getNoexceptExpr();
1998 if (const NonTypeTemplateParmDecl *NTTP =
1999 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
2000 : nullptr) {
2001 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
2002 "saw non-type template parameter with wrong depth");
2004 llvm::APSInt Noexcept(1);
2005 switch (FPA->canThrow()) {
2006 case CT_Cannot:
2007 Noexcept = 1;
2008 [[fallthrough]];
2010 case CT_Can:
2011 // We give E in noexcept(E) the "deduced from array bound" treatment.
2012 // FIXME: Should we?
2013 return DeduceNonTypeTemplateArgument(
2014 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
2015 /*DeducedFromArrayBound=*/true, Info,
2016 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2018 case CT_Dependent:
2019 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
2020 return DeduceNonTypeTemplateArgument(
2021 S, TemplateParams, NTTP, ArgNoexceptExpr, Info,
2022 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2023 // Can't deduce anything from throw(T...).
2024 break;
2027 // FIXME: Detect non-deduced exception specification mismatches?
2029 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
2030 // top-level differences in noexcept-specifications.
2032 return TemplateDeductionResult::Success;
2035 case Type::InjectedClassName:
2036 // Treat a template's injected-class-name as if the template
2037 // specialization type had been used.
2039 // template-name<T> (where template-name refers to a class template)
2040 // template-name<i>
2041 // TT<T>
2042 // TT<i>
2043 // TT<>
2044 case Type::TemplateSpecialization: {
2045 // When Arg cannot be a derived class, we can just try to deduce template
2046 // arguments from the template-id.
2047 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2048 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
2049 POK != PartialOrderingKind::None,
2050 Deduced, HasDeducedAnyParam);
2052 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
2053 Deduced.end());
2055 auto Result = DeduceTemplateSpecArguments(
2056 S, TemplateParams, P, A, Info, POK != PartialOrderingKind::None,
2057 Deduced, HasDeducedAnyParam);
2058 if (Result == TemplateDeductionResult::Success)
2059 return Result;
2061 // We cannot inspect base classes as part of deduction when the type
2062 // is incomplete, so either instantiate any templates necessary to
2063 // complete the type, or skip over it if it cannot be completed.
2064 if (!S.isCompleteType(Info.getLocation(), A))
2065 return Result;
2067 const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
2068 if (RD->isInvalidDecl())
2069 return Result;
2071 // Reset the incorrectly deduced argument from above.
2072 Deduced = DeducedOrig;
2074 // Check bases according to C++14 [temp.deduct.call] p4b3:
2075 auto BaseResult = DeduceTemplateBases(S, RD, TemplateParams, P, Info,
2076 POK != PartialOrderingKind::None,
2077 Deduced, HasDeducedAnyParam);
2078 return BaseResult != TemplateDeductionResult::Invalid ? BaseResult
2079 : Result;
2082 // T type::*
2083 // T T::*
2084 // T (type::*)()
2085 // type (T::*)()
2086 // type (type::*)(T)
2087 // type (T::*)(T)
2088 // T (type::*)(T)
2089 // T (T::*)()
2090 // T (T::*)(T)
2091 case Type::MemberPointer: {
2092 const auto *MPP = P->castAs<MemberPointerType>(),
2093 *MPA = A->getAs<MemberPointerType>();
2094 if (!MPA)
2095 return TemplateDeductionResult::NonDeducedMismatch;
2097 QualType PPT = MPP->getPointeeType();
2098 if (PPT->isFunctionType())
2099 S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
2100 /*IsCtorOrDtor=*/false, Info.getLocation());
2101 QualType APT = MPA->getPointeeType();
2102 if (APT->isFunctionType())
2103 S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
2104 /*IsCtorOrDtor=*/false, Info.getLocation());
2106 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2107 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2108 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF,
2109 degradeCallPartialOrderingKind(POK),
2110 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2111 Result != TemplateDeductionResult::Success)
2112 return Result;
2113 return DeduceTemplateArgumentsByTypeMatch(
2114 S, TemplateParams, QualType(MPP->getClass(), 0),
2115 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF,
2116 degradeCallPartialOrderingKind(POK),
2117 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2120 // (clang extension)
2122 // type(^)(T)
2123 // T(^)()
2124 // T(^)(T)
2125 case Type::BlockPointer: {
2126 const auto *BPP = P->castAs<BlockPointerType>(),
2127 *BPA = A->getAs<BlockPointerType>();
2128 if (!BPA)
2129 return TemplateDeductionResult::NonDeducedMismatch;
2130 return DeduceTemplateArgumentsByTypeMatch(
2131 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2132 Deduced, 0, degradeCallPartialOrderingKind(POK),
2133 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2136 // (clang extension)
2138 // T __attribute__(((ext_vector_type(<integral constant>))))
2139 case Type::ExtVector: {
2140 const auto *VP = P->castAs<ExtVectorType>();
2141 QualType ElementType;
2142 if (const auto *VA = A->getAs<ExtVectorType>()) {
2143 // Make sure that the vectors have the same number of elements.
2144 if (VP->getNumElements() != VA->getNumElements())
2145 return TemplateDeductionResult::NonDeducedMismatch;
2146 ElementType = VA->getElementType();
2147 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2148 // We can't check the number of elements, since the argument has a
2149 // dependent number of elements. This can only occur during partial
2150 // ordering.
2151 ElementType = VA->getElementType();
2152 } else {
2153 return TemplateDeductionResult::NonDeducedMismatch;
2155 // Perform deduction on the element types.
2156 return DeduceTemplateArgumentsByTypeMatch(
2157 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2158 TDF, degradeCallPartialOrderingKind(POK),
2159 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2162 case Type::DependentVector: {
2163 const auto *VP = P->castAs<DependentVectorType>();
2165 if (const auto *VA = A->getAs<VectorType>()) {
2166 // Perform deduction on the element types.
2167 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2168 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2169 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2170 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2171 Result != TemplateDeductionResult::Success)
2172 return Result;
2174 // Perform deduction on the vector size, if we can.
2175 const NonTypeTemplateParmDecl *NTTP =
2176 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2177 if (!NTTP)
2178 return TemplateDeductionResult::Success;
2180 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2181 ArgSize = VA->getNumElements();
2182 // Note that we use the "array bound" rules here; just like in that
2183 // case, we don't have any particular type for the vector size, but
2184 // we can provide one if necessary.
2185 return DeduceNonTypeTemplateArgument(
2186 S, TemplateParams, NTTP, ArgSize, S.Context.UnsignedIntTy, true,
2187 Info, POK != PartialOrderingKind::None, Deduced,
2188 HasDeducedAnyParam);
2191 if (const auto *VA = A->getAs<DependentVectorType>()) {
2192 // Perform deduction on the element types.
2193 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2194 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2195 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2196 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2197 Result != TemplateDeductionResult::Success)
2198 return Result;
2200 // Perform deduction on the vector size, if we can.
2201 const NonTypeTemplateParmDecl *NTTP =
2202 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2203 if (!NTTP)
2204 return TemplateDeductionResult::Success;
2206 return DeduceNonTypeTemplateArgument(
2207 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2208 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2211 return TemplateDeductionResult::NonDeducedMismatch;
2214 // (clang extension)
2216 // T __attribute__(((ext_vector_type(N))))
2217 case Type::DependentSizedExtVector: {
2218 const auto *VP = P->castAs<DependentSizedExtVectorType>();
2220 if (const auto *VA = A->getAs<ExtVectorType>()) {
2221 // Perform deduction on the element types.
2222 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2223 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2224 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2225 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2226 Result != TemplateDeductionResult::Success)
2227 return Result;
2229 // Perform deduction on the vector size, if we can.
2230 const NonTypeTemplateParmDecl *NTTP =
2231 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2232 if (!NTTP)
2233 return TemplateDeductionResult::Success;
2235 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2236 ArgSize = VA->getNumElements();
2237 // Note that we use the "array bound" rules here; just like in that
2238 // case, we don't have any particular type for the vector size, but
2239 // we can provide one if necessary.
2240 return DeduceNonTypeTemplateArgument(
2241 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2242 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2245 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2246 // Perform deduction on the element types.
2247 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2248 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2249 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2250 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2251 Result != TemplateDeductionResult::Success)
2252 return Result;
2254 // Perform deduction on the vector size, if we can.
2255 const NonTypeTemplateParmDecl *NTTP =
2256 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2257 if (!NTTP)
2258 return TemplateDeductionResult::Success;
2260 return DeduceNonTypeTemplateArgument(
2261 S, TemplateParams, NTTP, VA->getSizeExpr(), Info,
2262 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2265 return TemplateDeductionResult::NonDeducedMismatch;
2268 // (clang extension)
2270 // T __attribute__((matrix_type(<integral constant>,
2271 // <integral constant>)))
2272 case Type::ConstantMatrix: {
2273 const auto *MP = P->castAs<ConstantMatrixType>(),
2274 *MA = A->getAs<ConstantMatrixType>();
2275 if (!MA)
2276 return TemplateDeductionResult::NonDeducedMismatch;
2278 // Check that the dimensions are the same
2279 if (MP->getNumRows() != MA->getNumRows() ||
2280 MP->getNumColumns() != MA->getNumColumns()) {
2281 return TemplateDeductionResult::NonDeducedMismatch;
2283 // Perform deduction on element types.
2284 return DeduceTemplateArgumentsByTypeMatch(
2285 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2286 Deduced, TDF, degradeCallPartialOrderingKind(POK),
2287 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2290 case Type::DependentSizedMatrix: {
2291 const auto *MP = P->castAs<DependentSizedMatrixType>();
2292 const auto *MA = A->getAs<MatrixType>();
2293 if (!MA)
2294 return TemplateDeductionResult::NonDeducedMismatch;
2296 // Check the element type of the matrixes.
2297 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2298 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2299 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2300 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2301 Result != TemplateDeductionResult::Success)
2302 return Result;
2304 // Try to deduce a matrix dimension.
2305 auto DeduceMatrixArg =
2306 [&S, &Info, &Deduced, &TemplateParams, &HasDeducedAnyParam, POK](
2307 Expr *ParamExpr, const MatrixType *A,
2308 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2309 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2310 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2311 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
2312 if (!ParamExpr->isValueDependent()) {
2313 std::optional<llvm::APSInt> ParamConst =
2314 ParamExpr->getIntegerConstantExpr(S.Context);
2315 if (!ParamConst)
2316 return TemplateDeductionResult::NonDeducedMismatch;
2318 if (ACM) {
2319 if ((ACM->*GetArgDimension)() == *ParamConst)
2320 return TemplateDeductionResult::Success;
2321 return TemplateDeductionResult::NonDeducedMismatch;
2324 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2325 if (std::optional<llvm::APSInt> ArgConst =
2326 ArgExpr->getIntegerConstantExpr(S.Context))
2327 if (*ArgConst == *ParamConst)
2328 return TemplateDeductionResult::Success;
2329 return TemplateDeductionResult::NonDeducedMismatch;
2332 const NonTypeTemplateParmDecl *NTTP =
2333 getDeducedParameterFromExpr(Info, ParamExpr);
2334 if (!NTTP)
2335 return TemplateDeductionResult::Success;
2337 if (ACM) {
2338 llvm::APSInt ArgConst(
2339 S.Context.getTypeSize(S.Context.getSizeType()));
2340 ArgConst = (ACM->*GetArgDimension)();
2341 return DeduceNonTypeTemplateArgument(
2342 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2343 /*ArrayBound=*/true, Info, POK != PartialOrderingKind::None,
2344 Deduced, HasDeducedAnyParam);
2347 return DeduceNonTypeTemplateArgument(
2348 S, TemplateParams, NTTP, (ADM->*GetArgDimensionExpr)(), Info,
2349 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2352 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
2353 &ConstantMatrixType::getNumRows,
2354 &DependentSizedMatrixType::getRowExpr);
2355 Result != TemplateDeductionResult::Success)
2356 return Result;
2358 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2359 &ConstantMatrixType::getNumColumns,
2360 &DependentSizedMatrixType::getColumnExpr);
2363 // (clang extension)
2365 // T __attribute__(((address_space(N))))
2366 case Type::DependentAddressSpace: {
2367 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2369 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2370 // Perform deduction on the pointer type.
2371 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2372 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2373 Info, Deduced, TDF, degradeCallPartialOrderingKind(POK),
2374 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2375 Result != TemplateDeductionResult::Success)
2376 return Result;
2378 // Perform deduction on the address space, if we can.
2379 const NonTypeTemplateParmDecl *NTTP =
2380 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2381 if (!NTTP)
2382 return TemplateDeductionResult::Success;
2384 return DeduceNonTypeTemplateArgument(
2385 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info,
2386 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2389 if (isTargetAddressSpace(A.getAddressSpace())) {
2390 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2391 false);
2392 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2394 // Perform deduction on the pointer types.
2395 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2396 S, TemplateParams, ASP->getPointeeType(),
2397 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF,
2398 degradeCallPartialOrderingKind(POK),
2399 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2400 Result != TemplateDeductionResult::Success)
2401 return Result;
2403 // Perform deduction on the address space, if we can.
2404 const NonTypeTemplateParmDecl *NTTP =
2405 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2406 if (!NTTP)
2407 return TemplateDeductionResult::Success;
2409 return DeduceNonTypeTemplateArgument(
2410 S, TemplateParams, NTTP, ArgAddressSpace, S.Context.IntTy, true,
2411 Info, POK != PartialOrderingKind::None, Deduced,
2412 HasDeducedAnyParam);
2415 return TemplateDeductionResult::NonDeducedMismatch;
2417 case Type::DependentBitInt: {
2418 const auto *IP = P->castAs<DependentBitIntType>();
2420 if (const auto *IA = A->getAs<BitIntType>()) {
2421 if (IP->isUnsigned() != IA->isUnsigned())
2422 return TemplateDeductionResult::NonDeducedMismatch;
2424 const NonTypeTemplateParmDecl *NTTP =
2425 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2426 if (!NTTP)
2427 return TemplateDeductionResult::Success;
2429 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2430 ArgSize = IA->getNumBits();
2432 return DeduceNonTypeTemplateArgument(
2433 S, TemplateParams, NTTP, ArgSize, S.Context.IntTy, true, Info,
2434 POK != PartialOrderingKind::None, Deduced, HasDeducedAnyParam);
2437 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2438 if (IP->isUnsigned() != IA->isUnsigned())
2439 return TemplateDeductionResult::NonDeducedMismatch;
2440 return TemplateDeductionResult::Success;
2443 return TemplateDeductionResult::NonDeducedMismatch;
2446 case Type::TypeOfExpr:
2447 case Type::TypeOf:
2448 case Type::DependentName:
2449 case Type::UnresolvedUsing:
2450 case Type::Decltype:
2451 case Type::UnaryTransform:
2452 case Type::DeducedTemplateSpecialization:
2453 case Type::DependentTemplateSpecialization:
2454 case Type::PackExpansion:
2455 case Type::Pipe:
2456 case Type::ArrayParameter:
2457 case Type::HLSLAttributedResource:
2458 // No template argument deduction for these types
2459 return TemplateDeductionResult::Success;
2461 case Type::PackIndexing: {
2462 const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2463 if (PIT->hasSelectedType()) {
2464 return DeduceTemplateArgumentsByTypeMatch(
2465 S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF,
2466 degradeCallPartialOrderingKind(POK),
2467 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2469 return TemplateDeductionResult::IncompletePack;
2473 llvm_unreachable("Invalid Type Class!");
2476 static TemplateDeductionResult
2477 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2478 const TemplateArgument &P, TemplateArgument A,
2479 TemplateDeductionInfo &Info, bool PartialOrdering,
2480 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2481 bool *HasDeducedAnyParam) {
2482 // If the template argument is a pack expansion, perform template argument
2483 // deduction against the pattern of that expansion. This only occurs during
2484 // partial ordering.
2485 if (A.isPackExpansion())
2486 A = A.getPackExpansionPattern();
2488 switch (P.getKind()) {
2489 case TemplateArgument::Null:
2490 llvm_unreachable("Null template argument in parameter list");
2492 case TemplateArgument::Type:
2493 if (A.getKind() == TemplateArgument::Type)
2494 return DeduceTemplateArgumentsByTypeMatch(
2495 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0,
2496 PartialOrdering ? PartialOrderingKind::NonCall
2497 : PartialOrderingKind::None,
2498 /*DeducedFromArrayBound=*/false, HasDeducedAnyParam);
2499 Info.FirstArg = P;
2500 Info.SecondArg = A;
2501 return TemplateDeductionResult::NonDeducedMismatch;
2503 case TemplateArgument::Template:
2504 // PartialOrdering does not matter here, since template specializations are
2505 // not being deduced.
2506 if (A.getKind() == TemplateArgument::Template)
2507 return DeduceTemplateArguments(
2508 S, TemplateParams, P.getAsTemplate(), A.getAsTemplate(), Info,
2509 /*DefaultArguments=*/{}, /*PartialOrdering=*/false, Deduced,
2510 HasDeducedAnyParam);
2511 Info.FirstArg = P;
2512 Info.SecondArg = A;
2513 return TemplateDeductionResult::NonDeducedMismatch;
2515 case TemplateArgument::TemplateExpansion:
2516 llvm_unreachable("caller should handle pack expansions");
2518 case TemplateArgument::Declaration:
2519 if (A.getKind() == TemplateArgument::Declaration &&
2520 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2521 return TemplateDeductionResult::Success;
2523 Info.FirstArg = P;
2524 Info.SecondArg = A;
2525 return TemplateDeductionResult::NonDeducedMismatch;
2527 case TemplateArgument::NullPtr:
2528 if (A.getKind() == TemplateArgument::NullPtr &&
2529 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2530 return TemplateDeductionResult::Success;
2532 Info.FirstArg = P;
2533 Info.SecondArg = A;
2534 return TemplateDeductionResult::NonDeducedMismatch;
2536 case TemplateArgument::Integral:
2537 if (A.getKind() == TemplateArgument::Integral) {
2538 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2539 return TemplateDeductionResult::Success;
2541 Info.FirstArg = P;
2542 Info.SecondArg = A;
2543 return TemplateDeductionResult::NonDeducedMismatch;
2545 case TemplateArgument::StructuralValue:
2546 if (A.getKind() == TemplateArgument::StructuralValue &&
2547 A.structurallyEquals(P))
2548 return TemplateDeductionResult::Success;
2550 Info.FirstArg = P;
2551 Info.SecondArg = A;
2552 return TemplateDeductionResult::NonDeducedMismatch;
2554 case TemplateArgument::Expression:
2555 if (const NonTypeTemplateParmDecl *NTTP =
2556 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2557 switch (A.getKind()) {
2558 case TemplateArgument::Integral:
2559 case TemplateArgument::Expression:
2560 case TemplateArgument::StructuralValue:
2561 return DeduceNonTypeTemplateArgument(
2562 S, TemplateParams, NTTP, DeducedTemplateArgument(A),
2563 A.getNonTypeTemplateArgumentType(), Info, PartialOrdering, Deduced,
2564 HasDeducedAnyParam);
2566 case TemplateArgument::NullPtr:
2567 return DeduceNullPtrTemplateArgument(
2568 S, TemplateParams, NTTP, A.getNullPtrType(), Info, PartialOrdering,
2569 Deduced, HasDeducedAnyParam);
2571 case TemplateArgument::Declaration:
2572 return DeduceNonTypeTemplateArgument(
2573 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2574 Info, PartialOrdering, Deduced, HasDeducedAnyParam);
2576 case TemplateArgument::Null:
2577 case TemplateArgument::Type:
2578 case TemplateArgument::Template:
2579 case TemplateArgument::TemplateExpansion:
2580 case TemplateArgument::Pack:
2581 Info.FirstArg = P;
2582 Info.SecondArg = A;
2583 return TemplateDeductionResult::NonDeducedMismatch;
2585 llvm_unreachable("Unknown template argument kind");
2588 // Can't deduce anything, but that's okay.
2589 return TemplateDeductionResult::Success;
2590 case TemplateArgument::Pack:
2591 llvm_unreachable("Argument packs should be expanded by the caller!");
2594 llvm_unreachable("Invalid TemplateArgument Kind!");
2597 /// Determine whether there is a template argument to be used for
2598 /// deduction.
2600 /// This routine "expands" argument packs in-place, overriding its input
2601 /// parameters so that \c Args[ArgIdx] will be the available template argument.
2603 /// \returns true if there is another template argument (which will be at
2604 /// \c Args[ArgIdx]), false otherwise.
2605 static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2606 unsigned &ArgIdx) {
2607 if (ArgIdx == Args.size())
2608 return false;
2610 const TemplateArgument &Arg = Args[ArgIdx];
2611 if (Arg.getKind() != TemplateArgument::Pack)
2612 return true;
2614 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2615 Args = Arg.pack_elements();
2616 ArgIdx = 0;
2617 return ArgIdx < Args.size();
2620 /// Determine whether the given set of template arguments has a pack
2621 /// expansion that is not the last template argument.
2622 static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2623 bool FoundPackExpansion = false;
2624 for (const auto &A : Args) {
2625 if (FoundPackExpansion)
2626 return true;
2628 if (A.getKind() == TemplateArgument::Pack)
2629 return hasPackExpansionBeforeEnd(A.pack_elements());
2631 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2632 // templates, it should not be treated as a pack expansion.
2633 if (A.isPackExpansion())
2634 FoundPackExpansion = true;
2637 return false;
2640 static TemplateDeductionResult
2641 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2642 ArrayRef<TemplateArgument> Ps,
2643 ArrayRef<TemplateArgument> As,
2644 TemplateDeductionInfo &Info,
2645 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2646 bool NumberOfArgumentsMustMatch, bool PartialOrdering,
2647 PackFold PackFold, bool *HasDeducedAnyParam) {
2648 if (PackFold == PackFold::ArgumentToParameter)
2649 std::swap(Ps, As);
2650 // C++0x [temp.deduct.type]p9:
2651 // If the template argument list of P contains a pack expansion that is not
2652 // the last template argument, the entire template argument list is a
2653 // non-deduced context.
2654 if (hasPackExpansionBeforeEnd(Ps))
2655 return TemplateDeductionResult::Success;
2657 // C++0x [temp.deduct.type]p9:
2658 // If P has a form that contains <T> or <i>, then each argument Pi of the
2659 // respective template argument list P is compared with the corresponding
2660 // argument Ai of the corresponding template argument list of A.
2661 unsigned ArgIdx = 0, ParamIdx = 0;
2662 for (; hasTemplateArgumentForDeduction(Ps, ParamIdx); ++ParamIdx) {
2663 const TemplateArgument &P = Ps[ParamIdx];
2664 if (!P.isPackExpansion()) {
2665 // The simple case: deduce template arguments by matching Pi and Ai.
2667 // Check whether we have enough arguments.
2668 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2669 return NumberOfArgumentsMustMatch
2670 ? TemplateDeductionResult::MiscellaneousDeductionFailure
2671 : TemplateDeductionResult::Success;
2673 // C++1z [temp.deduct.type]p9:
2674 // During partial ordering, if Ai was originally a pack expansion [and]
2675 // Pi is not a pack expansion, template argument deduction fails.
2676 if (As[ArgIdx].isPackExpansion())
2677 return TemplateDeductionResult::MiscellaneousDeductionFailure;
2679 // Perform deduction for this Pi/Ai pair.
2680 TemplateArgument Pi = P, Ai = As[ArgIdx];
2681 if (PackFold == PackFold::ArgumentToParameter)
2682 std::swap(Pi, Ai);
2683 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info,
2684 PartialOrdering, Deduced,
2685 HasDeducedAnyParam);
2686 Result != TemplateDeductionResult::Success)
2687 return Result;
2689 // Move to the next argument.
2690 ++ArgIdx;
2691 continue;
2694 // The parameter is a pack expansion.
2696 // C++0x [temp.deduct.type]p9:
2697 // If Pi is a pack expansion, then the pattern of Pi is compared with
2698 // each remaining argument in the template argument list of A. Each
2699 // comparison deduces template arguments for subsequent positions in the
2700 // template parameter packs expanded by Pi.
2701 TemplateArgument Pattern = P.getPackExpansionPattern();
2703 // Prepare to deduce the packs within the pattern.
2704 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2706 // Keep track of the deduced template arguments for each parameter pack
2707 // expanded by this pack expansion (the outer index) and for each
2708 // template argument (the inner SmallVectors).
2709 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2710 PackScope.hasNextElement();
2711 ++ArgIdx) {
2712 TemplateArgument Pi = Pattern, Ai = As[ArgIdx];
2713 if (PackFold == PackFold::ArgumentToParameter)
2714 std::swap(Pi, Ai);
2715 // Deduce template arguments from the pattern.
2716 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info,
2717 PartialOrdering, Deduced,
2718 HasDeducedAnyParam);
2719 Result != TemplateDeductionResult::Success)
2720 return Result;
2722 PackScope.nextPackElement();
2725 // Build argument packs for each of the parameter packs expanded by this
2726 // pack expansion.
2727 if (auto Result = PackScope.finish();
2728 Result != TemplateDeductionResult::Success)
2729 return Result;
2732 return TemplateDeductionResult::Success;
2735 TemplateDeductionResult Sema::DeduceTemplateArguments(
2736 TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
2737 ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
2738 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2739 bool NumberOfArgumentsMustMatch) {
2740 return ::DeduceTemplateArguments(
2741 *this, TemplateParams, Ps, As, Info, Deduced, NumberOfArgumentsMustMatch,
2742 /*PartialOrdering=*/false, PackFold::ParameterToArgument,
2743 /*HasDeducedAnyParam=*/nullptr);
2746 /// Determine whether two template arguments are the same.
2747 static bool isSameTemplateArg(ASTContext &Context,
2748 TemplateArgument X,
2749 const TemplateArgument &Y,
2750 bool PartialOrdering,
2751 bool PackExpansionMatchesPack = false) {
2752 // If we're checking deduced arguments (X) against original arguments (Y),
2753 // we will have flattened packs to non-expansions in X.
2754 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2755 X = X.getPackExpansionPattern();
2757 if (X.getKind() != Y.getKind())
2758 return false;
2760 switch (X.getKind()) {
2761 case TemplateArgument::Null:
2762 llvm_unreachable("Comparing NULL template argument");
2764 case TemplateArgument::Type:
2765 return Context.getCanonicalType(X.getAsType()) ==
2766 Context.getCanonicalType(Y.getAsType());
2768 case TemplateArgument::Declaration:
2769 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2771 case TemplateArgument::NullPtr:
2772 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2774 case TemplateArgument::Template:
2775 case TemplateArgument::TemplateExpansion:
2776 return Context.getCanonicalTemplateName(
2777 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2778 Context.getCanonicalTemplateName(
2779 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
2781 case TemplateArgument::Integral:
2782 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2784 case TemplateArgument::StructuralValue:
2785 return X.structurallyEquals(Y);
2787 case TemplateArgument::Expression: {
2788 llvm::FoldingSetNodeID XID, YID;
2789 X.getAsExpr()->Profile(XID, Context, true);
2790 Y.getAsExpr()->Profile(YID, Context, true);
2791 return XID == YID;
2794 case TemplateArgument::Pack: {
2795 unsigned PackIterationSize = X.pack_size();
2796 if (X.pack_size() != Y.pack_size()) {
2797 if (!PartialOrdering)
2798 return false;
2800 // C++0x [temp.deduct.type]p9:
2801 // During partial ordering, if Ai was originally a pack expansion:
2802 // - if P does not contain a template argument corresponding to Ai
2803 // then Ai is ignored;
2804 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2805 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2806 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2807 return false;
2809 if (XHasMoreArg)
2810 PackIterationSize = Y.pack_size();
2813 ArrayRef<TemplateArgument> XP = X.pack_elements();
2814 ArrayRef<TemplateArgument> YP = Y.pack_elements();
2815 for (unsigned i = 0; i < PackIterationSize; ++i)
2816 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2817 PackExpansionMatchesPack))
2818 return false;
2819 return true;
2823 llvm_unreachable("Invalid TemplateArgument Kind!");
2826 TemplateArgumentLoc
2827 Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2828 QualType NTTPType, SourceLocation Loc,
2829 NamedDecl *TemplateParam) {
2830 switch (Arg.getKind()) {
2831 case TemplateArgument::Null:
2832 llvm_unreachable("Can't get a NULL template argument here");
2834 case TemplateArgument::Type:
2835 return TemplateArgumentLoc(
2836 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2838 case TemplateArgument::Declaration: {
2839 if (NTTPType.isNull())
2840 NTTPType = Arg.getParamTypeForDecl();
2841 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc,
2842 TemplateParam)
2843 .getAs<Expr>();
2844 return TemplateArgumentLoc(TemplateArgument(E), E);
2847 case TemplateArgument::NullPtr: {
2848 if (NTTPType.isNull())
2849 NTTPType = Arg.getNullPtrType();
2850 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2851 .getAs<Expr>();
2852 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2856 case TemplateArgument::Integral:
2857 case TemplateArgument::StructuralValue: {
2858 Expr *E = BuildExpressionFromNonTypeTemplateArgument(Arg, Loc).get();
2859 return TemplateArgumentLoc(TemplateArgument(E), E);
2862 case TemplateArgument::Template:
2863 case TemplateArgument::TemplateExpansion: {
2864 NestedNameSpecifierLocBuilder Builder;
2865 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2866 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2867 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2868 else if (QualifiedTemplateName *QTN =
2869 Template.getAsQualifiedTemplateName())
2870 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2872 if (Arg.getKind() == TemplateArgument::Template)
2873 return TemplateArgumentLoc(Context, Arg,
2874 Builder.getWithLocInContext(Context), Loc);
2876 return TemplateArgumentLoc(
2877 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2880 case TemplateArgument::Expression:
2881 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2883 case TemplateArgument::Pack:
2884 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2887 llvm_unreachable("Invalid TemplateArgument Kind!");
2890 TemplateArgumentLoc
2891 Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm,
2892 SourceLocation Location) {
2893 return getTrivialTemplateArgumentLoc(
2894 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2897 /// Convert the given deduced template argument and add it to the set of
2898 /// fully-converted template arguments.
2899 static bool ConvertDeducedTemplateArgument(
2900 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2901 TemplateDeductionInfo &Info, bool IsDeduced,
2902 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2903 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2904 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2905 unsigned ArgumentPackIndex) {
2906 // Convert the deduced template argument into a template
2907 // argument that we can check, almost as if the user had written
2908 // the template argument explicitly.
2909 TemplateArgumentLoc ArgLoc = S.getTrivialTemplateArgumentLoc(
2910 Arg, QualType(), Info.getLocation(), Param);
2912 // Check the template argument, converting it as necessary.
2913 return S.CheckTemplateArgument(
2914 Param, ArgLoc, Template, Template->getLocation(),
2915 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2916 CanonicalOutput,
2917 IsDeduced
2918 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2919 : Sema::CTAK_Deduced)
2920 : Sema::CTAK_Specified);
2923 if (Arg.getKind() == TemplateArgument::Pack) {
2924 // This is a template argument pack, so check each of its arguments against
2925 // the template parameter.
2926 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2927 CanonicalPackedArgsBuilder;
2928 for (const auto &P : Arg.pack_elements()) {
2929 // When converting the deduced template argument, append it to the
2930 // general output list. We need to do this so that the template argument
2931 // checking logic has all of the prior template arguments available.
2932 DeducedTemplateArgument InnerArg(P);
2933 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2934 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2935 "deduced nested pack");
2936 if (P.isNull()) {
2937 // We deduced arguments for some elements of this pack, but not for
2938 // all of them. This happens if we get a conditionally-non-deduced
2939 // context in a pack expansion (such as an overload set in one of the
2940 // arguments).
2941 S.Diag(Param->getLocation(),
2942 diag::err_template_arg_deduced_incomplete_pack)
2943 << Arg << Param;
2944 return true;
2946 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2947 return true;
2949 // Move the converted template argument into our argument pack.
2950 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2951 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2954 // If the pack is empty, we still need to substitute into the parameter
2955 // itself, in case that substitution fails.
2956 if (SugaredPackedArgsBuilder.empty()) {
2957 LocalInstantiationScope Scope(S);
2958 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2959 /*Final=*/true);
2961 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2962 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2963 NTTP, SugaredOutput,
2964 Template->getSourceRange());
2965 if (Inst.isInvalid() ||
2966 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2967 NTTP->getDeclName()).isNull())
2968 return true;
2969 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2970 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2971 TTP, SugaredOutput,
2972 Template->getSourceRange());
2973 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2974 return true;
2976 // For type parameters, no substitution is ever required.
2979 // Create the resulting argument pack.
2980 SugaredOutput.push_back(
2981 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2982 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2983 S.Context, CanonicalPackedArgsBuilder));
2984 return false;
2987 return ConvertArg(Arg, 0);
2990 // FIXME: This should not be a template, but
2991 // ClassTemplatePartialSpecializationDecl sadly does not derive from
2992 // TemplateDecl.
2993 /// \param IsIncomplete When used, we only consider template parameters that
2994 /// were deduced, disregarding any default arguments. After the function
2995 /// finishes, the object pointed at will contain a value indicating if the
2996 /// conversion was actually incomplete.
2997 template <typename TemplateDeclT>
2998 static TemplateDeductionResult ConvertDeducedTemplateArguments(
2999 Sema &S, TemplateDeclT *Template, bool IsDeduced,
3000 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3001 TemplateDeductionInfo &Info,
3002 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
3003 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
3004 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
3005 unsigned NumAlreadyConverted = 0, bool *IsIncomplete = nullptr) {
3006 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3008 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3009 NamedDecl *Param = TemplateParams->getParam(I);
3011 // C++0x [temp.arg.explicit]p3:
3012 // A trailing template parameter pack (14.5.3) not otherwise deduced will
3013 // be deduced to an empty sequence of template arguments.
3014 // FIXME: Where did the word "trailing" come from?
3015 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
3016 if (auto Result =
3017 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
3018 Result != TemplateDeductionResult::Success)
3019 return Result;
3022 if (!Deduced[I].isNull()) {
3023 if (I < NumAlreadyConverted) {
3024 // We may have had explicitly-specified template arguments for a
3025 // template parameter pack (that may or may not have been extended
3026 // via additional deduced arguments).
3027 if (Param->isParameterPack() && CurrentInstantiationScope &&
3028 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
3029 // Forget the partially-substituted pack; its substitution is now
3030 // complete.
3031 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
3032 // We still need to check the argument in case it was extended by
3033 // deduction.
3034 } else {
3035 // We have already fully type-checked and converted this
3036 // argument, because it was explicitly-specified. Just record the
3037 // presence of this argument.
3038 SugaredBuilder.push_back(Deduced[I]);
3039 CanonicalBuilder.push_back(
3040 S.Context.getCanonicalTemplateArgument(Deduced[I]));
3041 continue;
3045 // We may have deduced this argument, so it still needs to be
3046 // checked and converted.
3047 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
3048 IsDeduced, SugaredBuilder,
3049 CanonicalBuilder)) {
3050 Info.Param = makeTemplateParameter(Param);
3051 // FIXME: These template arguments are temporary. Free them!
3052 Info.reset(
3053 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3054 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3055 return TemplateDeductionResult::SubstitutionFailure;
3058 continue;
3061 // [C++26][temp.deduct.partial]p12 - When partial ordering, it's ok for
3062 // template parameters to remain not deduced. As a provisional fix for a
3063 // core issue that does not exist yet, which may be related to CWG2160, only
3064 // consider template parameters that were deduced, disregarding any default
3065 // arguments.
3066 if (IsIncomplete) {
3067 *IsIncomplete = true;
3068 SugaredBuilder.push_back({});
3069 CanonicalBuilder.push_back({});
3070 continue;
3073 // Substitute into the default template argument, if available.
3074 bool HasDefaultArg = false;
3075 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
3076 if (!TD) {
3077 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
3078 isa<VarTemplatePartialSpecializationDecl>(Template));
3079 return TemplateDeductionResult::Incomplete;
3082 TemplateArgumentLoc DefArg;
3084 Qualifiers ThisTypeQuals;
3085 CXXRecordDecl *ThisContext = nullptr;
3086 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
3087 if (Rec->isLambda())
3088 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
3089 ThisContext = Method->getParent();
3090 ThisTypeQuals = Method->getMethodQualifiers();
3093 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3094 S.getLangOpts().CPlusPlus17);
3096 DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
3097 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
3098 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
3101 // If there was no default argument, deduction is incomplete.
3102 if (DefArg.getArgument().isNull()) {
3103 Info.Param = makeTemplateParameter(
3104 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3105 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3106 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3108 return HasDefaultArg ? TemplateDeductionResult::SubstitutionFailure
3109 : TemplateDeductionResult::Incomplete;
3112 // Check whether we can actually use the default argument.
3113 if (S.CheckTemplateArgument(
3114 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3115 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
3116 Info.Param = makeTemplateParameter(
3117 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3118 // FIXME: These template arguments are temporary. Free them!
3119 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3120 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3121 return TemplateDeductionResult::SubstitutionFailure;
3124 // If we get here, we successfully used the default template argument.
3127 return TemplateDeductionResult::Success;
3130 static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
3131 if (auto *DC = dyn_cast<DeclContext>(D))
3132 return DC;
3133 return D->getDeclContext();
3136 template<typename T> struct IsPartialSpecialization {
3137 static constexpr bool value = false;
3139 template<>
3140 struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
3141 static constexpr bool value = true;
3143 template<>
3144 struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
3145 static constexpr bool value = true;
3147 template <typename TemplateDeclT>
3148 static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3149 return false;
3151 template <>
3152 bool DeducedArgsNeedReplacement<VarTemplatePartialSpecializationDecl>(
3153 VarTemplatePartialSpecializationDecl *Spec) {
3154 return !Spec->isClassScopeExplicitSpecialization();
3156 template <>
3157 bool DeducedArgsNeedReplacement<ClassTemplatePartialSpecializationDecl>(
3158 ClassTemplatePartialSpecializationDecl *Spec) {
3159 return !Spec->isClassScopeExplicitSpecialization();
3162 template <typename TemplateDeclT>
3163 static TemplateDeductionResult
3164 CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3165 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3166 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3167 TemplateDeductionInfo &Info) {
3168 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3169 Template->getAssociatedConstraints(AssociatedConstraints);
3171 std::optional<ArrayRef<TemplateArgument>> Innermost;
3172 // If we don't need to replace the deduced template arguments,
3173 // we can add them immediately as the inner-most argument list.
3174 if (!DeducedArgsNeedReplacement(Template))
3175 Innermost = CanonicalDeducedArgs;
3177 MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
3178 Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3179 /*RelativeToPrimary=*/true, /*Pattern=*/
3180 nullptr, /*ForConstraintInstantiation=*/true);
3182 // getTemplateInstantiationArgs picks up the non-deduced version of the
3183 // template args when this is a variable template partial specialization and
3184 // not class-scope explicit specialization, so replace with Deduced Args
3185 // instead of adding to inner-most.
3186 if (!Innermost)
3187 MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3189 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3190 Info.getLocation(),
3191 Info.AssociatedConstraintsSatisfaction) ||
3192 !Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
3193 Info.reset(
3194 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3195 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3196 return TemplateDeductionResult::ConstraintsNotSatisfied;
3198 return TemplateDeductionResult::Success;
3201 /// Complete template argument deduction for a partial specialization.
3202 template <typename T>
3203 static std::enable_if_t<IsPartialSpecialization<T>::value,
3204 TemplateDeductionResult>
3205 FinishTemplateArgumentDeduction(
3206 Sema &S, T *Partial, bool IsPartialOrdering,
3207 ArrayRef<TemplateArgument> TemplateArgs,
3208 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3209 TemplateDeductionInfo &Info) {
3210 // Unevaluated SFINAE context.
3211 EnterExpressionEvaluationContext Unevaluated(
3212 S, Sema::ExpressionEvaluationContext::Unevaluated);
3213 Sema::SFINAETrap Trap(S);
3215 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
3217 // C++ [temp.deduct.type]p2:
3218 // [...] or if any template argument remains neither deduced nor
3219 // explicitly specified, template argument deduction fails.
3220 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3221 if (auto Result = ConvertDeducedTemplateArguments(
3222 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3223 CanonicalBuilder);
3224 Result != TemplateDeductionResult::Success)
3225 return Result;
3227 // Form the template argument list from the deduced template arguments.
3228 TemplateArgumentList *SugaredDeducedArgumentList =
3229 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3230 TemplateArgumentList *CanonicalDeducedArgumentList =
3231 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
3233 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3235 // Substitute the deduced template arguments into the template
3236 // arguments of the class template partial specialization, and
3237 // verify that the instantiated template arguments are both valid
3238 // and are equivalent to the template arguments originally provided
3239 // to the class template.
3240 LocalInstantiationScope InstScope(S);
3241 auto *Template = Partial->getSpecializedTemplate();
3242 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
3243 Partial->getTemplateArgsAsWritten();
3245 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
3246 PartialTemplArgInfo->RAngleLoc);
3248 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3249 MultiLevelTemplateArgumentList(Partial,
3250 SugaredBuilder,
3251 /*Final=*/true),
3252 InstArgs)) {
3253 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
3254 if (ParamIdx >= Partial->getTemplateParameters()->size())
3255 ParamIdx = Partial->getTemplateParameters()->size() - 1;
3257 Decl *Param = const_cast<NamedDecl *>(
3258 Partial->getTemplateParameters()->getParam(ParamIdx));
3259 Info.Param = makeTemplateParameter(Param);
3260 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3261 return TemplateDeductionResult::SubstitutionFailure;
3264 bool ConstraintsNotSatisfied;
3265 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3266 CanonicalConvertedInstArgs;
3267 if (S.CheckTemplateArgumentList(
3268 Template, Partial->getLocation(), InstArgs, /*DefaultArgs=*/{}, false,
3269 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3270 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3271 return ConstraintsNotSatisfied
3272 ? TemplateDeductionResult::ConstraintsNotSatisfied
3273 : TemplateDeductionResult::SubstitutionFailure;
3275 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3276 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3277 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3278 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3279 IsPartialOrdering)) {
3280 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3281 Info.FirstArg = TemplateArgs[I];
3282 Info.SecondArg = InstArg;
3283 return TemplateDeductionResult::NonDeducedMismatch;
3287 if (Trap.hasErrorOccurred())
3288 return TemplateDeductionResult::SubstitutionFailure;
3290 if (!IsPartialOrdering) {
3291 if (auto Result = CheckDeducedArgumentConstraints(
3292 S, Partial, SugaredBuilder, CanonicalBuilder, Info);
3293 Result != TemplateDeductionResult::Success)
3294 return Result;
3297 return TemplateDeductionResult::Success;
3300 /// Complete template argument deduction for a class or variable template,
3301 /// when partial ordering against a partial specialization.
3302 // FIXME: Factor out duplication with partial specialization version above.
3303 static TemplateDeductionResult FinishTemplateArgumentDeduction(
3304 Sema &S, TemplateDecl *Template, bool PartialOrdering,
3305 ArrayRef<TemplateArgument> TemplateArgs,
3306 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3307 TemplateDeductionInfo &Info) {
3308 // Unevaluated SFINAE context.
3309 EnterExpressionEvaluationContext Unevaluated(
3310 S, Sema::ExpressionEvaluationContext::Unevaluated);
3311 Sema::SFINAETrap Trap(S);
3313 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3315 // C++ [temp.deduct.type]p2:
3316 // [...] or if any template argument remains neither deduced nor
3317 // explicitly specified, template argument deduction fails.
3318 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3319 if (auto Result = ConvertDeducedTemplateArguments(
3320 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3321 SugaredBuilder, CanonicalBuilder,
3322 /*CurrentInstantiationScope=*/nullptr,
3323 /*NumAlreadyConverted=*/0U);
3324 Result != TemplateDeductionResult::Success)
3325 return Result;
3327 // Check that we produced the correct argument list.
3328 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3329 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3330 TemplateArgument InstArg = CanonicalBuilder[I];
3331 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3332 /*PackExpansionMatchesPack=*/true)) {
3333 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3334 Info.FirstArg = TemplateArgs[I];
3335 Info.SecondArg = InstArg;
3336 return TemplateDeductionResult::NonDeducedMismatch;
3340 if (Trap.hasErrorOccurred())
3341 return TemplateDeductionResult::SubstitutionFailure;
3343 if (!PartialOrdering) {
3344 if (auto Result = CheckDeducedArgumentConstraints(
3345 S, Template, SugaredBuilder, CanonicalBuilder, Info);
3346 Result != TemplateDeductionResult::Success)
3347 return Result;
3350 return TemplateDeductionResult::Success;
3353 /// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3354 /// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3355 /// the three implementations.
3356 static TemplateDeductionResult FinishTemplateArgumentDeduction(
3357 Sema &S, TemplateDecl *TD,
3358 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3359 TemplateDeductionInfo &Info) {
3360 // Unevaluated SFINAE context.
3361 EnterExpressionEvaluationContext Unevaluated(
3362 S, Sema::ExpressionEvaluationContext::Unevaluated);
3363 Sema::SFINAETrap Trap(S);
3365 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(TD));
3367 // C++ [temp.deduct.type]p2:
3368 // [...] or if any template argument remains neither deduced nor
3369 // explicitly specified, template argument deduction fails.
3370 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3371 if (auto Result = ConvertDeducedTemplateArguments(
3372 S, TD, /*IsPartialOrdering=*/false, Deduced, Info, SugaredBuilder,
3373 CanonicalBuilder);
3374 Result != TemplateDeductionResult::Success)
3375 return Result;
3377 if (Trap.hasErrorOccurred())
3378 return TemplateDeductionResult::SubstitutionFailure;
3380 if (auto Result = CheckDeducedArgumentConstraints(S, TD, SugaredBuilder,
3381 CanonicalBuilder, Info);
3382 Result != TemplateDeductionResult::Success)
3383 return Result;
3385 return TemplateDeductionResult::Success;
3388 /// Perform template argument deduction to determine whether the given template
3389 /// arguments match the given class or variable template partial specialization
3390 /// per C++ [temp.class.spec.match].
3391 template <typename T>
3392 static std::enable_if_t<IsPartialSpecialization<T>::value,
3393 TemplateDeductionResult>
3394 DeduceTemplateArguments(Sema &S, T *Partial,
3395 ArrayRef<TemplateArgument> TemplateArgs,
3396 TemplateDeductionInfo &Info) {
3397 if (Partial->isInvalidDecl())
3398 return TemplateDeductionResult::Invalid;
3400 // C++ [temp.class.spec.match]p2:
3401 // A partial specialization matches a given actual template
3402 // argument list if the template arguments of the partial
3403 // specialization can be deduced from the actual template argument
3404 // list (14.8.2).
3406 // Unevaluated SFINAE context.
3407 EnterExpressionEvaluationContext Unevaluated(
3408 S, Sema::ExpressionEvaluationContext::Unevaluated);
3409 Sema::SFINAETrap Trap(S);
3411 // This deduction has no relation to any outer instantiation we might be
3412 // performing.
3413 LocalInstantiationScope InstantiationScope(S);
3415 SmallVector<DeducedTemplateArgument, 4> Deduced;
3416 Deduced.resize(Partial->getTemplateParameters()->size());
3417 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
3418 S, Partial->getTemplateParameters(),
3419 Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3420 /*NumberOfArgumentsMustMatch=*/false, /*PartialOrdering=*/false,
3421 PackFold::ParameterToArgument,
3422 /*HasDeducedAnyParam=*/nullptr);
3423 Result != TemplateDeductionResult::Success)
3424 return Result;
3426 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3427 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
3428 Info);
3429 if (Inst.isInvalid())
3430 return TemplateDeductionResult::InstantiationDepth;
3432 if (Trap.hasErrorOccurred())
3433 return TemplateDeductionResult::SubstitutionFailure;
3435 TemplateDeductionResult Result;
3436 S.runWithSufficientStackSpace(Info.getLocation(), [&] {
3437 Result = ::FinishTemplateArgumentDeduction(S, Partial,
3438 /*IsPartialOrdering=*/false,
3439 TemplateArgs, Deduced, Info);
3441 return Result;
3444 TemplateDeductionResult
3445 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
3446 ArrayRef<TemplateArgument> TemplateArgs,
3447 TemplateDeductionInfo &Info) {
3448 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3450 TemplateDeductionResult
3451 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
3452 ArrayRef<TemplateArgument> TemplateArgs,
3453 TemplateDeductionInfo &Info) {
3454 return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3457 TemplateDeductionResult
3458 Sema::DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
3459 sema::TemplateDeductionInfo &Info) {
3460 if (TD->isInvalidDecl())
3461 return TemplateDeductionResult::Invalid;
3463 QualType PType;
3464 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3465 // Use the InjectedClassNameType.
3466 PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3467 } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3468 PType = AliasTemplate->getTemplatedDecl()->getUnderlyingType();
3469 } else {
3470 assert(false && "Expected a class or alias template");
3473 // Unevaluated SFINAE context.
3474 EnterExpressionEvaluationContext Unevaluated(
3475 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3476 SFINAETrap Trap(*this);
3478 // This deduction has no relation to any outer instantiation we might be
3479 // performing.
3480 LocalInstantiationScope InstantiationScope(*this);
3482 SmallVector<DeducedTemplateArgument> Deduced(
3483 TD->getTemplateParameters()->size());
3484 SmallVector<TemplateArgument> PArgs = {TemplateArgument(PType)};
3485 SmallVector<TemplateArgument> AArgs = {TemplateArgument(FromType)};
3486 if (auto DeducedResult = DeduceTemplateArguments(
3487 TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3488 DeducedResult != TemplateDeductionResult::Success) {
3489 return DeducedResult;
3492 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3493 InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
3494 if (Inst.isInvalid())
3495 return TemplateDeductionResult::InstantiationDepth;
3497 if (Trap.hasErrorOccurred())
3498 return TemplateDeductionResult::SubstitutionFailure;
3500 TemplateDeductionResult Result;
3501 runWithSufficientStackSpace(Info.getLocation(), [&] {
3502 Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
3504 return Result;
3507 /// Determine whether the given type T is a simple-template-id type.
3508 static bool isSimpleTemplateIdType(QualType T) {
3509 if (const TemplateSpecializationType *Spec
3510 = T->getAs<TemplateSpecializationType>())
3511 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3513 // C++17 [temp.local]p2:
3514 // the injected-class-name [...] is equivalent to the template-name followed
3515 // by the template-arguments of the class template specialization or partial
3516 // specialization enclosed in <>
3517 // ... which means it's equivalent to a simple-template-id.
3519 // This only arises during class template argument deduction for a copy
3520 // deduction candidate, where it permits slicing.
3521 if (T->getAs<InjectedClassNameType>())
3522 return true;
3524 return false;
3527 TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments(
3528 FunctionTemplateDecl *FunctionTemplate,
3529 TemplateArgumentListInfo &ExplicitTemplateArgs,
3530 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3531 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
3532 TemplateDeductionInfo &Info) {
3533 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3534 TemplateParameterList *TemplateParams
3535 = FunctionTemplate->getTemplateParameters();
3537 if (ExplicitTemplateArgs.size() == 0) {
3538 // No arguments to substitute; just copy over the parameter types and
3539 // fill in the function type.
3540 for (auto *P : Function->parameters())
3541 ParamTypes.push_back(P->getType());
3543 if (FunctionType)
3544 *FunctionType = Function->getType();
3545 return TemplateDeductionResult::Success;
3548 // Unevaluated SFINAE context.
3549 EnterExpressionEvaluationContext Unevaluated(
3550 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3551 SFINAETrap Trap(*this);
3553 // C++ [temp.arg.explicit]p3:
3554 // Template arguments that are present shall be specified in the
3555 // declaration order of their corresponding template-parameters. The
3556 // template argument list shall not specify more template-arguments than
3557 // there are corresponding template-parameters.
3558 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3560 // Enter a new template instantiation context where we check the
3561 // explicitly-specified template arguments against this function template,
3562 // and then substitute them into the function parameter types.
3563 SmallVector<TemplateArgument, 4> DeducedArgs;
3564 InstantiatingTemplate Inst(
3565 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3566 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
3567 if (Inst.isInvalid())
3568 return TemplateDeductionResult::InstantiationDepth;
3570 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
3571 ExplicitTemplateArgs, /*DefaultArgs=*/{}, true,
3572 SugaredBuilder, CanonicalBuilder,
3573 /*UpdateArgsWithConversions=*/false) ||
3574 Trap.hasErrorOccurred()) {
3575 unsigned Index = SugaredBuilder.size();
3576 if (Index >= TemplateParams->size())
3577 return TemplateDeductionResult::SubstitutionFailure;
3578 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3579 return TemplateDeductionResult::InvalidExplicitArguments;
3582 // Form the template argument list from the explicitly-specified
3583 // template arguments.
3584 TemplateArgumentList *SugaredExplicitArgumentList =
3585 TemplateArgumentList::CreateCopy(Context, SugaredBuilder);
3586 TemplateArgumentList *CanonicalExplicitArgumentList =
3587 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3588 Info.setExplicitArgs(SugaredExplicitArgumentList,
3589 CanonicalExplicitArgumentList);
3591 // Template argument deduction and the final substitution should be
3592 // done in the context of the templated declaration. Explicit
3593 // argument substitution, on the other hand, needs to happen in the
3594 // calling context.
3595 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3597 // If we deduced template arguments for a template parameter pack,
3598 // note that the template argument pack is partially substituted and record
3599 // the explicit template arguments. They'll be used as part of deduction
3600 // for this template parameter pack.
3601 unsigned PartiallySubstitutedPackIndex = -1u;
3602 if (!SugaredBuilder.empty()) {
3603 const TemplateArgument &Arg = SugaredBuilder.back();
3604 if (Arg.getKind() == TemplateArgument::Pack) {
3605 auto *Param = TemplateParams->getParam(SugaredBuilder.size() - 1);
3606 // If this is a fully-saturated fixed-size pack, it should be
3607 // fully-substituted, not partially-substituted.
3608 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3609 if (!Expansions || Arg.pack_size() < *Expansions) {
3610 PartiallySubstitutedPackIndex = SugaredBuilder.size() - 1;
3611 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3612 Param, Arg.pack_begin(), Arg.pack_size());
3617 const FunctionProtoType *Proto
3618 = Function->getType()->getAs<FunctionProtoType>();
3619 assert(Proto && "Function template does not have a prototype?");
3621 // Isolate our substituted parameters from our caller.
3622 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3624 ExtParameterInfoBuilder ExtParamInfos;
3626 MultiLevelTemplateArgumentList MLTAL(FunctionTemplate,
3627 SugaredExplicitArgumentList->asArray(),
3628 /*Final=*/true);
3630 // Instantiate the types of each of the function parameters given the
3631 // explicitly-specified template arguments. If the function has a trailing
3632 // return type, substitute it after the arguments to ensure we substitute
3633 // in lexical order.
3634 if (Proto->hasTrailingReturn()) {
3635 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3636 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3637 /*params=*/nullptr, ExtParamInfos))
3638 return TemplateDeductionResult::SubstitutionFailure;
3641 // Instantiate the return type.
3642 QualType ResultType;
3644 // C++11 [expr.prim.general]p3:
3645 // If a declaration declares a member function or member function
3646 // template of a class X, the expression this is a prvalue of type
3647 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3648 // and the end of the function-definition, member-declarator, or
3649 // declarator.
3650 Qualifiers ThisTypeQuals;
3651 CXXRecordDecl *ThisContext = nullptr;
3652 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3653 ThisContext = Method->getParent();
3654 ThisTypeQuals = Method->getMethodQualifiers();
3657 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3658 getLangOpts().CPlusPlus11);
3660 ResultType =
3661 SubstType(Proto->getReturnType(), MLTAL,
3662 Function->getTypeSpecStartLoc(), Function->getDeclName());
3663 if (ResultType.isNull() || Trap.hasErrorOccurred())
3664 return TemplateDeductionResult::SubstitutionFailure;
3665 // CUDA: Kernel function must have 'void' return type.
3666 if (getLangOpts().CUDA)
3667 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3668 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3669 << Function->getType() << Function->getSourceRange();
3670 return TemplateDeductionResult::SubstitutionFailure;
3674 // Instantiate the types of each of the function parameters given the
3675 // explicitly-specified template arguments if we didn't do so earlier.
3676 if (!Proto->hasTrailingReturn() &&
3677 SubstParmTypes(Function->getLocation(), Function->parameters(),
3678 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3679 /*params*/ nullptr, ExtParamInfos))
3680 return TemplateDeductionResult::SubstitutionFailure;
3682 if (FunctionType) {
3683 auto EPI = Proto->getExtProtoInfo();
3684 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3685 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3686 Function->getLocation(),
3687 Function->getDeclName(),
3688 EPI);
3689 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3690 return TemplateDeductionResult::SubstitutionFailure;
3693 // C++ [temp.arg.explicit]p2:
3694 // Trailing template arguments that can be deduced (14.8.2) may be
3695 // omitted from the list of explicit template-arguments. If all of the
3696 // template arguments can be deduced, they may all be omitted; in this
3697 // case, the empty template argument list <> itself may also be omitted.
3699 // Take all of the explicitly-specified arguments and put them into
3700 // the set of deduced template arguments. The partially-substituted
3701 // parameter pack, however, will be set to NULL since the deduction
3702 // mechanism handles the partially-substituted argument pack directly.
3703 Deduced.reserve(TemplateParams->size());
3704 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3705 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3706 if (I == PartiallySubstitutedPackIndex)
3707 Deduced.push_back(DeducedTemplateArgument());
3708 else
3709 Deduced.push_back(Arg);
3712 return TemplateDeductionResult::Success;
3715 /// Check whether the deduced argument type for a call to a function
3716 /// template matches the actual argument type per C++ [temp.deduct.call]p4.
3717 static TemplateDeductionResult
3718 CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3719 Sema::OriginalCallArg OriginalArg,
3720 QualType DeducedA) {
3721 ASTContext &Context = S.Context;
3723 auto Failed = [&]() -> TemplateDeductionResult {
3724 Info.FirstArg = TemplateArgument(DeducedA);
3725 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3726 Info.CallArgIndex = OriginalArg.ArgIdx;
3727 return OriginalArg.DecomposedParam
3728 ? TemplateDeductionResult::DeducedMismatchNested
3729 : TemplateDeductionResult::DeducedMismatch;
3732 QualType A = OriginalArg.OriginalArgType;
3733 QualType OriginalParamType = OriginalArg.OriginalParamType;
3735 // Check for type equality (top-level cv-qualifiers are ignored).
3736 if (Context.hasSameUnqualifiedType(A, DeducedA))
3737 return TemplateDeductionResult::Success;
3739 // Strip off references on the argument types; they aren't needed for
3740 // the following checks.
3741 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3742 DeducedA = DeducedARef->getPointeeType();
3743 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3744 A = ARef->getPointeeType();
3746 // C++ [temp.deduct.call]p4:
3747 // [...] However, there are three cases that allow a difference:
3748 // - If the original P is a reference type, the deduced A (i.e., the
3749 // type referred to by the reference) can be more cv-qualified than
3750 // the transformed A.
3751 if (const ReferenceType *OriginalParamRef
3752 = OriginalParamType->getAs<ReferenceType>()) {
3753 // We don't want to keep the reference around any more.
3754 OriginalParamType = OriginalParamRef->getPointeeType();
3756 // FIXME: Resolve core issue (no number yet): if the original P is a
3757 // reference type and the transformed A is function type "noexcept F",
3758 // the deduced A can be F.
3759 QualType Tmp;
3760 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3761 return TemplateDeductionResult::Success;
3763 Qualifiers AQuals = A.getQualifiers();
3764 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3766 // Under Objective-C++ ARC, the deduced type may have implicitly
3767 // been given strong or (when dealing with a const reference)
3768 // unsafe_unretained lifetime. If so, update the original
3769 // qualifiers to include this lifetime.
3770 if (S.getLangOpts().ObjCAutoRefCount &&
3771 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3772 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3773 (DeducedAQuals.hasConst() &&
3774 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3775 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3778 if (AQuals == DeducedAQuals) {
3779 // Qualifiers match; there's nothing to do.
3780 } else if (!DeducedAQuals.compatiblyIncludes(AQuals, S.getASTContext())) {
3781 return Failed();
3782 } else {
3783 // Qualifiers are compatible, so have the argument type adopt the
3784 // deduced argument type's qualifiers as if we had performed the
3785 // qualification conversion.
3786 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3790 // - The transformed A can be another pointer or pointer to member
3791 // type that can be converted to the deduced A via a function pointer
3792 // conversion and/or a qualification conversion.
3794 // Also allow conversions which merely strip __attribute__((noreturn)) from
3795 // function types (recursively).
3796 bool ObjCLifetimeConversion = false;
3797 QualType ResultTy;
3798 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3799 (S.IsQualificationConversion(A, DeducedA, false,
3800 ObjCLifetimeConversion) ||
3801 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3802 return TemplateDeductionResult::Success;
3804 // - If P is a class and P has the form simple-template-id, then the
3805 // transformed A can be a derived class of the deduced A. [...]
3806 // [...] Likewise, if P is a pointer to a class of the form
3807 // simple-template-id, the transformed A can be a pointer to a
3808 // derived class pointed to by the deduced A.
3809 if (const PointerType *OriginalParamPtr
3810 = OriginalParamType->getAs<PointerType>()) {
3811 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3812 if (const PointerType *APtr = A->getAs<PointerType>()) {
3813 if (A->getPointeeType()->isRecordType()) {
3814 OriginalParamType = OriginalParamPtr->getPointeeType();
3815 DeducedA = DeducedAPtr->getPointeeType();
3816 A = APtr->getPointeeType();
3822 if (Context.hasSameUnqualifiedType(A, DeducedA))
3823 return TemplateDeductionResult::Success;
3825 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3826 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3827 return TemplateDeductionResult::Success;
3829 return Failed();
3832 /// Find the pack index for a particular parameter index in an instantiation of
3833 /// a function template with specific arguments.
3835 /// \return The pack index for whichever pack produced this parameter, or -1
3836 /// if this was not produced by a parameter. Intended to be used as the
3837 /// ArgumentPackSubstitutionIndex for further substitutions.
3838 // FIXME: We should track this in OriginalCallArgs so we don't need to
3839 // reconstruct it here.
3840 static unsigned getPackIndexForParam(Sema &S,
3841 FunctionTemplateDecl *FunctionTemplate,
3842 const MultiLevelTemplateArgumentList &Args,
3843 unsigned ParamIdx) {
3844 unsigned Idx = 0;
3845 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3846 if (PD->isParameterPack()) {
3847 unsigned NumExpansions =
3848 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3849 if (Idx + NumExpansions > ParamIdx)
3850 return ParamIdx - Idx;
3851 Idx += NumExpansions;
3852 } else {
3853 if (Idx == ParamIdx)
3854 return -1; // Not a pack expansion
3855 ++Idx;
3859 llvm_unreachable("parameter index would not be produced from template");
3862 // if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
3863 // we'll try to instantiate and update its explicit specifier after constraint
3864 // checking.
3865 static TemplateDeductionResult instantiateExplicitSpecifierDeferred(
3866 Sema &S, FunctionDecl *Specialization,
3867 const MultiLevelTemplateArgumentList &SubstArgs,
3868 TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
3869 ArrayRef<TemplateArgument> DeducedArgs) {
3870 auto GetExplicitSpecifier = [](FunctionDecl *D) {
3871 return isa<CXXConstructorDecl>(D)
3872 ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
3873 : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
3875 auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
3876 isa<CXXConstructorDecl>(D)
3877 ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
3878 : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
3881 ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
3882 Expr *ExplicitExpr = ES.getExpr();
3883 if (!ExplicitExpr)
3884 return TemplateDeductionResult::Success;
3885 if (!ExplicitExpr->isValueDependent())
3886 return TemplateDeductionResult::Success;
3888 Sema::InstantiatingTemplate Inst(
3889 S, Info.getLocation(), FunctionTemplate, DeducedArgs,
3890 Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
3891 if (Inst.isInvalid())
3892 return TemplateDeductionResult::InstantiationDepth;
3893 Sema::SFINAETrap Trap(S);
3894 const ExplicitSpecifier InstantiatedES =
3895 S.instantiateExplicitSpecifier(SubstArgs, ES);
3896 if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
3897 Specialization->setInvalidDecl(true);
3898 return TemplateDeductionResult::SubstitutionFailure;
3900 SetExplicitSpecifier(Specialization, InstantiatedES);
3901 return TemplateDeductionResult::Success;
3904 TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3905 FunctionTemplateDecl *FunctionTemplate,
3906 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3907 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3908 TemplateDeductionInfo &Info,
3909 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3910 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3911 // Unevaluated SFINAE context.
3912 EnterExpressionEvaluationContext Unevaluated(
3913 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3914 SFINAETrap Trap(*this);
3916 // Enter a new template instantiation context while we instantiate the
3917 // actual function declaration.
3918 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3919 InstantiatingTemplate Inst(
3920 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3921 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
3922 if (Inst.isInvalid())
3923 return TemplateDeductionResult::InstantiationDepth;
3925 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3927 // C++ [temp.deduct.type]p2:
3928 // [...] or if any template argument remains neither deduced nor
3929 // explicitly specified, template argument deduction fails.
3930 bool IsIncomplete = false;
3931 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3932 if (auto Result = ConvertDeducedTemplateArguments(
3933 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3934 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3935 NumExplicitlySpecified, PartialOverloading ? &IsIncomplete : nullptr);
3936 Result != TemplateDeductionResult::Success)
3937 return Result;
3939 // C++ [temp.deduct.call]p10: [DR1391]
3940 // If deduction succeeds for all parameters that contain
3941 // template-parameters that participate in template argument deduction,
3942 // and all template arguments are explicitly specified, deduced, or
3943 // obtained from default template arguments, remaining parameters are then
3944 // compared with the corresponding arguments. For each remaining parameter
3945 // P with a type that was non-dependent before substitution of any
3946 // explicitly-specified template arguments, if the corresponding argument
3947 // A cannot be implicitly converted to P, deduction fails.
3948 if (CheckNonDependent())
3949 return TemplateDeductionResult::NonDependentConversionFailure;
3951 // Form the template argument list from the deduced template arguments.
3952 TemplateArgumentList *SugaredDeducedArgumentList =
3953 TemplateArgumentList::CreateCopy(Context, SugaredBuilder);
3954 TemplateArgumentList *CanonicalDeducedArgumentList =
3955 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3956 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3958 // Substitute the deduced template arguments into the function template
3959 // declaration to produce the function template specialization.
3960 DeclContext *Owner = FunctionTemplate->getDeclContext();
3961 if (FunctionTemplate->getFriendObjectKind())
3962 Owner = FunctionTemplate->getLexicalDeclContext();
3963 FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
3964 // additional check for inline friend,
3965 // ```
3966 // template <class F1> int foo(F1 X);
3967 // template <int A1> struct A {
3968 // template <class F1> friend int foo(F1 X) { return A1; }
3969 // };
3970 // template struct A<1>;
3971 // int a = foo(1.0);
3972 // ```
3973 const FunctionDecl *FDFriend;
3974 if (FD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None &&
3975 FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
3976 FDFriend->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None) {
3977 FD = const_cast<FunctionDecl *>(FDFriend);
3978 Owner = FD->getLexicalDeclContext();
3980 MultiLevelTemplateArgumentList SubstArgs(
3981 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3982 /*Final=*/false);
3983 Specialization = cast_or_null<FunctionDecl>(
3984 SubstDecl(FD, Owner, SubstArgs));
3985 if (!Specialization || Specialization->isInvalidDecl())
3986 return TemplateDeductionResult::SubstitutionFailure;
3988 assert(isSameDeclaration(Specialization->getPrimaryTemplate(),
3989 FunctionTemplate));
3991 // If the template argument list is owned by the function template
3992 // specialization, release it.
3993 if (Specialization->getTemplateSpecializationArgs() ==
3994 CanonicalDeducedArgumentList &&
3995 !Trap.hasErrorOccurred())
3996 Info.takeCanonical();
3998 // There may have been an error that did not prevent us from constructing a
3999 // declaration. Mark the declaration invalid and return with a substitution
4000 // failure.
4001 if (Trap.hasErrorOccurred()) {
4002 Specialization->setInvalidDecl(true);
4003 return TemplateDeductionResult::SubstitutionFailure;
4006 // C++2a [temp.deduct]p5
4007 // [...] When all template arguments have been deduced [...] all uses of
4008 // template parameters [...] are replaced with the corresponding deduced
4009 // or default argument values.
4010 // [...] If the function template has associated constraints
4011 // ([temp.constr.decl]), those constraints are checked for satisfaction
4012 // ([temp.constr.constr]). If the constraints are not satisfied, type
4013 // deduction fails.
4014 if (!IsIncomplete) {
4015 if (CheckInstantiatedFunctionTemplateConstraints(
4016 Info.getLocation(), Specialization, CanonicalBuilder,
4017 Info.AssociatedConstraintsSatisfaction))
4018 return TemplateDeductionResult::MiscellaneousDeductionFailure;
4020 if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
4021 Info.reset(Info.takeSugared(),
4022 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
4023 return TemplateDeductionResult::ConstraintsNotSatisfied;
4027 // We skipped the instantiation of the explicit-specifier during the
4028 // substitution of `FD` before. So, we try to instantiate it back if
4029 // `Specialization` is either a constructor or a conversion function.
4030 if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
4031 if (TemplateDeductionResult::Success !=
4032 instantiateExplicitSpecifierDeferred(*this, Specialization, SubstArgs,
4033 Info, FunctionTemplate,
4034 DeducedArgs)) {
4035 return TemplateDeductionResult::SubstitutionFailure;
4039 if (OriginalCallArgs) {
4040 // C++ [temp.deduct.call]p4:
4041 // In general, the deduction process attempts to find template argument
4042 // values that will make the deduced A identical to A (after the type A
4043 // is transformed as described above). [...]
4044 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
4045 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
4046 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
4048 auto ParamIdx = OriginalArg.ArgIdx;
4049 unsigned ExplicitOffset =
4050 Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
4051 if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
4052 // FIXME: This presumably means a pack ended up smaller than we
4053 // expected while deducing. Should this not result in deduction
4054 // failure? Can it even happen?
4055 continue;
4057 QualType DeducedA;
4058 if (!OriginalArg.DecomposedParam) {
4059 // P is one of the function parameters, just look up its substituted
4060 // type.
4061 DeducedA =
4062 Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
4063 } else {
4064 // P is a decomposed element of a parameter corresponding to a
4065 // braced-init-list argument. Substitute back into P to find the
4066 // deduced A.
4067 QualType &CacheEntry =
4068 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
4069 if (CacheEntry.isNull()) {
4070 ArgumentPackSubstitutionIndexRAII PackIndex(
4071 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
4072 ParamIdx));
4073 CacheEntry =
4074 SubstType(OriginalArg.OriginalParamType, SubstArgs,
4075 Specialization->getTypeSpecStartLoc(),
4076 Specialization->getDeclName());
4078 DeducedA = CacheEntry;
4081 if (auto TDK =
4082 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
4083 TDK != TemplateDeductionResult::Success)
4084 return TDK;
4088 // If we suppressed any diagnostics while performing template argument
4089 // deduction, and if we haven't already instantiated this declaration,
4090 // keep track of these diagnostics. They'll be emitted if this specialization
4091 // is actually used.
4092 if (Info.diag_begin() != Info.diag_end()) {
4093 auto [Pos, Inserted] =
4094 SuppressedDiagnostics.try_emplace(Specialization->getCanonicalDecl());
4095 if (Inserted)
4096 Pos->second.append(Info.diag_begin(), Info.diag_end());
4099 return TemplateDeductionResult::Success;
4102 /// Gets the type of a function for template-argument-deducton
4103 /// purposes when it's considered as part of an overload set.
4104 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
4105 FunctionDecl *Fn) {
4106 // We may need to deduce the return type of the function now.
4107 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
4108 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
4109 return {};
4111 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
4112 if (Method->isImplicitObjectMemberFunction()) {
4113 // An instance method that's referenced in a form that doesn't
4114 // look like a member pointer is just invalid.
4115 if (!R.HasFormOfMemberPointer)
4116 return {};
4118 return S.Context.getMemberPointerType(Fn->getType(),
4119 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
4122 if (!R.IsAddressOfOperand) return Fn->getType();
4123 return S.Context.getPointerType(Fn->getType());
4126 /// Apply the deduction rules for overload sets.
4128 /// \return the null type if this argument should be treated as an
4129 /// undeduced context
4130 static QualType
4131 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
4132 Expr *Arg, QualType ParamType,
4133 bool ParamWasReference,
4134 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4136 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
4138 OverloadExpr *Ovl = R.Expression;
4140 // C++0x [temp.deduct.call]p4
4141 unsigned TDF = 0;
4142 if (ParamWasReference)
4143 TDF |= TDF_ParamWithReferenceType;
4144 if (R.IsAddressOfOperand)
4145 TDF |= TDF_IgnoreQualifiers;
4147 // C++0x [temp.deduct.call]p6:
4148 // When P is a function type, pointer to function type, or pointer
4149 // to member function type:
4151 if (!ParamType->isFunctionType() &&
4152 !ParamType->isFunctionPointerType() &&
4153 !ParamType->isMemberFunctionPointerType()) {
4154 if (Ovl->hasExplicitTemplateArgs()) {
4155 // But we can still look for an explicit specialization.
4156 if (FunctionDecl *ExplicitSpec =
4157 S.ResolveSingleFunctionTemplateSpecialization(
4158 Ovl, /*Complain=*/false,
4159 /*FoundDeclAccessPair=*/nullptr, FailedTSC))
4160 return GetTypeOfFunction(S, R, ExplicitSpec);
4163 DeclAccessPair DAP;
4164 if (FunctionDecl *Viable =
4165 S.resolveAddressOfSingleOverloadCandidate(Arg, DAP))
4166 return GetTypeOfFunction(S, R, Viable);
4168 return {};
4171 // Gather the explicit template arguments, if any.
4172 TemplateArgumentListInfo ExplicitTemplateArgs;
4173 if (Ovl->hasExplicitTemplateArgs())
4174 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4175 QualType Match;
4176 for (UnresolvedSetIterator I = Ovl->decls_begin(),
4177 E = Ovl->decls_end(); I != E; ++I) {
4178 NamedDecl *D = (*I)->getUnderlyingDecl();
4180 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
4181 // - If the argument is an overload set containing one or more
4182 // function templates, the parameter is treated as a
4183 // non-deduced context.
4184 if (!Ovl->hasExplicitTemplateArgs())
4185 return {};
4187 // Otherwise, see if we can resolve a function type
4188 FunctionDecl *Specialization = nullptr;
4189 TemplateDeductionInfo Info(Ovl->getNameLoc());
4190 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4191 Specialization,
4192 Info) != TemplateDeductionResult::Success)
4193 continue;
4195 D = Specialization;
4198 FunctionDecl *Fn = cast<FunctionDecl>(D);
4199 QualType ArgType = GetTypeOfFunction(S, R, Fn);
4200 if (ArgType.isNull()) continue;
4202 // Function-to-pointer conversion.
4203 if (!ParamWasReference && ParamType->isPointerType() &&
4204 ArgType->isFunctionType())
4205 ArgType = S.Context.getPointerType(ArgType);
4207 // - If the argument is an overload set (not containing function
4208 // templates), trial argument deduction is attempted using each
4209 // of the members of the set. If deduction succeeds for only one
4210 // of the overload set members, that member is used as the
4211 // argument value for the deduction. If deduction succeeds for
4212 // more than one member of the overload set the parameter is
4213 // treated as a non-deduced context.
4215 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
4216 // Type deduction is done independently for each P/A pair, and
4217 // the deduced template argument values are then combined.
4218 // So we do not reject deductions which were made elsewhere.
4219 SmallVector<DeducedTemplateArgument, 8>
4220 Deduced(TemplateParams->size());
4221 TemplateDeductionInfo Info(Ovl->getNameLoc());
4222 TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch(
4223 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4224 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4225 /*HasDeducedAnyParam=*/nullptr);
4226 if (Result != TemplateDeductionResult::Success)
4227 continue;
4228 if (!Match.isNull())
4229 return {};
4230 Match = ArgType;
4233 return Match;
4236 /// Perform the adjustments to the parameter and argument types
4237 /// described in C++ [temp.deduct.call].
4239 /// \returns true if the caller should not attempt to perform any template
4240 /// argument deduction based on this P/A pair because the argument is an
4241 /// overloaded function set that could not be resolved.
4242 static bool AdjustFunctionParmAndArgTypesForDeduction(
4243 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4244 QualType &ParamType, QualType &ArgType,
4245 Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
4246 TemplateSpecCandidateSet *FailedTSC = nullptr) {
4247 // C++0x [temp.deduct.call]p3:
4248 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
4249 // are ignored for type deduction.
4250 if (ParamType.hasQualifiers())
4251 ParamType = ParamType.getUnqualifiedType();
4253 // [...] If P is a reference type, the type referred to by P is
4254 // used for type deduction.
4255 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
4256 if (ParamRefType)
4257 ParamType = ParamRefType->getPointeeType();
4259 // Overload sets usually make this parameter an undeduced context,
4260 // but there are sometimes special circumstances. Typically
4261 // involving a template-id-expr.
4262 if (ArgType == S.Context.OverloadTy) {
4263 assert(Arg && "expected a non-null arg expression");
4264 ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
4265 ParamRefType != nullptr, FailedTSC);
4266 if (ArgType.isNull())
4267 return true;
4270 if (ParamRefType) {
4271 // If the argument has incomplete array type, try to complete its type.
4272 if (ArgType->isIncompleteArrayType()) {
4273 assert(Arg && "expected a non-null arg expression");
4274 ArgType = S.getCompletedType(Arg);
4277 // C++1z [temp.deduct.call]p3:
4278 // If P is a forwarding reference and the argument is an lvalue, the type
4279 // "lvalue reference to A" is used in place of A for type deduction.
4280 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
4281 ArgClassification.isLValue()) {
4282 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4283 ArgType = S.Context.getAddrSpaceQualType(
4284 ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace());
4285 ArgType = S.Context.getLValueReferenceType(ArgType);
4287 } else {
4288 // C++ [temp.deduct.call]p2:
4289 // If P is not a reference type:
4290 // - If A is an array type, the pointer type produced by the
4291 // array-to-pointer standard conversion (4.2) is used in place of
4292 // A for type deduction; otherwise,
4293 // - If A is a function type, the pointer type produced by the
4294 // function-to-pointer standard conversion (4.3) is used in place
4295 // of A for type deduction; otherwise,
4296 if (ArgType->canDecayToPointerType())
4297 ArgType = S.Context.getDecayedType(ArgType);
4298 else {
4299 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
4300 // type are ignored for type deduction.
4301 ArgType = ArgType.getUnqualifiedType();
4305 // C++0x [temp.deduct.call]p4:
4306 // In general, the deduction process attempts to find template argument
4307 // values that will make the deduced A identical to A (after the type A
4308 // is transformed as described above). [...]
4309 TDF = TDF_SkipNonDependent;
4311 // - If the original P is a reference type, the deduced A (i.e., the
4312 // type referred to by the reference) can be more cv-qualified than
4313 // the transformed A.
4314 if (ParamRefType)
4315 TDF |= TDF_ParamWithReferenceType;
4316 // - The transformed A can be another pointer or pointer to member
4317 // type that can be converted to the deduced A via a qualification
4318 // conversion (4.4).
4319 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
4320 ArgType->isObjCObjectPointerType())
4321 TDF |= TDF_IgnoreQualifiers;
4322 // - If P is a class and P has the form simple-template-id, then the
4323 // transformed A can be a derived class of the deduced A. Likewise,
4324 // if P is a pointer to a class of the form simple-template-id, the
4325 // transformed A can be a pointer to a derived class pointed to by
4326 // the deduced A.
4327 if (isSimpleTemplateIdType(ParamType) ||
4328 (isa<PointerType>(ParamType) &&
4329 isSimpleTemplateIdType(
4330 ParamType->castAs<PointerType>()->getPointeeType())))
4331 TDF |= TDF_DerivedClass;
4333 return false;
4336 static bool
4337 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
4338 QualType T);
4340 static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
4341 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4342 QualType ParamType, QualType ArgType,
4343 Expr::Classification ArgClassification, Expr *Arg,
4344 TemplateDeductionInfo &Info,
4345 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4346 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
4347 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4348 TemplateSpecCandidateSet *FailedTSC = nullptr);
4350 /// Attempt template argument deduction from an initializer list
4351 /// deemed to be an argument in a function call.
4352 static TemplateDeductionResult DeduceFromInitializerList(
4353 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
4354 InitListExpr *ILE, TemplateDeductionInfo &Info,
4355 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4356 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
4357 unsigned TDF) {
4358 // C++ [temp.deduct.call]p1: (CWG 1591)
4359 // If removing references and cv-qualifiers from P gives
4360 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
4361 // a non-empty initializer list, then deduction is performed instead for
4362 // each element of the initializer list, taking P0 as a function template
4363 // parameter type and the initializer element as its argument
4365 // We've already removed references and cv-qualifiers here.
4366 if (!ILE->getNumInits())
4367 return TemplateDeductionResult::Success;
4369 QualType ElTy;
4370 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
4371 if (ArrTy)
4372 ElTy = ArrTy->getElementType();
4373 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
4374 // Otherwise, an initializer list argument causes the parameter to be
4375 // considered a non-deduced context
4376 return TemplateDeductionResult::Success;
4379 // Resolving a core issue: a braced-init-list containing any designators is
4380 // a non-deduced context.
4381 for (Expr *E : ILE->inits())
4382 if (isa<DesignatedInitExpr>(E))
4383 return TemplateDeductionResult::Success;
4385 // Deduction only needs to be done for dependent types.
4386 if (ElTy->isDependentType()) {
4387 for (Expr *E : ILE->inits()) {
4388 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
4389 S, TemplateParams, 0, ElTy, E->getType(),
4390 E->Classify(S.getASTContext()), E, Info, Deduced,
4391 OriginalCallArgs, true, ArgIdx, TDF);
4392 Result != TemplateDeductionResult::Success)
4393 return Result;
4397 // in the P0[N] case, if N is a non-type template parameter, N is deduced
4398 // from the length of the initializer list.
4399 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
4400 // Determine the array bound is something we can deduce.
4401 if (const NonTypeTemplateParmDecl *NTTP =
4402 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
4403 // We can perform template argument deduction for the given non-type
4404 // template parameter.
4405 // C++ [temp.deduct.type]p13:
4406 // The type of N in the type T[N] is std::size_t.
4407 QualType T = S.Context.getSizeType();
4408 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
4409 if (auto Result = DeduceNonTypeTemplateArgument(
4410 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4411 /*ArrayBound=*/true, Info, /*PartialOrdering=*/false, Deduced,
4412 /*HasDeducedAnyParam=*/nullptr);
4413 Result != TemplateDeductionResult::Success)
4414 return Result;
4418 return TemplateDeductionResult::Success;
4421 /// Perform template argument deduction per [temp.deduct.call] for a
4422 /// single parameter / argument pair.
4423 static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
4424 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4425 QualType ParamType, QualType ArgType,
4426 Expr::Classification ArgClassification, Expr *Arg,
4427 TemplateDeductionInfo &Info,
4428 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4429 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
4430 bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
4431 TemplateSpecCandidateSet *FailedTSC) {
4433 QualType OrigParamType = ParamType;
4435 // If P is a reference type [...]
4436 // If P is a cv-qualified type [...]
4437 if (AdjustFunctionParmAndArgTypesForDeduction(
4438 S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
4439 ArgClassification, Arg, TDF, FailedTSC))
4440 return TemplateDeductionResult::Success;
4442 // If [...] the argument is a non-empty initializer list [...]
4443 if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
4444 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4445 Deduced, OriginalCallArgs, ArgIdx, TDF);
4447 // [...] the deduction process attempts to find template argument values
4448 // that will make the deduced A identical to A
4450 // Keep track of the argument type and corresponding parameter index,
4451 // so we can check for compatibility between the deduced A and A.
4452 if (Arg)
4453 OriginalCallArgs.push_back(
4454 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4455 return DeduceTemplateArgumentsByTypeMatch(
4456 S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF,
4457 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4458 /*HasDeducedAnyParam=*/nullptr);
4461 TemplateDeductionResult Sema::DeduceTemplateArguments(
4462 FunctionTemplateDecl *FunctionTemplate,
4463 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4464 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4465 bool PartialOverloading, bool AggregateDeductionCandidate,
4466 QualType ObjectType, Expr::Classification ObjectClassification,
4467 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4468 if (FunctionTemplate->isInvalidDecl())
4469 return TemplateDeductionResult::Invalid;
4471 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4472 unsigned NumParams = Function->getNumParams();
4473 bool HasExplicitObject = false;
4474 int ExplicitObjectOffset = 0;
4475 if (Function->hasCXXExplicitFunctionObjectParameter()) {
4476 HasExplicitObject = true;
4477 ExplicitObjectOffset = 1;
4480 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4482 // C++ [temp.deduct.call]p1:
4483 // Template argument deduction is done by comparing each function template
4484 // parameter type (call it P) with the type of the corresponding argument
4485 // of the call (call it A) as described below.
4486 if (Args.size() < Function->getMinRequiredExplicitArguments() &&
4487 !PartialOverloading)
4488 return TemplateDeductionResult::TooFewArguments;
4489 else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
4490 PartialOverloading)) {
4491 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4492 if (Proto->isTemplateVariadic())
4493 /* Do nothing */;
4494 else if (!Proto->isVariadic())
4495 return TemplateDeductionResult::TooManyArguments;
4498 // The types of the parameters from which we will perform template argument
4499 // deduction.
4500 LocalInstantiationScope InstScope(*this);
4501 TemplateParameterList *TemplateParams
4502 = FunctionTemplate->getTemplateParameters();
4503 SmallVector<DeducedTemplateArgument, 4> Deduced;
4504 SmallVector<QualType, 8> ParamTypes;
4505 unsigned NumExplicitlySpecified = 0;
4506 if (ExplicitTemplateArgs) {
4507 TemplateDeductionResult Result;
4508 runWithSufficientStackSpace(Info.getLocation(), [&] {
4509 Result = SubstituteExplicitTemplateArguments(
4510 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4511 Info);
4513 if (Result != TemplateDeductionResult::Success)
4514 return Result;
4516 NumExplicitlySpecified = Deduced.size();
4517 } else {
4518 // Just fill in the parameter types from the function declaration.
4519 for (unsigned I = 0; I != NumParams; ++I)
4520 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4523 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4525 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4526 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4527 bool ExplicitObjectArgument) {
4528 // C++ [demp.deduct.call]p1: (DR1391)
4529 // Template argument deduction is done by comparing each function template
4530 // parameter that contains template-parameters that participate in
4531 // template argument deduction ...
4532 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4533 return TemplateDeductionResult::Success;
4535 if (ExplicitObjectArgument) {
4536 // ... with the type of the corresponding argument
4537 return DeduceTemplateArgumentsFromCallArgument(
4538 *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
4539 ObjectClassification,
4540 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4541 /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
4544 // ... with the type of the corresponding argument
4545 return DeduceTemplateArgumentsFromCallArgument(
4546 *this, TemplateParams, FirstInnerIndex, ParamType,
4547 Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
4548 Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
4549 ArgIdx, /*TDF*/ 0);
4552 // Deduce template arguments from the function parameters.
4553 Deduced.resize(TemplateParams->size());
4554 SmallVector<QualType, 8> ParamTypesForArgChecking;
4555 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4556 ParamIdx != NumParamTypes; ++ParamIdx) {
4557 QualType ParamType = ParamTypes[ParamIdx];
4559 const PackExpansionType *ParamExpansion =
4560 dyn_cast<PackExpansionType>(ParamType);
4561 if (!ParamExpansion) {
4562 // Simple case: matching a function parameter to a function argument.
4563 if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
4564 break;
4566 ParamTypesForArgChecking.push_back(ParamType);
4568 if (ParamIdx == 0 && HasExplicitObject) {
4569 if (ObjectType.isNull())
4570 return TemplateDeductionResult::InvalidExplicitArguments;
4572 if (auto Result = DeduceCallArgument(ParamType, 0,
4573 /*ExplicitObjectArgument=*/true);
4574 Result != TemplateDeductionResult::Success)
4575 return Result;
4576 continue;
4579 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4580 /*ExplicitObjectArgument=*/false);
4581 Result != TemplateDeductionResult::Success)
4582 return Result;
4584 continue;
4587 bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
4589 QualType ParamPattern = ParamExpansion->getPattern();
4590 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4591 ParamPattern,
4592 AggregateDeductionCandidate && IsTrailingPack);
4594 // C++0x [temp.deduct.call]p1:
4595 // For a function parameter pack that occurs at the end of the
4596 // parameter-declaration-list, the type A of each remaining argument of
4597 // the call is compared with the type P of the declarator-id of the
4598 // function parameter pack. Each comparison deduces template arguments
4599 // for subsequent positions in the template parameter packs expanded by
4600 // the function parameter pack. When a function parameter pack appears
4601 // in a non-deduced context [not at the end of the list], the type of
4602 // that parameter pack is never deduced.
4604 // FIXME: The above rule allows the size of the parameter pack to change
4605 // after we skip it (in the non-deduced case). That makes no sense, so
4606 // we instead notionally deduce the pack against N arguments, where N is
4607 // the length of the explicitly-specified pack if it's expanded by the
4608 // parameter pack and 0 otherwise, and we treat each deduction as a
4609 // non-deduced context.
4610 if (IsTrailingPack || PackScope.hasFixedArity()) {
4611 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4612 PackScope.nextPackElement(), ++ArgIdx) {
4613 ParamTypesForArgChecking.push_back(ParamPattern);
4614 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4615 /*ExplicitObjectArgument=*/false);
4616 Result != TemplateDeductionResult::Success)
4617 return Result;
4619 } else {
4620 // If the parameter type contains an explicitly-specified pack that we
4621 // could not expand, skip the number of parameters notionally created
4622 // by the expansion.
4623 std::optional<unsigned> NumExpansions =
4624 ParamExpansion->getNumExpansions();
4625 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4626 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4627 ++I, ++ArgIdx) {
4628 ParamTypesForArgChecking.push_back(ParamPattern);
4629 // FIXME: Should we add OriginalCallArgs for these? What if the
4630 // corresponding argument is a list?
4631 PackScope.nextPackElement();
4633 } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4634 PackScope.isDeducedFromEarlierParameter()) {
4635 // [temp.deduct.general#3]
4636 // When all template arguments have been deduced
4637 // or obtained from default template arguments, all uses of template
4638 // parameters in the template parameter list of the template are
4639 // replaced with the corresponding deduced or default argument values
4641 // If we have a trailing parameter pack, that has been deduced
4642 // previously we substitute the pack here in a similar fashion as
4643 // above with the trailing parameter packs. The main difference here is
4644 // that, in this case we are not processing all of the remaining
4645 // arguments. We are only process as many arguments as we have in
4646 // the already deduced parameter.
4647 std::optional<unsigned> ArgPosAfterSubstitution =
4648 PackScope.getSavedPackSizeIfAllEqual();
4649 if (!ArgPosAfterSubstitution)
4650 continue;
4652 unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4653 for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4654 ParamTypesForArgChecking.push_back(ParamPattern);
4655 if (auto Result =
4656 DeduceCallArgument(ParamPattern, ArgIdx,
4657 /*ExplicitObjectArgument=*/false);
4658 Result != TemplateDeductionResult::Success)
4659 return Result;
4661 PackScope.nextPackElement();
4666 // Build argument packs for each of the parameter packs expanded by this
4667 // pack expansion.
4668 if (auto Result = PackScope.finish();
4669 Result != TemplateDeductionResult::Success)
4670 return Result;
4673 // Capture the context in which the function call is made. This is the context
4674 // that is needed when the accessibility of template arguments is checked.
4675 DeclContext *CallingCtx = CurContext;
4677 TemplateDeductionResult Result;
4678 runWithSufficientStackSpace(Info.getLocation(), [&] {
4679 Result = FinishTemplateArgumentDeduction(
4680 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4681 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4682 ContextRAII SavedContext(*this, CallingCtx);
4683 return CheckNonDependent(ParamTypesForArgChecking);
4686 return Result;
4689 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
4690 QualType FunctionType,
4691 bool AdjustExceptionSpec) {
4692 if (ArgFunctionType.isNull())
4693 return ArgFunctionType;
4695 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4696 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4697 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4698 bool Rebuild = false;
4700 CallingConv CC = FunctionTypeP->getCallConv();
4701 if (EPI.ExtInfo.getCC() != CC) {
4702 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4703 Rebuild = true;
4706 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4707 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4708 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4709 Rebuild = true;
4712 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4713 ArgFunctionTypeP->hasExceptionSpec())) {
4714 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4715 Rebuild = true;
4718 if (!Rebuild)
4719 return ArgFunctionType;
4721 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4722 ArgFunctionTypeP->getParamTypes(), EPI);
4725 TemplateDeductionResult Sema::DeduceTemplateArguments(
4726 FunctionTemplateDecl *FunctionTemplate,
4727 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4728 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4729 bool IsAddressOfFunction) {
4730 if (FunctionTemplate->isInvalidDecl())
4731 return TemplateDeductionResult::Invalid;
4733 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4734 TemplateParameterList *TemplateParams
4735 = FunctionTemplate->getTemplateParameters();
4736 QualType FunctionType = Function->getType();
4738 // Substitute any explicit template arguments.
4739 LocalInstantiationScope InstScope(*this);
4740 SmallVector<DeducedTemplateArgument, 4> Deduced;
4741 unsigned NumExplicitlySpecified = 0;
4742 SmallVector<QualType, 4> ParamTypes;
4743 if (ExplicitTemplateArgs) {
4744 TemplateDeductionResult Result;
4745 runWithSufficientStackSpace(Info.getLocation(), [&] {
4746 Result = SubstituteExplicitTemplateArguments(
4747 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4748 &FunctionType, Info);
4750 if (Result != TemplateDeductionResult::Success)
4751 return Result;
4753 NumExplicitlySpecified = Deduced.size();
4756 // When taking the address of a function, we require convertibility of
4757 // the resulting function type. Otherwise, we allow arbitrary mismatches
4758 // of calling convention and noreturn.
4759 if (!IsAddressOfFunction)
4760 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4761 /*AdjustExceptionSpec*/false);
4763 // Unevaluated SFINAE context.
4764 EnterExpressionEvaluationContext Unevaluated(
4765 *this, Sema::ExpressionEvaluationContext::Unevaluated);
4766 SFINAETrap Trap(*this);
4768 Deduced.resize(TemplateParams->size());
4770 // If the function has a deduced return type, substitute it for a dependent
4771 // type so that we treat it as a non-deduced context in what follows.
4772 bool HasDeducedReturnType = false;
4773 if (getLangOpts().CPlusPlus14 &&
4774 Function->getReturnType()->getContainedAutoType()) {
4775 FunctionType = SubstAutoTypeDependent(FunctionType);
4776 HasDeducedReturnType = true;
4779 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4780 unsigned TDF =
4781 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
4782 // Deduce template arguments from the function type.
4783 if (TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch(
4784 *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4785 TDF, PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4786 /*HasDeducedAnyParam=*/nullptr);
4787 Result != TemplateDeductionResult::Success)
4788 return Result;
4791 TemplateDeductionResult Result;
4792 runWithSufficientStackSpace(Info.getLocation(), [&] {
4793 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4794 NumExplicitlySpecified,
4795 Specialization, Info);
4797 if (Result != TemplateDeductionResult::Success)
4798 return Result;
4800 // If the function has a deduced return type, deduce it now, so we can check
4801 // that the deduced function type matches the requested type.
4802 if (HasDeducedReturnType && IsAddressOfFunction &&
4803 Specialization->getReturnType()->isUndeducedType() &&
4804 DeduceReturnType(Specialization, Info.getLocation(), false))
4805 return TemplateDeductionResult::MiscellaneousDeductionFailure;
4807 // [C++26][expr.const]/p17
4808 // An expression or conversion is immediate-escalating if it is not initially
4809 // in an immediate function context and it is [...]
4810 // a potentially-evaluated id-expression that denotes an immediate function.
4811 if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
4812 Specialization->isImmediateEscalating() &&
4813 parentEvaluationContext().isPotentiallyEvaluated() &&
4814 CheckIfFunctionSpecializationIsImmediate(Specialization,
4815 Info.getLocation()))
4816 return TemplateDeductionResult::MiscellaneousDeductionFailure;
4818 // Adjust the exception specification of the argument to match the
4819 // substituted and resolved type we just formed. (Calling convention and
4820 // noreturn can't be dependent, so we don't actually need this for them
4821 // right now.)
4822 QualType SpecializationType = Specialization->getType();
4823 if (!IsAddressOfFunction) {
4824 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4825 /*AdjustExceptionSpec*/true);
4827 // Revert placeholder types in the return type back to undeduced types so
4828 // that the comparison below compares the declared return types.
4829 if (HasDeducedReturnType) {
4830 SpecializationType = SubstAutoType(SpecializationType, QualType());
4831 ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
4835 // If the requested function type does not match the actual type of the
4836 // specialization with respect to arguments of compatible pointer to function
4837 // types, template argument deduction fails.
4838 if (!ArgFunctionType.isNull()) {
4839 if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
4840 SpecializationType, ArgFunctionType)
4841 : !Context.hasSameFunctionTypeIgnoringExceptionSpec(
4842 SpecializationType, ArgFunctionType)) {
4843 Info.FirstArg = TemplateArgument(SpecializationType);
4844 Info.SecondArg = TemplateArgument(ArgFunctionType);
4845 return TemplateDeductionResult::NonDeducedMismatch;
4849 return TemplateDeductionResult::Success;
4852 TemplateDeductionResult Sema::DeduceTemplateArguments(
4853 FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
4854 Expr::Classification ObjectClassification, QualType A,
4855 CXXConversionDecl *&Specialization, TemplateDeductionInfo &Info) {
4856 if (ConversionTemplate->isInvalidDecl())
4857 return TemplateDeductionResult::Invalid;
4859 CXXConversionDecl *ConversionGeneric
4860 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4862 QualType P = ConversionGeneric->getConversionType();
4863 bool IsReferenceP = P->isReferenceType();
4864 bool IsReferenceA = A->isReferenceType();
4866 // C++0x [temp.deduct.conv]p2:
4867 // If P is a reference type, the type referred to by P is used for
4868 // type deduction.
4869 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4870 P = PRef->getPointeeType();
4872 // C++0x [temp.deduct.conv]p4:
4873 // [...] If A is a reference type, the type referred to by A is used
4874 // for type deduction.
4875 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4876 A = ARef->getPointeeType();
4877 // We work around a defect in the standard here: cv-qualifiers are also
4878 // removed from P and A in this case, unless P was a reference type. This
4879 // seems to mostly match what other compilers are doing.
4880 if (!IsReferenceP) {
4881 A = A.getUnqualifiedType();
4882 P = P.getUnqualifiedType();
4885 // C++ [temp.deduct.conv]p3:
4887 // If A is not a reference type:
4888 } else {
4889 assert(!A->isReferenceType() && "Reference types were handled above");
4891 // - If P is an array type, the pointer type produced by the
4892 // array-to-pointer standard conversion (4.2) is used in place
4893 // of P for type deduction; otherwise,
4894 if (P->isArrayType())
4895 P = Context.getArrayDecayedType(P);
4896 // - If P is a function type, the pointer type produced by the
4897 // function-to-pointer standard conversion (4.3) is used in
4898 // place of P for type deduction; otherwise,
4899 else if (P->isFunctionType())
4900 P = Context.getPointerType(P);
4901 // - If P is a cv-qualified type, the top level cv-qualifiers of
4902 // P's type are ignored for type deduction.
4903 else
4904 P = P.getUnqualifiedType();
4906 // C++0x [temp.deduct.conv]p4:
4907 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4908 // type are ignored for type deduction. If A is a reference type, the type
4909 // referred to by A is used for type deduction.
4910 A = A.getUnqualifiedType();
4913 // Unevaluated SFINAE context.
4914 EnterExpressionEvaluationContext Unevaluated(
4915 *this, Sema::ExpressionEvaluationContext::Unevaluated);
4916 SFINAETrap Trap(*this);
4918 // C++ [temp.deduct.conv]p1:
4919 // Template argument deduction is done by comparing the return
4920 // type of the template conversion function (call it P) with the
4921 // type that is required as the result of the conversion (call it
4922 // A) as described in 14.8.2.4.
4923 TemplateParameterList *TemplateParams
4924 = ConversionTemplate->getTemplateParameters();
4925 SmallVector<DeducedTemplateArgument, 4> Deduced;
4926 Deduced.resize(TemplateParams->size());
4928 // C++0x [temp.deduct.conv]p4:
4929 // In general, the deduction process attempts to find template
4930 // argument values that will make the deduced A identical to
4931 // A. However, there are two cases that allow a difference:
4932 unsigned TDF = 0;
4933 // - If the original A is a reference type, A can be more
4934 // cv-qualified than the deduced A (i.e., the type referred to
4935 // by the reference)
4936 if (IsReferenceA)
4937 TDF |= TDF_ArgWithReferenceType;
4938 // - The deduced A can be another pointer or pointer to member
4939 // type that can be converted to A via a qualification
4940 // conversion.
4942 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4943 // both P and A are pointers or member pointers. In this case, we
4944 // just ignore cv-qualifiers completely).
4945 if ((P->isPointerType() && A->isPointerType()) ||
4946 (P->isMemberPointerType() && A->isMemberPointerType()))
4947 TDF |= TDF_IgnoreQualifiers;
4949 SmallVector<Sema::OriginalCallArg, 1> OriginalCallArgs;
4950 if (ConversionGeneric->isExplicitObjectMemberFunction()) {
4951 QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
4952 if (TemplateDeductionResult Result =
4953 DeduceTemplateArgumentsFromCallArgument(
4954 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
4955 ParamType, ObjectType, ObjectClassification,
4956 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4957 /*Decomposed*/ false, 0, /*TDF*/ 0);
4958 Result != TemplateDeductionResult::Success)
4959 return Result;
4962 if (TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch(
4963 *this, TemplateParams, P, A, Info, Deduced, TDF,
4964 PartialOrderingKind::None, /*DeducedFromArrayBound=*/false,
4965 /*HasDeducedAnyParam=*/nullptr);
4966 Result != TemplateDeductionResult::Success)
4967 return Result;
4969 // Create an Instantiation Scope for finalizing the operator.
4970 LocalInstantiationScope InstScope(*this);
4971 // Finish template argument deduction.
4972 FunctionDecl *ConversionSpecialized = nullptr;
4973 TemplateDeductionResult Result;
4974 runWithSufficientStackSpace(Info.getLocation(), [&] {
4975 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4976 ConversionSpecialized, Info,
4977 &OriginalCallArgs);
4979 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4980 return Result;
4983 TemplateDeductionResult
4984 Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
4985 TemplateArgumentListInfo *ExplicitTemplateArgs,
4986 FunctionDecl *&Specialization,
4987 TemplateDeductionInfo &Info,
4988 bool IsAddressOfFunction) {
4989 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4990 QualType(), Specialization, Info,
4991 IsAddressOfFunction);
4994 namespace {
4995 struct DependentAuto { bool IsPack; };
4997 /// Substitute the 'auto' specifier or deduced template specialization type
4998 /// specifier within a type for a given replacement type.
4999 class SubstituteDeducedTypeTransform :
5000 public TreeTransform<SubstituteDeducedTypeTransform> {
5001 QualType Replacement;
5002 bool ReplacementIsPack;
5003 bool UseTypeSugar;
5004 using inherited = TreeTransform<SubstituteDeducedTypeTransform>;
5006 public:
5007 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
5008 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5009 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
5011 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
5012 bool UseTypeSugar = true)
5013 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
5014 Replacement(Replacement), ReplacementIsPack(false),
5015 UseTypeSugar(UseTypeSugar) {}
5017 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
5018 assert(isa<TemplateTypeParmType>(Replacement) &&
5019 "unexpected unsugared replacement kind");
5020 QualType Result = Replacement;
5021 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
5022 NewTL.setNameLoc(TL.getNameLoc());
5023 return Result;
5026 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
5027 // If we're building the type pattern to deduce against, don't wrap the
5028 // substituted type in an AutoType. Certain template deduction rules
5029 // apply only when a template type parameter appears directly (and not if
5030 // the parameter is found through desugaring). For instance:
5031 // auto &&lref = lvalue;
5032 // must transform into "rvalue reference to T" not "rvalue reference to
5033 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
5035 // FIXME: Is this still necessary?
5036 if (!UseTypeSugar)
5037 return TransformDesugared(TLB, TL);
5039 QualType Result = SemaRef.Context.getAutoType(
5040 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
5041 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
5042 TL.getTypePtr()->getTypeConstraintArguments());
5043 auto NewTL = TLB.push<AutoTypeLoc>(Result);
5044 NewTL.copy(TL);
5045 return Result;
5048 QualType TransformDeducedTemplateSpecializationType(
5049 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
5050 if (!UseTypeSugar)
5051 return TransformDesugared(TLB, TL);
5053 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
5054 TL.getTypePtr()->getTemplateName(),
5055 Replacement, Replacement.isNull());
5056 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
5057 NewTL.setNameLoc(TL.getNameLoc());
5058 return Result;
5061 ExprResult TransformLambdaExpr(LambdaExpr *E) {
5062 // Lambdas never need to be transformed.
5063 return E;
5065 bool TransformExceptionSpec(SourceLocation Loc,
5066 FunctionProtoType::ExceptionSpecInfo &ESI,
5067 SmallVectorImpl<QualType> &Exceptions,
5068 bool &Changed) {
5069 if (ESI.Type == EST_Uninstantiated) {
5070 ESI.instantiate();
5071 Changed = true;
5073 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
5076 QualType Apply(TypeLoc TL) {
5077 // Create some scratch storage for the transformed type locations.
5078 // FIXME: We're just going to throw this information away. Don't build it.
5079 TypeLocBuilder TLB;
5080 TLB.reserve(TL.getFullDataSize());
5081 return TransformType(TLB, TL);
5085 } // namespace
5087 static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
5088 AutoTypeLoc TypeLoc,
5089 QualType Deduced) {
5090 ConstraintSatisfaction Satisfaction;
5091 ConceptDecl *Concept = Type.getTypeConstraintConcept();
5092 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
5093 TypeLoc.getRAngleLoc());
5094 TemplateArgs.addArgument(
5095 TemplateArgumentLoc(TemplateArgument(Deduced),
5096 S.Context.getTrivialTypeSourceInfo(
5097 Deduced, TypeLoc.getNameLoc())));
5098 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
5099 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
5101 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5102 if (S.CheckTemplateArgumentList(
5103 Concept, SourceLocation(), TemplateArgs, /*DefaultArgs=*/{},
5104 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
5105 return true;
5106 MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
5107 /*Final=*/false);
5108 // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5109 // that the template arguments of the constraint can be preserved. For
5110 // example:
5112 // template <class T>
5113 // concept C = []<D U = void>() { return true; }();
5115 // We need the argument for T while evaluating type constraint D in
5116 // building the CallExpr to the lambda.
5117 EnterExpressionEvaluationContext EECtx(
5118 S, Sema::ExpressionEvaluationContext::Unevaluated,
5119 ImplicitConceptSpecializationDecl::Create(
5120 S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5121 CanonicalConverted));
5122 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
5123 MLTAL, TypeLoc.getLocalSourceRange(),
5124 Satisfaction))
5125 return true;
5126 if (!Satisfaction.IsSatisfied) {
5127 std::string Buf;
5128 llvm::raw_string_ostream OS(Buf);
5129 OS << "'" << Concept->getName();
5130 if (TypeLoc.hasExplicitTemplateArgs()) {
5131 printTemplateArgumentList(
5132 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5133 Type.getTypeConstraintConcept()->getTemplateParameters());
5135 OS << "'";
5136 S.Diag(TypeLoc.getConceptNameLoc(),
5137 diag::err_placeholder_constraints_not_satisfied)
5138 << Deduced << Buf << TypeLoc.getLocalSourceRange();
5139 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5140 return true;
5142 return false;
5145 TemplateDeductionResult
5146 Sema::DeduceAutoType(TypeLoc Type, Expr *Init, QualType &Result,
5147 TemplateDeductionInfo &Info, bool DependentDeduction,
5148 bool IgnoreConstraints,
5149 TemplateSpecCandidateSet *FailedTSC) {
5150 assert(DependentDeduction || Info.getDeducedDepth() == 0);
5151 if (Init->containsErrors())
5152 return TemplateDeductionResult::AlreadyDiagnosed;
5154 const AutoType *AT = Type.getType()->getContainedAutoType();
5155 assert(AT);
5157 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
5158 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
5159 if (NonPlaceholder.isInvalid())
5160 return TemplateDeductionResult::AlreadyDiagnosed;
5161 Init = NonPlaceholder.get();
5164 DependentAuto DependentResult = {
5165 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
5167 if (!DependentDeduction &&
5168 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5169 Init->containsUnexpandedParameterPack())) {
5170 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5171 assert(!Result.isNull() && "substituting DependentTy can't fail");
5172 return TemplateDeductionResult::Success;
5175 // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
5176 auto *String = dyn_cast<StringLiteral>(Init);
5177 if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
5178 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5179 TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
5180 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
5181 assert(!Result.isNull() && "substituting DependentTy can't fail");
5182 return TemplateDeductionResult::Success;
5185 // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
5186 if (getLangOpts().C23 && Type.getType()->isPointerType()) {
5187 Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
5190 auto *InitList = dyn_cast<InitListExpr>(Init);
5191 if (!getLangOpts().CPlusPlus && InitList) {
5192 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
5193 << (int)AT->getKeyword() << getLangOpts().C23;
5194 return TemplateDeductionResult::AlreadyDiagnosed;
5197 // Deduce type of TemplParam in Func(Init)
5198 SmallVector<DeducedTemplateArgument, 1> Deduced;
5199 Deduced.resize(1);
5201 // If deduction failed, don't diagnose if the initializer is dependent; it
5202 // might acquire a matching type in the instantiation.
5203 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
5204 if (Init->isTypeDependent()) {
5205 Result =
5206 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
5207 assert(!Result.isNull() && "substituting DependentTy can't fail");
5208 return TemplateDeductionResult::Success;
5210 return TDK;
5213 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
5215 QualType DeducedType;
5216 // If this is a 'decltype(auto)' specifier, do the decltype dance.
5217 if (AT->isDecltypeAuto()) {
5218 if (InitList) {
5219 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5220 return TemplateDeductionResult::AlreadyDiagnosed;
5223 DeducedType = getDecltypeForExpr(Init);
5224 assert(!DeducedType.isNull());
5225 } else {
5226 LocalInstantiationScope InstScope(*this);
5228 // Build template<class TemplParam> void Func(FuncParam);
5229 SourceLocation Loc = Init->getExprLoc();
5230 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
5231 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5232 nullptr, false, false, false);
5233 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5234 NamedDecl *TemplParamPtr = TemplParam;
5235 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
5236 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5238 if (InitList) {
5239 // Notionally, we substitute std::initializer_list<T> for 'auto' and
5240 // deduce against that. Such deduction only succeeds if removing
5241 // cv-qualifiers and references results in std::initializer_list<T>.
5242 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5243 return TemplateDeductionResult::Invalid;
5245 SourceRange DeducedFromInitRange;
5246 for (Expr *Init : InitList->inits()) {
5247 // Resolving a core issue: a braced-init-list containing any designators
5248 // is a non-deduced context.
5249 if (isa<DesignatedInitExpr>(Init))
5250 return TemplateDeductionResult::Invalid;
5251 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
5252 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
5253 Init->Classify(getASTContext()), Init, Info, Deduced,
5254 OriginalCallArgs,
5255 /*Decomposed=*/true,
5256 /*ArgIdx=*/0, /*TDF=*/0);
5257 TDK != TemplateDeductionResult::Success) {
5258 if (TDK == TemplateDeductionResult::Inconsistent) {
5259 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5260 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5261 << Init->getSourceRange();
5262 return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5264 return DeductionFailed(TDK);
5267 if (DeducedFromInitRange.isInvalid() &&
5268 Deduced[0].getKind() != TemplateArgument::Null)
5269 DeducedFromInitRange = Init->getSourceRange();
5271 } else {
5272 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
5273 Diag(Loc, diag::err_auto_bitfield);
5274 return TemplateDeductionResult::AlreadyDiagnosed;
5276 QualType FuncParam =
5277 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5278 assert(!FuncParam.isNull() &&
5279 "substituting template parameter for 'auto' failed");
5280 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
5281 *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
5282 Init->Classify(getASTContext()), Init, Info, Deduced,
5283 OriginalCallArgs,
5284 /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0, FailedTSC);
5285 TDK != TemplateDeductionResult::Success)
5286 return DeductionFailed(TDK);
5289 // Could be null if somehow 'auto' appears in a non-deduced context.
5290 if (Deduced[0].getKind() != TemplateArgument::Type)
5291 return DeductionFailed(TemplateDeductionResult::Incomplete);
5292 DeducedType = Deduced[0].getAsType();
5294 if (InitList) {
5295 DeducedType = BuildStdInitializerList(DeducedType, Loc);
5296 if (DeducedType.isNull())
5297 return TemplateDeductionResult::AlreadyDiagnosed;
5301 if (!Result.isNull()) {
5302 if (!Context.hasSameType(DeducedType, Result)) {
5303 Info.FirstArg = Result;
5304 Info.SecondArg = DeducedType;
5305 return DeductionFailed(TemplateDeductionResult::Inconsistent);
5307 DeducedType = Context.getCommonSugaredType(Result, DeducedType);
5310 if (AT->isConstrained() && !IgnoreConstraints &&
5311 CheckDeducedPlaceholderConstraints(
5312 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5313 return TemplateDeductionResult::AlreadyDiagnosed;
5315 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
5316 if (Result.isNull())
5317 return TemplateDeductionResult::AlreadyDiagnosed;
5319 // Check that the deduced argument type is compatible with the original
5320 // argument type per C++ [temp.deduct.call]p4.
5321 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
5322 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
5323 assert((bool)InitList == OriginalArg.DecomposedParam &&
5324 "decomposed non-init-list in auto deduction?");
5325 if (auto TDK =
5326 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5327 TDK != TemplateDeductionResult::Success) {
5328 Result = QualType();
5329 return DeductionFailed(TDK);
5333 return TemplateDeductionResult::Success;
5336 QualType Sema::SubstAutoType(QualType TypeWithAuto,
5337 QualType TypeToReplaceAuto) {
5338 assert(TypeToReplaceAuto != Context.DependentTy);
5339 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5340 .TransformType(TypeWithAuto);
5343 TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
5344 QualType TypeToReplaceAuto) {
5345 assert(TypeToReplaceAuto != Context.DependentTy);
5346 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
5347 .TransformType(TypeWithAuto);
5350 QualType Sema::SubstAutoTypeDependent(QualType TypeWithAuto) {
5351 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5352 .TransformType(TypeWithAuto);
5355 TypeSourceInfo *
5356 Sema::SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto) {
5357 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5358 .TransformType(TypeWithAuto);
5361 QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
5362 QualType TypeToReplaceAuto) {
5363 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5364 /*UseTypeSugar*/ false)
5365 .TransformType(TypeWithAuto);
5368 TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
5369 QualType TypeToReplaceAuto) {
5370 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5371 /*UseTypeSugar*/ false)
5372 .TransformType(TypeWithAuto);
5375 void Sema::DiagnoseAutoDeductionFailure(const VarDecl *VDecl,
5376 const Expr *Init) {
5377 if (isa<InitListExpr>(Init))
5378 Diag(VDecl->getLocation(),
5379 VDecl->isInitCapture()
5380 ? diag::err_init_capture_deduction_failure_from_init_list
5381 : diag::err_auto_var_deduction_failure_from_init_list)
5382 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
5383 else
5384 Diag(VDecl->getLocation(),
5385 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
5386 : diag::err_auto_var_deduction_failure)
5387 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
5388 << Init->getSourceRange();
5391 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
5392 bool Diagnose) {
5393 assert(FD->getReturnType()->isUndeducedType());
5395 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
5396 // within the return type from the call operator's type.
5397 if (isLambdaConversionOperator(FD)) {
5398 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5399 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5401 // For a generic lambda, instantiate the call operator if needed.
5402 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5403 CallOp = InstantiateFunctionDeclaration(
5404 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5405 if (!CallOp || CallOp->isInvalidDecl())
5406 return true;
5408 // We might need to deduce the return type by instantiating the definition
5409 // of the operator() function.
5410 if (CallOp->getReturnType()->isUndeducedType()) {
5411 runWithSufficientStackSpace(Loc, [&] {
5412 InstantiateFunctionDefinition(Loc, CallOp);
5417 if (CallOp->isInvalidDecl())
5418 return true;
5419 assert(!CallOp->getReturnType()->isUndeducedType() &&
5420 "failed to deduce lambda return type");
5422 // Build the new return type from scratch.
5423 CallingConv RetTyCC = FD->getReturnType()
5424 ->getPointeeType()
5425 ->castAs<FunctionType>()
5426 ->getCallConv();
5427 QualType RetType = getLambdaConversionFunctionResultType(
5428 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
5429 if (FD->getReturnType()->getAs<PointerType>())
5430 RetType = Context.getPointerType(RetType);
5431 else {
5432 assert(FD->getReturnType()->getAs<BlockPointerType>());
5433 RetType = Context.getBlockPointerType(RetType);
5435 Context.adjustDeducedFunctionResultType(FD, RetType);
5436 return false;
5439 if (FD->getTemplateInstantiationPattern()) {
5440 runWithSufficientStackSpace(Loc, [&] {
5441 InstantiateFunctionDefinition(Loc, FD);
5445 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
5446 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
5447 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
5448 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
5451 return StillUndeduced;
5454 bool Sema::CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
5455 SourceLocation Loc) {
5456 assert(FD->isImmediateEscalating());
5458 if (isLambdaConversionOperator(FD)) {
5459 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
5460 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
5462 // For a generic lambda, instantiate the call operator if needed.
5463 if (auto *Args = FD->getTemplateSpecializationArgs()) {
5464 CallOp = InstantiateFunctionDeclaration(
5465 CallOp->getDescribedFunctionTemplate(), Args, Loc);
5466 if (!CallOp || CallOp->isInvalidDecl())
5467 return true;
5468 runWithSufficientStackSpace(
5469 Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
5471 return CallOp->isInvalidDecl();
5474 if (FD->getTemplateInstantiationPattern()) {
5475 runWithSufficientStackSpace(
5476 Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
5478 return false;
5481 static QualType GetImplicitObjectParameterType(ASTContext &Context,
5482 const CXXMethodDecl *Method,
5483 QualType RawType,
5484 bool IsOtherRvr) {
5485 // C++20 [temp.func.order]p3.1, p3.2:
5486 // - The type X(M) is "rvalue reference to cv A" if the optional
5487 // ref-qualifier of M is && or if M has no ref-qualifier and the
5488 // positionally-corresponding parameter of the other transformed template
5489 // has rvalue reference type; if this determination depends recursively
5490 // upon whether X(M) is an rvalue reference type, it is not considered to
5491 // have rvalue reference type.
5493 // - Otherwise, X(M) is "lvalue reference to cv A".
5494 assert(Method && !Method->isExplicitObjectMemberFunction() &&
5495 "expected a member function with no explicit object parameter");
5497 RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5498 if (Method->getRefQualifier() == RQ_RValue ||
5499 (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5500 return Context.getRValueReferenceType(RawType);
5501 return Context.getLValueReferenceType(RawType);
5504 static TemplateDeductionResult CheckDeductionConsistency(
5505 Sema &S, FunctionTemplateDecl *FTD, int ArgIdx, QualType P, QualType A,
5506 ArrayRef<TemplateArgument> DeducedArgs, bool CheckConsistency) {
5507 MultiLevelTemplateArgumentList MLTAL(FTD, DeducedArgs,
5508 /*Final=*/true);
5509 Sema::ArgumentPackSubstitutionIndexRAII PackIndex(
5510 S, ArgIdx != -1 ? ::getPackIndexForParam(S, FTD, MLTAL, ArgIdx) : -1);
5511 bool IsIncompleteSubstitution = false;
5512 // FIXME: A substitution can be incomplete on a non-structural part of the
5513 // type. Use the canonical type for now, until the TemplateInstantiator can
5514 // deal with that.
5515 QualType InstP = S.SubstType(P.getCanonicalType(), MLTAL, FTD->getLocation(),
5516 FTD->getDeclName(), &IsIncompleteSubstitution);
5517 if (InstP.isNull() && !IsIncompleteSubstitution)
5518 return TemplateDeductionResult::SubstitutionFailure;
5519 if (!CheckConsistency)
5520 return TemplateDeductionResult::Success;
5521 if (IsIncompleteSubstitution)
5522 return TemplateDeductionResult::Incomplete;
5524 // [temp.deduct.call]/4 - Check we produced a consistent deduction.
5525 // This handles just the cases that can appear when partial ordering.
5526 if (auto *PA = dyn_cast<PackExpansionType>(A);
5527 PA && !isa<PackExpansionType>(InstP))
5528 A = PA->getPattern();
5529 if (!S.Context.hasSameType(
5530 S.Context.getUnqualifiedArrayType(InstP.getNonReferenceType()),
5531 S.Context.getUnqualifiedArrayType(A.getNonReferenceType())))
5532 return TemplateDeductionResult::NonDeducedMismatch;
5533 return TemplateDeductionResult::Success;
5536 template <class T>
5537 static TemplateDeductionResult FinishTemplateArgumentDeduction(
5538 Sema &S, FunctionTemplateDecl *FTD,
5539 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5540 TemplateDeductionInfo &Info, T &&CheckDeductionConsistency) {
5541 EnterExpressionEvaluationContext Unevaluated(
5542 S, Sema::ExpressionEvaluationContext::Unevaluated);
5543 Sema::SFINAETrap Trap(S);
5545 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(FTD));
5547 // C++26 [temp.deduct.type]p2:
5548 // [...] or if any template argument remains neither deduced nor
5549 // explicitly specified, template argument deduction fails.
5550 bool IsIncomplete = false;
5551 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
5552 if (auto Result = ConvertDeducedTemplateArguments(
5553 S, FTD, /*IsDeduced=*/true, Deduced, Info, SugaredBuilder,
5554 CanonicalBuilder, /*CurrentInstantiationScope=*/nullptr,
5555 /*NumAlreadyConverted=*/0, &IsIncomplete);
5556 Result != TemplateDeductionResult::Success)
5557 return Result;
5559 // Form the template argument list from the deduced template arguments.
5560 TemplateArgumentList *SugaredDeducedArgumentList =
5561 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
5562 TemplateArgumentList *CanonicalDeducedArgumentList =
5563 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
5565 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
5567 // Substitute the deduced template arguments into the argument
5568 // and verify that the instantiated argument is both valid
5569 // and equivalent to the parameter.
5570 LocalInstantiationScope InstScope(S);
5572 if (auto TDR = CheckDeductionConsistency(S, FTD, SugaredBuilder);
5573 TDR != TemplateDeductionResult::Success)
5574 return TDR;
5576 return Trap.hasErrorOccurred() ? TemplateDeductionResult::SubstitutionFailure
5577 : TemplateDeductionResult::Success;
5580 /// Determine whether the function template \p FT1 is at least as
5581 /// specialized as \p FT2.
5582 static bool isAtLeastAsSpecializedAs(
5583 Sema &S, SourceLocation Loc, FunctionTemplateDecl *FT1,
5584 FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC,
5585 ArrayRef<QualType> Args1, ArrayRef<QualType> Args2, bool Args1Offset) {
5586 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5587 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5588 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5589 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5590 assert(Proto1 && Proto2 && "Function templates must have prototypes");
5592 // C++26 [temp.deduct.partial]p3:
5593 // The types used to determine the ordering depend on the context in which
5594 // the partial ordering is done:
5595 // - In the context of a function call, the types used are those function
5596 // parameter types for which the function call has arguments.
5597 // - In the context of a call to a conversion operator, the return types
5598 // of the conversion function templates are used.
5599 // - In other contexts (14.6.6.2) the function template's function type
5600 // is used.
5602 if (TPOC == TPOC_Other) {
5603 // We wouldn't be partial ordering these candidates if these didn't match.
5604 assert(Proto1->getMethodQuals() == Proto2->getMethodQuals() &&
5605 Proto1->getRefQualifier() == Proto2->getRefQualifier() &&
5606 Proto1->isVariadic() == Proto2->isVariadic() &&
5607 "shouldn't partial order functions with different qualifiers in a "
5608 "context where the function type is used");
5610 assert(Args1.empty() && Args2.empty() &&
5611 "Only call context should have arguments");
5612 Args1 = Proto1->getParamTypes();
5613 Args2 = Proto2->getParamTypes();
5616 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5617 SmallVector<DeducedTemplateArgument, 4> Deduced(TemplateParams->size());
5618 TemplateDeductionInfo Info(Loc);
5620 bool HasDeducedAnyParamFromReturnType = false;
5621 if (TPOC != TPOC_Call) {
5622 if (DeduceTemplateArgumentsByTypeMatch(
5623 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5624 Info, Deduced, TDF_None, PartialOrderingKind::Call,
5625 /*DeducedFromArrayBound=*/false,
5626 &HasDeducedAnyParamFromReturnType) !=
5627 TemplateDeductionResult::Success)
5628 return false;
5631 llvm::SmallBitVector HasDeducedParam;
5632 if (TPOC != TPOC_Conversion) {
5633 HasDeducedParam.resize(Args2.size());
5634 if (DeduceTemplateArguments(S, TemplateParams, Args2, Args1, Info, Deduced,
5635 TDF_None, PartialOrderingKind::Call,
5636 /*HasDeducedAnyParam=*/nullptr,
5637 &HasDeducedParam) !=
5638 TemplateDeductionResult::Success)
5639 return false;
5642 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
5643 Sema::InstantiatingTemplate Inst(
5644 S, Info.getLocation(), FT2, DeducedArgs,
5645 Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
5646 if (Inst.isInvalid())
5647 return false;
5649 bool AtLeastAsSpecialized;
5650 S.runWithSufficientStackSpace(Info.getLocation(), [&] {
5651 AtLeastAsSpecialized =
5652 ::FinishTemplateArgumentDeduction(
5653 S, FT2, Deduced, Info,
5654 [&](Sema &S, FunctionTemplateDecl *FTD,
5655 ArrayRef<TemplateArgument> DeducedArgs) {
5656 // As a provisional fix for a core issue that does not
5657 // exist yet, which may be related to CWG2160, only check the
5658 // consistency of parameters and return types which participated
5659 // in deduction. We will still try to substitute them though.
5660 if (TPOC != TPOC_Call) {
5661 if (auto TDR = ::CheckDeductionConsistency(
5662 S, FTD, /*ArgIdx=*/-1, Proto2->getReturnType(),
5663 Proto1->getReturnType(), DeducedArgs,
5664 /*CheckConsistency=*/HasDeducedAnyParamFromReturnType);
5665 TDR != TemplateDeductionResult::Success)
5666 return TDR;
5669 if (TPOC == TPOC_Conversion)
5670 return TemplateDeductionResult::Success;
5672 return ::DeduceForEachType(
5673 S, TemplateParams, Args2, Args1, Info, Deduced,
5674 PartialOrderingKind::Call, /*FinishingDeduction=*/true,
5675 [&](Sema &S, TemplateParameterList *, int ParamIdx,
5676 int ArgIdx, QualType P, QualType A,
5677 TemplateDeductionInfo &Info,
5678 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
5679 PartialOrderingKind) {
5680 if (ArgIdx != -1)
5681 ArgIdx -= Args1Offset;
5682 return ::CheckDeductionConsistency(
5683 S, FTD, ArgIdx, P, A, DeducedArgs,
5684 /*CheckConsistency=*/HasDeducedParam[ParamIdx]);
5686 }) == TemplateDeductionResult::Success;
5688 if (!AtLeastAsSpecialized)
5689 return false;
5691 // C++0x [temp.deduct.partial]p11:
5692 // In most cases, all template parameters must have values in order for
5693 // deduction to succeed, but for partial ordering purposes a template
5694 // parameter may remain without a value provided it is not used in the
5695 // types being used for partial ordering. [ Note: a template parameter used
5696 // in a non-deduced context is considered used. -end note]
5697 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5698 for (; ArgIdx != NumArgs; ++ArgIdx)
5699 if (Deduced[ArgIdx].isNull())
5700 break;
5702 if (ArgIdx == NumArgs) {
5703 // All template arguments were deduced. FT1 is at least as specialized
5704 // as FT2.
5705 return true;
5708 // Figure out which template parameters were used.
5709 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5710 switch (TPOC) {
5711 case TPOC_Call:
5712 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5713 ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5714 TemplateParams->getDepth(), UsedParameters);
5715 break;
5717 case TPOC_Conversion:
5718 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5719 /*OnlyDeduced=*/false,
5720 TemplateParams->getDepth(), UsedParameters);
5721 break;
5723 case TPOC_Other:
5724 // We do not deduce template arguments from the exception specification
5725 // when determining the primary template of a function template
5726 // specialization or when taking the address of a function template.
5727 // Therefore, we do not mark template parameters in the exception
5728 // specification as used during partial ordering to prevent the following
5729 // from being ambiguous:
5731 // template<typename T, typename U>
5732 // void f(U) noexcept(noexcept(T())); // #1
5734 // template<typename T>
5735 // void f(T*) noexcept; // #2
5737 // template<>
5738 // void f<int>(int*) noexcept; // explicit specialization of #2
5740 // Although there is no corresponding wording in the standard, this seems
5741 // to be the intended behavior given the definition of
5742 // 'deduction substitution loci' in [temp.deduct].
5743 ::MarkUsedTemplateParameters(
5744 S.Context,
5745 S.Context.getFunctionTypeWithExceptionSpec(FD2->getType(), EST_None),
5746 /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
5747 break;
5750 for (; ArgIdx != NumArgs; ++ArgIdx)
5751 // If this argument had no value deduced but was used in one of the types
5752 // used for partial ordering, then deduction fails.
5753 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5754 return false;
5756 return true;
5759 FunctionTemplateDecl *Sema::getMoreSpecializedTemplate(
5760 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
5761 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5762 QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5763 SmallVector<QualType> Args1;
5764 SmallVector<QualType> Args2;
5765 const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5766 const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5767 bool ShouldConvert1 = false;
5768 bool ShouldConvert2 = false;
5769 bool Args1Offset = false;
5770 bool Args2Offset = false;
5771 QualType Obj1Ty;
5772 QualType Obj2Ty;
5773 if (TPOC == TPOC_Call) {
5774 const FunctionProtoType *Proto1 =
5775 FD1->getType()->castAs<FunctionProtoType>();
5776 const FunctionProtoType *Proto2 =
5777 FD2->getType()->castAs<FunctionProtoType>();
5779 // - In the context of a function call, the function parameter types are
5780 // used.
5781 const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5782 const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5783 // C++20 [temp.func.order]p3
5784 // [...] Each function template M that is a member function is
5785 // considered to have a new first parameter of type
5786 // X(M), described below, inserted in its function parameter list.
5788 // Note that we interpret "that is a member function" as
5789 // "that is a member function with no expicit object argument".
5790 // Otherwise the ordering rules for methods with expicit objet arguments
5791 // against anything else make no sense.
5793 bool NonStaticMethod1 = Method1 && !Method1->isStatic(),
5794 NonStaticMethod2 = Method2 && !Method2->isStatic();
5796 auto Params1Begin = Proto1->param_type_begin(),
5797 Params2Begin = Proto2->param_type_begin();
5799 size_t NumComparedArguments = NumCallArguments1;
5801 if (auto OO = FD1->getOverloadedOperator();
5802 (NonStaticMethod1 && NonStaticMethod2) ||
5803 (OO != OO_None && OO != OO_Call && OO != OO_Subscript)) {
5804 ShouldConvert1 =
5805 NonStaticMethod1 && !Method1->hasCXXExplicitFunctionObjectParameter();
5806 ShouldConvert2 =
5807 NonStaticMethod2 && !Method2->hasCXXExplicitFunctionObjectParameter();
5808 NumComparedArguments += 1;
5810 if (ShouldConvert1) {
5811 bool IsRValRef2 =
5812 ShouldConvert2
5813 ? Method2->getRefQualifier() == RQ_RValue
5814 : Proto2->param_type_begin()[0]->isRValueReferenceType();
5815 // Compare 'this' from Method1 against first parameter from Method2.
5816 Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1,
5817 RawObj1Ty, IsRValRef2);
5818 Args1.push_back(Obj1Ty);
5819 Args1Offset = true;
5821 if (ShouldConvert2) {
5822 bool IsRValRef1 =
5823 ShouldConvert1
5824 ? Method1->getRefQualifier() == RQ_RValue
5825 : Proto1->param_type_begin()[0]->isRValueReferenceType();
5826 // Compare 'this' from Method2 against first parameter from Method1.
5827 Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2,
5828 RawObj2Ty, IsRValRef1);
5829 Args2.push_back(Obj2Ty);
5830 Args2Offset = true;
5832 } else {
5833 if (NonStaticMethod1 && Method1->hasCXXExplicitFunctionObjectParameter())
5834 Params1Begin += 1;
5835 if (NonStaticMethod2 && Method2->hasCXXExplicitFunctionObjectParameter())
5836 Params2Begin += 1;
5838 Args1.insert(Args1.end(), Params1Begin, Proto1->param_type_end());
5839 Args2.insert(Args2.end(), Params2Begin, Proto2->param_type_end());
5841 // C++ [temp.func.order]p5:
5842 // The presence of unused ellipsis and default arguments has no effect on
5843 // the partial ordering of function templates.
5844 Args1.resize(std::min(Args1.size(), NumComparedArguments));
5845 Args2.resize(std::min(Args2.size(), NumComparedArguments));
5847 if (Reversed)
5848 std::reverse(Args2.begin(), Args2.end());
5849 } else {
5850 assert(!Reversed && "Only call context could have reversed arguments");
5852 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Args1,
5853 Args2, Args2Offset);
5854 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Args2,
5855 Args1, Args1Offset);
5856 // C++ [temp.deduct.partial]p10:
5857 // F is more specialized than G if F is at least as specialized as G and G
5858 // is not at least as specialized as F.
5859 if (Better1 != Better2) // We have a clear winner
5860 return Better1 ? FT1 : FT2;
5862 if (!Better1 && !Better2) // Neither is better than the other
5863 return nullptr;
5865 // C++ [temp.deduct.partial]p11:
5866 // ... and if G has a trailing function parameter pack for which F does not
5867 // have a corresponding parameter, and if F does not have a trailing
5868 // function parameter pack, then F is more specialized than G.
5870 SmallVector<QualType> Param1;
5871 Param1.reserve(FD1->param_size() + ShouldConvert1);
5872 if (ShouldConvert1)
5873 Param1.push_back(Obj1Ty);
5874 for (const auto &P : FD1->parameters())
5875 Param1.push_back(P->getType());
5877 SmallVector<QualType> Param2;
5878 Param2.reserve(FD2->param_size() + ShouldConvert2);
5879 if (ShouldConvert2)
5880 Param2.push_back(Obj2Ty);
5881 for (const auto &P : FD2->parameters())
5882 Param2.push_back(P->getType());
5884 unsigned NumParams1 = Param1.size();
5885 unsigned NumParams2 = Param2.size();
5887 bool Variadic1 =
5888 FD1->param_size() && FD1->parameters().back()->isParameterPack();
5889 bool Variadic2 =
5890 FD2->param_size() && FD2->parameters().back()->isParameterPack();
5891 if (Variadic1 != Variadic2) {
5892 if (Variadic1 && NumParams1 > NumParams2)
5893 return FT2;
5894 if (Variadic2 && NumParams2 > NumParams1)
5895 return FT1;
5898 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5899 // there is no wording or even resolution for this issue.
5900 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
5901 QualType T1 = Param1[i].getCanonicalType();
5902 QualType T2 = Param2[i].getCanonicalType();
5903 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5904 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5905 if (!TST1 || !TST2)
5906 continue;
5907 const TemplateArgument &TA1 = TST1->template_arguments().back();
5908 if (TA1.getKind() == TemplateArgument::Pack) {
5909 assert(TST1->template_arguments().size() ==
5910 TST2->template_arguments().size());
5911 const TemplateArgument &TA2 = TST2->template_arguments().back();
5912 assert(TA2.getKind() == TemplateArgument::Pack);
5913 unsigned PackSize1 = TA1.pack_size();
5914 unsigned PackSize2 = TA2.pack_size();
5915 bool IsPackExpansion1 =
5916 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5917 bool IsPackExpansion2 =
5918 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5919 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5920 if (PackSize1 > PackSize2 && IsPackExpansion1)
5921 return FT2;
5922 if (PackSize1 < PackSize2 && IsPackExpansion2)
5923 return FT1;
5928 if (!Context.getLangOpts().CPlusPlus20)
5929 return nullptr;
5931 // Match GCC on not implementing [temp.func.order]p6.2.1.
5933 // C++20 [temp.func.order]p6:
5934 // If deduction against the other template succeeds for both transformed
5935 // templates, constraints can be considered as follows:
5937 // C++20 [temp.func.order]p6.1:
5938 // If their template-parameter-lists (possibly including template-parameters
5939 // invented for an abbreviated function template ([dcl.fct])) or function
5940 // parameter lists differ in length, neither template is more specialized
5941 // than the other.
5942 TemplateParameterList *TPL1 = FT1->getTemplateParameters();
5943 TemplateParameterList *TPL2 = FT2->getTemplateParameters();
5944 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
5945 return nullptr;
5947 // C++20 [temp.func.order]p6.2.2:
5948 // Otherwise, if the corresponding template-parameters of the
5949 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5950 // function parameters that positionally correspond between the two
5951 // templates are not of the same type, neither template is more specialized
5952 // than the other.
5953 if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
5954 Sema::TPL_TemplateParamsEquivalent))
5955 return nullptr;
5957 // [dcl.fct]p5:
5958 // Any top-level cv-qualifiers modifying a parameter type are deleted when
5959 // forming the function type.
5960 for (unsigned i = 0; i < NumParams1; ++i)
5961 if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
5962 return nullptr;
5964 // C++20 [temp.func.order]p6.3:
5965 // Otherwise, if the context in which the partial ordering is done is
5966 // that of a call to a conversion function and the return types of the
5967 // templates are not the same, then neither template is more specialized
5968 // than the other.
5969 if (TPOC == TPOC_Conversion &&
5970 !Context.hasSameType(FD1->getReturnType(), FD2->getReturnType()))
5971 return nullptr;
5973 llvm::SmallVector<const Expr *, 3> AC1, AC2;
5974 FT1->getAssociatedConstraints(AC1);
5975 FT2->getAssociatedConstraints(AC2);
5976 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5977 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5978 return nullptr;
5979 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5980 return nullptr;
5981 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5982 return nullptr;
5983 return AtLeastAsConstrained1 ? FT1 : FT2;
5986 UnresolvedSetIterator Sema::getMostSpecialized(
5987 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
5988 TemplateSpecCandidateSet &FailedCandidates,
5989 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
5990 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
5991 bool Complain, QualType TargetType) {
5992 if (SpecBegin == SpecEnd) {
5993 if (Complain) {
5994 Diag(Loc, NoneDiag);
5995 FailedCandidates.NoteCandidates(*this, Loc);
5997 return SpecEnd;
6000 if (SpecBegin + 1 == SpecEnd)
6001 return SpecBegin;
6003 // Find the function template that is better than all of the templates it
6004 // has been compared to.
6005 UnresolvedSetIterator Best = SpecBegin;
6006 FunctionTemplateDecl *BestTemplate
6007 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
6008 assert(BestTemplate && "Not a function template specialization?");
6009 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
6010 FunctionTemplateDecl *Challenger
6011 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6012 assert(Challenger && "Not a function template specialization?");
6013 if (declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6014 Loc, TPOC_Other, 0),
6015 Challenger)) {
6016 Best = I;
6017 BestTemplate = Challenger;
6021 // Make sure that the "best" function template is more specialized than all
6022 // of the others.
6023 bool Ambiguous = false;
6024 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6025 FunctionTemplateDecl *Challenger
6026 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
6027 if (I != Best &&
6028 !declaresSameEntity(getMoreSpecializedTemplate(BestTemplate, Challenger,
6029 Loc, TPOC_Other, 0),
6030 BestTemplate)) {
6031 Ambiguous = true;
6032 break;
6036 if (!Ambiguous) {
6037 // We found an answer. Return it.
6038 return Best;
6041 // Diagnose the ambiguity.
6042 if (Complain) {
6043 Diag(Loc, AmbigDiag);
6045 // FIXME: Can we order the candidates in some sane way?
6046 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
6047 PartialDiagnostic PD = CandidateDiag;
6048 const auto *FD = cast<FunctionDecl>(*I);
6049 PD << FD << getTemplateArgumentBindingsText(
6050 FD->getPrimaryTemplate()->getTemplateParameters(),
6051 *FD->getTemplateSpecializationArgs());
6052 if (!TargetType.isNull())
6053 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
6054 Diag((*I)->getLocation(), PD);
6058 return SpecEnd;
6061 FunctionDecl *Sema::getMoreConstrainedFunction(FunctionDecl *FD1,
6062 FunctionDecl *FD2) {
6063 assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
6064 "not for function templates");
6065 assert(!FD1->isFunctionTemplateSpecialization() ||
6066 isa<CXXConversionDecl>(FD1));
6067 assert(!FD2->isFunctionTemplateSpecialization() ||
6068 isa<CXXConversionDecl>(FD2));
6070 FunctionDecl *F1 = FD1;
6071 if (FunctionDecl *P = FD1->getTemplateInstantiationPattern(false))
6072 F1 = P;
6074 FunctionDecl *F2 = FD2;
6075 if (FunctionDecl *P = FD2->getTemplateInstantiationPattern(false))
6076 F2 = P;
6078 llvm::SmallVector<const Expr *, 1> AC1, AC2;
6079 F1->getAssociatedConstraints(AC1);
6080 F2->getAssociatedConstraints(AC2);
6081 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6082 if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
6083 return nullptr;
6084 if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
6085 return nullptr;
6086 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6087 return nullptr;
6088 return AtLeastAsConstrained1 ? FD1 : FD2;
6091 /// Determine whether one partial specialization, P1, is at least as
6092 /// specialized than another, P2.
6094 /// \tparam TemplateLikeDecl The kind of P2, which must be a
6095 /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
6096 /// \param T1 The injected-class-name of P1 (faked for a variable template).
6097 /// \param T2 The injected-class-name of P2 (faked for a variable template).
6098 template<typename TemplateLikeDecl>
6099 static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
6100 TemplateLikeDecl *P2,
6101 TemplateDeductionInfo &Info) {
6102 // C++ [temp.class.order]p1:
6103 // For two class template partial specializations, the first is at least as
6104 // specialized as the second if, given the following rewrite to two
6105 // function templates, the first function template is at least as
6106 // specialized as the second according to the ordering rules for function
6107 // templates (14.6.6.2):
6108 // - the first function template has the same template parameters as the
6109 // first partial specialization and has a single function parameter
6110 // whose type is a class template specialization with the template
6111 // arguments of the first partial specialization, and
6112 // - the second function template has the same template parameters as the
6113 // second partial specialization and has a single function parameter
6114 // whose type is a class template specialization with the template
6115 // arguments of the second partial specialization.
6117 // Rather than synthesize function templates, we merely perform the
6118 // equivalent partial ordering by performing deduction directly on
6119 // the template arguments of the class template partial
6120 // specializations. This computation is slightly simpler than the
6121 // general problem of function template partial ordering, because
6122 // class template partial specializations are more constrained. We
6123 // know that every template parameter is deducible from the class
6124 // template partial specialization's template arguments, for
6125 // example.
6126 SmallVector<DeducedTemplateArgument, 4> Deduced;
6128 // Determine whether P1 is at least as specialized as P2.
6129 Deduced.resize(P2->getTemplateParameters()->size());
6130 if (DeduceTemplateArgumentsByTypeMatch(
6131 S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
6132 PartialOrderingKind::Call, /*DeducedFromArrayBound=*/false,
6133 /*HasDeducedAnyParam=*/nullptr) != TemplateDeductionResult::Success)
6134 return false;
6136 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
6137 Deduced.end());
6138 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
6139 Info);
6140 if (Inst.isInvalid())
6141 return false;
6143 const auto *TST1 = cast<TemplateSpecializationType>(T1);
6144 bool AtLeastAsSpecialized;
6145 S.runWithSufficientStackSpace(Info.getLocation(), [&] {
6146 AtLeastAsSpecialized =
6147 FinishTemplateArgumentDeduction(
6148 S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(),
6149 Deduced, Info) == TemplateDeductionResult::Success;
6151 return AtLeastAsSpecialized;
6154 namespace {
6155 // A dummy class to return nullptr instead of P2 when performing "more
6156 // specialized than primary" check.
6157 struct GetP2 {
6158 template <typename T1, typename T2,
6159 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6160 T2 *operator()(T1 *, T2 *P2) {
6161 return P2;
6163 template <typename T1, typename T2,
6164 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6165 T1 *operator()(T1 *, T2 *) {
6166 return nullptr;
6170 // The assumption is that two template argument lists have the same size.
6171 struct TemplateArgumentListAreEqual {
6172 ASTContext &Ctx;
6173 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
6175 template <typename T1, typename T2,
6176 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
6177 bool operator()(T1 *PS1, T2 *PS2) {
6178 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
6179 Args2 = PS2->getTemplateArgs().asArray();
6181 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6182 // We use profile, instead of structural comparison of the arguments,
6183 // because canonicalization can't do the right thing for dependent
6184 // expressions.
6185 llvm::FoldingSetNodeID IDA, IDB;
6186 Args1[I].Profile(IDA, Ctx);
6187 Args2[I].Profile(IDB, Ctx);
6188 if (IDA != IDB)
6189 return false;
6191 return true;
6194 template <typename T1, typename T2,
6195 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
6196 bool operator()(T1 *Spec, T2 *Primary) {
6197 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
6198 Args2 = Primary->getInjectedTemplateArgs(Ctx);
6200 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
6201 // We use profile, instead of structural comparison of the arguments,
6202 // because canonicalization can't do the right thing for dependent
6203 // expressions.
6204 llvm::FoldingSetNodeID IDA, IDB;
6205 Args1[I].Profile(IDA, Ctx);
6206 // Unlike the specialization arguments, the injected arguments are not
6207 // always canonical.
6208 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
6209 if (IDA != IDB)
6210 return false;
6212 return true;
6215 } // namespace
6217 /// Returns the more specialized template specialization between T1/P1 and
6218 /// T2/P2.
6219 /// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
6220 /// specialization and T2/P2 is the primary template.
6221 /// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
6223 /// \param T1 the type of the first template partial specialization
6225 /// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
6226 /// template partial specialization; otherwise, the type of the
6227 /// primary template.
6229 /// \param P1 the first template partial specialization
6231 /// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
6232 /// partial specialization; otherwise, the primary template.
6234 /// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
6235 /// more specialized, returns nullptr if P1 is not more specialized.
6236 /// - otherwise, returns the more specialized template partial
6237 /// specialization. If neither partial specialization is more
6238 /// specialized, returns NULL.
6239 template <typename TemplateLikeDecl, typename PrimaryDel>
6240 static TemplateLikeDecl *
6241 getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
6242 PrimaryDel *P2, TemplateDeductionInfo &Info) {
6243 constexpr bool IsMoreSpecialThanPrimaryCheck =
6244 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
6246 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
6247 if (IsMoreSpecialThanPrimaryCheck && !Better1)
6248 return nullptr;
6250 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
6251 if (IsMoreSpecialThanPrimaryCheck && !Better2)
6252 return P1;
6254 // C++ [temp.deduct.partial]p10:
6255 // F is more specialized than G if F is at least as specialized as G and G
6256 // is not at least as specialized as F.
6257 if (Better1 != Better2) // We have a clear winner
6258 return Better1 ? P1 : GetP2()(P1, P2);
6260 if (!Better1 && !Better2)
6261 return nullptr;
6263 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6264 // there is no wording or even resolution for this issue.
6265 auto *TST1 = cast<TemplateSpecializationType>(T1);
6266 auto *TST2 = cast<TemplateSpecializationType>(T2);
6267 const TemplateArgument &TA1 = TST1->template_arguments().back();
6268 if (TA1.getKind() == TemplateArgument::Pack) {
6269 assert(TST1->template_arguments().size() ==
6270 TST2->template_arguments().size());
6271 const TemplateArgument &TA2 = TST2->template_arguments().back();
6272 assert(TA2.getKind() == TemplateArgument::Pack);
6273 unsigned PackSize1 = TA1.pack_size();
6274 unsigned PackSize2 = TA2.pack_size();
6275 bool IsPackExpansion1 =
6276 PackSize1 && TA1.pack_elements().back().isPackExpansion();
6277 bool IsPackExpansion2 =
6278 PackSize2 && TA2.pack_elements().back().isPackExpansion();
6279 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6280 if (PackSize1 > PackSize2 && IsPackExpansion1)
6281 return GetP2()(P1, P2);
6282 if (PackSize1 < PackSize2 && IsPackExpansion2)
6283 return P1;
6287 if (!S.Context.getLangOpts().CPlusPlus20)
6288 return nullptr;
6290 // Match GCC on not implementing [temp.func.order]p6.2.1.
6292 // C++20 [temp.func.order]p6:
6293 // If deduction against the other template succeeds for both transformed
6294 // templates, constraints can be considered as follows:
6296 TemplateParameterList *TPL1 = P1->getTemplateParameters();
6297 TemplateParameterList *TPL2 = P2->getTemplateParameters();
6298 if (TPL1->size() != TPL2->size())
6299 return nullptr;
6301 // C++20 [temp.func.order]p6.2.2:
6302 // Otherwise, if the corresponding template-parameters of the
6303 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6304 // function parameters that positionally correspond between the two
6305 // templates are not of the same type, neither template is more specialized
6306 // than the other.
6307 if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
6308 Sema::TPL_TemplateParamsEquivalent))
6309 return nullptr;
6311 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6312 return nullptr;
6314 llvm::SmallVector<const Expr *, 3> AC1, AC2;
6315 P1->getAssociatedConstraints(AC1);
6316 P2->getAssociatedConstraints(AC2);
6317 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6318 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6319 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6320 return nullptr;
6321 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6322 return nullptr;
6323 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6324 return nullptr;
6325 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6328 ClassTemplatePartialSpecializationDecl *
6329 Sema::getMoreSpecializedPartialSpecialization(
6330 ClassTemplatePartialSpecializationDecl *PS1,
6331 ClassTemplatePartialSpecializationDecl *PS2,
6332 SourceLocation Loc) {
6333 QualType PT1 = PS1->getInjectedSpecializationType();
6334 QualType PT2 = PS2->getInjectedSpecializationType();
6336 TemplateDeductionInfo Info(Loc);
6337 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6340 bool Sema::isMoreSpecializedThanPrimary(
6341 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
6342 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
6343 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
6344 QualType PartialT = Spec->getInjectedSpecializationType();
6346 ClassTemplatePartialSpecializationDecl *MaybeSpec =
6347 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6348 if (MaybeSpec)
6349 Info.clearSFINAEDiagnostic();
6350 return MaybeSpec;
6353 VarTemplatePartialSpecializationDecl *
6354 Sema::getMoreSpecializedPartialSpecialization(
6355 VarTemplatePartialSpecializationDecl *PS1,
6356 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
6357 // Pretend the variable template specializations are class template
6358 // specializations and form a fake injected class name type for comparison.
6359 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
6360 "the partial specializations being compared should specialize"
6361 " the same template.");
6362 TemplateName Name(PS1->getSpecializedTemplate());
6363 QualType PT1 = Context.getTemplateSpecializationType(
6364 Name, PS1->getTemplateArgs().asArray());
6365 QualType PT2 = Context.getTemplateSpecializationType(
6366 Name, PS2->getTemplateArgs().asArray());
6368 TemplateDeductionInfo Info(Loc);
6369 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
6372 bool Sema::isMoreSpecializedThanPrimary(
6373 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
6374 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
6375 TemplateName Name(Primary);
6376 QualType PrimaryT = Context.getTemplateSpecializationType(
6377 Name, Primary->getInjectedTemplateArgs(Context));
6378 QualType PartialT = Context.getTemplateSpecializationType(
6379 Name, Spec->getTemplateArgs().asArray());
6381 VarTemplatePartialSpecializationDecl *MaybeSpec =
6382 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6383 if (MaybeSpec)
6384 Info.clearSFINAEDiagnostic();
6385 return MaybeSpec;
6388 bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
6389 TemplateParameterList *P, TemplateDecl *AArg,
6390 const DefaultArguments &DefaultArgs, SourceLocation Loc, bool IsDeduced) {
6391 // C++1z [temp.arg.template]p4: (DR 150)
6392 // A template template-parameter P is at least as specialized as a
6393 // template template-argument A if, given the following rewrite to two
6394 // function templates...
6396 // Rather than synthesize function templates, we merely perform the
6397 // equivalent partial ordering by performing deduction directly on
6398 // the template parameter lists of the template template parameters.
6400 TemplateParameterList *A = AArg->getTemplateParameters();
6402 // Given an invented class template X with the template parameter list of
6403 // A (including default arguments):
6404 // - Each function template has a single function parameter whose type is
6405 // a specialization of X with template arguments corresponding to the
6406 // template parameters from the respective function template
6407 SmallVector<TemplateArgument, 8> AArgs(A->getInjectedTemplateArgs(Context));
6409 // Check P's arguments against A's parameter list. This will fill in default
6410 // template arguments as needed. AArgs are already correct by construction.
6411 // We can't just use CheckTemplateIdType because that will expand alias
6412 // templates.
6413 SmallVector<TemplateArgument, 4> PArgs(P->getInjectedTemplateArgs(Context));
6415 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6416 P->getRAngleLoc());
6417 for (unsigned I = 0, N = P->size(); I != N; ++I) {
6418 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
6419 // expansions, to form an "as written" argument list.
6420 TemplateArgument Arg = PArgs[I];
6421 if (Arg.getKind() == TemplateArgument::Pack) {
6422 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
6423 Arg = *Arg.pack_begin();
6425 PArgList.addArgument(getTrivialTemplateArgumentLoc(
6426 Arg, QualType(), P->getParam(I)->getLocation()));
6428 PArgs.clear();
6430 SFINAETrap Trap(*this);
6431 // C++1z [temp.arg.template]p3:
6432 // If the rewrite produces an invalid type, then P is not at least as
6433 // specialized as A.
6434 SmallVector<TemplateArgument, 4> SugaredPArgs;
6435 if (CheckTemplateArgumentList(AArg, Loc, PArgList, DefaultArgs, false,
6436 SugaredPArgs, PArgs,
6437 /*UpdateArgsWithConversions=*/true,
6438 /*ConstraintsNotSatisfied=*/nullptr,
6439 /*PartialOrderTTP=*/true) ||
6440 Trap.hasErrorOccurred())
6441 return false;
6444 // Determine whether P1 is at least as specialized as P2.
6445 TemplateDeductionInfo Info(Loc, A->getDepth());
6446 SmallVector<DeducedTemplateArgument, 4> Deduced;
6447 Deduced.resize(A->size());
6449 // ... the function template corresponding to P is at least as specialized
6450 // as the function template corresponding to A according to the partial
6451 // ordering rules for function templates.
6453 // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6454 // applying the partial ordering rules for function templates on
6455 // the rewritten template template parameters:
6456 // - In a deduced context, the matching of packs versus fixed-size needs to
6457 // be inverted between Ps and As. On non-deduced context, matching needs to
6458 // happen both ways, according to [temp.arg.template]p3, but this is
6459 // currently implemented as a special case elsewhere.
6460 if (::DeduceTemplateArguments(*this, A, AArgs, PArgs, Info, Deduced,
6461 /*NumberOfArgumentsMustMatch=*/false,
6462 /*PartialOrdering=*/true,
6463 IsDeduced ? PackFold::ArgumentToParameter
6464 : PackFold::ParameterToArgument,
6465 /*HasDeducedAnyParam=*/nullptr) !=
6466 TemplateDeductionResult::Success)
6467 return false;
6469 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6470 Sema::InstantiatingTemplate Inst(*this, Info.getLocation(), AArg, DeducedArgs,
6471 Info);
6472 if (Inst.isInvalid())
6473 return false;
6475 bool AtLeastAsSpecialized;
6476 runWithSufficientStackSpace(Info.getLocation(), [&] {
6477 AtLeastAsSpecialized =
6478 ::FinishTemplateArgumentDeduction(
6479 *this, AArg, /*IsPartialOrdering=*/true, PArgs, Deduced, Info) ==
6480 TemplateDeductionResult::Success;
6482 return AtLeastAsSpecialized;
6485 namespace {
6486 struct MarkUsedTemplateParameterVisitor : DynamicRecursiveASTVisitor {
6487 llvm::SmallBitVector &Used;
6488 unsigned Depth;
6490 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6491 unsigned Depth)
6492 : Used(Used), Depth(Depth) { }
6494 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
6495 if (T->getDepth() == Depth)
6496 Used[T->getIndex()] = true;
6497 return true;
6500 bool TraverseTemplateName(TemplateName Template) override {
6501 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6502 Template.getAsTemplateDecl()))
6503 if (TTP->getDepth() == Depth)
6504 Used[TTP->getIndex()] = true;
6505 DynamicRecursiveASTVisitor::TraverseTemplateName(Template);
6506 return true;
6509 bool VisitDeclRefExpr(DeclRefExpr *E) override {
6510 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6511 if (NTTP->getDepth() == Depth)
6512 Used[NTTP->getIndex()] = true;
6513 return true;
6518 /// Mark the template parameters that are used by the given
6519 /// expression.
6520 static void
6521 MarkUsedTemplateParameters(ASTContext &Ctx,
6522 const Expr *E,
6523 bool OnlyDeduced,
6524 unsigned Depth,
6525 llvm::SmallBitVector &Used) {
6526 if (!OnlyDeduced) {
6527 MarkUsedTemplateParameterVisitor(Used, Depth)
6528 .TraverseStmt(const_cast<Expr *>(E));
6529 return;
6532 // We can deduce from a pack expansion.
6533 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
6534 E = Expansion->getPattern();
6536 const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(E, Depth);
6537 if (!NTTP)
6538 return;
6540 if (NTTP->getDepth() == Depth)
6541 Used[NTTP->getIndex()] = true;
6543 // In C++17 mode, additional arguments may be deduced from the type of a
6544 // non-type argument.
6545 if (Ctx.getLangOpts().CPlusPlus17)
6546 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
6549 /// Mark the template parameters that are used by the given
6550 /// nested name specifier.
6551 static void
6552 MarkUsedTemplateParameters(ASTContext &Ctx,
6553 NestedNameSpecifier *NNS,
6554 bool OnlyDeduced,
6555 unsigned Depth,
6556 llvm::SmallBitVector &Used) {
6557 if (!NNS)
6558 return;
6560 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
6561 Used);
6562 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
6563 OnlyDeduced, Depth, Used);
6566 /// Mark the template parameters that are used by the given
6567 /// template name.
6568 static void
6569 MarkUsedTemplateParameters(ASTContext &Ctx,
6570 TemplateName Name,
6571 bool OnlyDeduced,
6572 unsigned Depth,
6573 llvm::SmallBitVector &Used) {
6574 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
6575 if (TemplateTemplateParmDecl *TTP
6576 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
6577 if (TTP->getDepth() == Depth)
6578 Used[TTP->getIndex()] = true;
6580 return;
6583 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
6584 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
6585 Depth, Used);
6586 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
6587 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
6588 Depth, Used);
6591 /// Mark the template parameters that are used by the given
6592 /// type.
6593 static void
6594 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
6595 bool OnlyDeduced,
6596 unsigned Depth,
6597 llvm::SmallBitVector &Used) {
6598 if (T.isNull())
6599 return;
6601 // Non-dependent types have nothing deducible
6602 if (!T->isDependentType())
6603 return;
6605 T = Ctx.getCanonicalType(T);
6606 switch (T->getTypeClass()) {
6607 case Type::Pointer:
6608 MarkUsedTemplateParameters(Ctx,
6609 cast<PointerType>(T)->getPointeeType(),
6610 OnlyDeduced,
6611 Depth,
6612 Used);
6613 break;
6615 case Type::BlockPointer:
6616 MarkUsedTemplateParameters(Ctx,
6617 cast<BlockPointerType>(T)->getPointeeType(),
6618 OnlyDeduced,
6619 Depth,
6620 Used);
6621 break;
6623 case Type::LValueReference:
6624 case Type::RValueReference:
6625 MarkUsedTemplateParameters(Ctx,
6626 cast<ReferenceType>(T)->getPointeeType(),
6627 OnlyDeduced,
6628 Depth,
6629 Used);
6630 break;
6632 case Type::MemberPointer: {
6633 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
6634 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
6635 Depth, Used);
6636 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
6637 OnlyDeduced, Depth, Used);
6638 break;
6641 case Type::DependentSizedArray:
6642 MarkUsedTemplateParameters(Ctx,
6643 cast<DependentSizedArrayType>(T)->getSizeExpr(),
6644 OnlyDeduced, Depth, Used);
6645 // Fall through to check the element type
6646 [[fallthrough]];
6648 case Type::ConstantArray:
6649 case Type::IncompleteArray:
6650 case Type::ArrayParameter:
6651 MarkUsedTemplateParameters(Ctx,
6652 cast<ArrayType>(T)->getElementType(),
6653 OnlyDeduced, Depth, Used);
6654 break;
6655 case Type::Vector:
6656 case Type::ExtVector:
6657 MarkUsedTemplateParameters(Ctx,
6658 cast<VectorType>(T)->getElementType(),
6659 OnlyDeduced, Depth, Used);
6660 break;
6662 case Type::DependentVector: {
6663 const auto *VecType = cast<DependentVectorType>(T);
6664 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6665 Depth, Used);
6666 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
6667 Used);
6668 break;
6670 case Type::DependentSizedExtVector: {
6671 const DependentSizedExtVectorType *VecType
6672 = cast<DependentSizedExtVectorType>(T);
6673 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
6674 Depth, Used);
6675 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
6676 Depth, Used);
6677 break;
6680 case Type::DependentAddressSpace: {
6681 const DependentAddressSpaceType *DependentASType =
6682 cast<DependentAddressSpaceType>(T);
6683 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6684 OnlyDeduced, Depth, Used);
6685 MarkUsedTemplateParameters(Ctx,
6686 DependentASType->getAddrSpaceExpr(),
6687 OnlyDeduced, Depth, Used);
6688 break;
6691 case Type::ConstantMatrix: {
6692 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6693 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6694 Depth, Used);
6695 break;
6698 case Type::DependentSizedMatrix: {
6699 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6700 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6701 Depth, Used);
6702 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6703 Used);
6704 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6705 Depth, Used);
6706 break;
6709 case Type::FunctionProto: {
6710 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6711 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6712 Used);
6713 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6714 // C++17 [temp.deduct.type]p5:
6715 // The non-deduced contexts are: [...]
6716 // -- A function parameter pack that does not occur at the end of the
6717 // parameter-declaration-list.
6718 if (!OnlyDeduced || I + 1 == N ||
6719 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6720 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6721 Depth, Used);
6722 } else {
6723 // FIXME: C++17 [temp.deduct.call]p1:
6724 // When a function parameter pack appears in a non-deduced context,
6725 // the type of that pack is never deduced.
6727 // We should also track a set of "never deduced" parameters, and
6728 // subtract that from the list of deduced parameters after marking.
6731 if (auto *E = Proto->getNoexceptExpr())
6732 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6733 break;
6736 case Type::TemplateTypeParm: {
6737 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6738 if (TTP->getDepth() == Depth)
6739 Used[TTP->getIndex()] = true;
6740 break;
6743 case Type::SubstTemplateTypeParmPack: {
6744 const SubstTemplateTypeParmPackType *Subst
6745 = cast<SubstTemplateTypeParmPackType>(T);
6746 if (Subst->getReplacedParameter()->getDepth() == Depth)
6747 Used[Subst->getIndex()] = true;
6748 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
6749 OnlyDeduced, Depth, Used);
6750 break;
6753 case Type::InjectedClassName:
6754 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6755 [[fallthrough]];
6757 case Type::TemplateSpecialization: {
6758 const TemplateSpecializationType *Spec
6759 = cast<TemplateSpecializationType>(T);
6760 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6761 Depth, Used);
6763 // C++0x [temp.deduct.type]p9:
6764 // If the template argument list of P contains a pack expansion that is
6765 // not the last template argument, the entire template argument list is a
6766 // non-deduced context.
6767 if (OnlyDeduced &&
6768 hasPackExpansionBeforeEnd(Spec->template_arguments()))
6769 break;
6771 for (const auto &Arg : Spec->template_arguments())
6772 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6773 break;
6776 case Type::Complex:
6777 if (!OnlyDeduced)
6778 MarkUsedTemplateParameters(Ctx,
6779 cast<ComplexType>(T)->getElementType(),
6780 OnlyDeduced, Depth, Used);
6781 break;
6783 case Type::Atomic:
6784 if (!OnlyDeduced)
6785 MarkUsedTemplateParameters(Ctx,
6786 cast<AtomicType>(T)->getValueType(),
6787 OnlyDeduced, Depth, Used);
6788 break;
6790 case Type::DependentName:
6791 if (!OnlyDeduced)
6792 MarkUsedTemplateParameters(Ctx,
6793 cast<DependentNameType>(T)->getQualifier(),
6794 OnlyDeduced, Depth, Used);
6795 break;
6797 case Type::DependentTemplateSpecialization: {
6798 // C++14 [temp.deduct.type]p5:
6799 // The non-deduced contexts are:
6800 // -- The nested-name-specifier of a type that was specified using a
6801 // qualified-id
6803 // C++14 [temp.deduct.type]p6:
6804 // When a type name is specified in a way that includes a non-deduced
6805 // context, all of the types that comprise that type name are also
6806 // non-deduced.
6807 if (OnlyDeduced)
6808 break;
6810 const DependentTemplateSpecializationType *Spec
6811 = cast<DependentTemplateSpecializationType>(T);
6813 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
6814 OnlyDeduced, Depth, Used);
6816 for (const auto &Arg : Spec->template_arguments())
6817 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6818 break;
6821 case Type::TypeOf:
6822 if (!OnlyDeduced)
6823 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
6824 OnlyDeduced, Depth, Used);
6825 break;
6827 case Type::TypeOfExpr:
6828 if (!OnlyDeduced)
6829 MarkUsedTemplateParameters(Ctx,
6830 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
6831 OnlyDeduced, Depth, Used);
6832 break;
6834 case Type::Decltype:
6835 if (!OnlyDeduced)
6836 MarkUsedTemplateParameters(Ctx,
6837 cast<DecltypeType>(T)->getUnderlyingExpr(),
6838 OnlyDeduced, Depth, Used);
6839 break;
6841 case Type::PackIndexing:
6842 if (!OnlyDeduced) {
6843 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
6844 OnlyDeduced, Depth, Used);
6845 MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
6846 OnlyDeduced, Depth, Used);
6848 break;
6850 case Type::UnaryTransform:
6851 if (!OnlyDeduced)
6852 MarkUsedTemplateParameters(Ctx,
6853 cast<UnaryTransformType>(T)->getUnderlyingType(),
6854 OnlyDeduced, Depth, Used);
6855 break;
6857 case Type::PackExpansion:
6858 MarkUsedTemplateParameters(Ctx,
6859 cast<PackExpansionType>(T)->getPattern(),
6860 OnlyDeduced, Depth, Used);
6861 break;
6863 case Type::Auto:
6864 case Type::DeducedTemplateSpecialization:
6865 MarkUsedTemplateParameters(Ctx,
6866 cast<DeducedType>(T)->getDeducedType(),
6867 OnlyDeduced, Depth, Used);
6868 break;
6869 case Type::DependentBitInt:
6870 MarkUsedTemplateParameters(Ctx,
6871 cast<DependentBitIntType>(T)->getNumBitsExpr(),
6872 OnlyDeduced, Depth, Used);
6873 break;
6875 case Type::HLSLAttributedResource:
6876 MarkUsedTemplateParameters(
6877 Ctx, cast<HLSLAttributedResourceType>(T)->getWrappedType(), OnlyDeduced,
6878 Depth, Used);
6879 if (cast<HLSLAttributedResourceType>(T)->hasContainedType())
6880 MarkUsedTemplateParameters(
6881 Ctx, cast<HLSLAttributedResourceType>(T)->getContainedType(),
6882 OnlyDeduced, Depth, Used);
6883 break;
6885 // None of these types have any template parameters in them.
6886 case Type::Builtin:
6887 case Type::VariableArray:
6888 case Type::FunctionNoProto:
6889 case Type::Record:
6890 case Type::Enum:
6891 case Type::ObjCInterface:
6892 case Type::ObjCObject:
6893 case Type::ObjCObjectPointer:
6894 case Type::UnresolvedUsing:
6895 case Type::Pipe:
6896 case Type::BitInt:
6897 #define TYPE(Class, Base)
6898 #define ABSTRACT_TYPE(Class, Base)
6899 #define DEPENDENT_TYPE(Class, Base)
6900 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6901 #include "clang/AST/TypeNodes.inc"
6902 break;
6906 /// Mark the template parameters that are used by this
6907 /// template argument.
6908 static void
6909 MarkUsedTemplateParameters(ASTContext &Ctx,
6910 const TemplateArgument &TemplateArg,
6911 bool OnlyDeduced,
6912 unsigned Depth,
6913 llvm::SmallBitVector &Used) {
6914 switch (TemplateArg.getKind()) {
6915 case TemplateArgument::Null:
6916 case TemplateArgument::Integral:
6917 case TemplateArgument::Declaration:
6918 case TemplateArgument::NullPtr:
6919 case TemplateArgument::StructuralValue:
6920 break;
6922 case TemplateArgument::Type:
6923 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
6924 Depth, Used);
6925 break;
6927 case TemplateArgument::Template:
6928 case TemplateArgument::TemplateExpansion:
6929 MarkUsedTemplateParameters(Ctx,
6930 TemplateArg.getAsTemplateOrTemplatePattern(),
6931 OnlyDeduced, Depth, Used);
6932 break;
6934 case TemplateArgument::Expression:
6935 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
6936 Depth, Used);
6937 break;
6939 case TemplateArgument::Pack:
6940 for (const auto &P : TemplateArg.pack_elements())
6941 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
6942 break;
6946 void
6947 Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6948 unsigned Depth,
6949 llvm::SmallBitVector &Used) {
6950 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6953 void
6954 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6955 bool OnlyDeduced, unsigned Depth,
6956 llvm::SmallBitVector &Used) {
6957 // C++0x [temp.deduct.type]p9:
6958 // If the template argument list of P contains a pack expansion that is not
6959 // the last template argument, the entire template argument list is a
6960 // non-deduced context.
6961 if (OnlyDeduced &&
6962 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
6963 return;
6965 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6966 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
6967 Depth, Used);
6970 void Sema::MarkDeducedTemplateParameters(
6971 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
6972 llvm::SmallBitVector &Deduced) {
6973 TemplateParameterList *TemplateParams
6974 = FunctionTemplate->getTemplateParameters();
6975 Deduced.clear();
6976 Deduced.resize(TemplateParams->size());
6978 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
6979 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
6980 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
6981 true, TemplateParams->getDepth(), Deduced);
6984 bool hasDeducibleTemplateParameters(Sema &S,
6985 FunctionTemplateDecl *FunctionTemplate,
6986 QualType T) {
6987 if (!T->isDependentType())
6988 return false;
6990 TemplateParameterList *TemplateParams
6991 = FunctionTemplate->getTemplateParameters();
6992 llvm::SmallBitVector Deduced(TemplateParams->size());
6993 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
6994 Deduced);
6996 return Deduced.any();