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