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

source code of clang/lib/Sema/SemaTemplateDeduction.cpp