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