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