xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements C++ template argument deduction.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "TreeTransform.h"
140b57cec5SDimitry Andric #include "TypeLocBuilder.h"
150b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
160b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h"
170b57cec5SDimitry Andric #include "clang/AST/Decl.h"
180b57cec5SDimitry Andric #include "clang/AST/DeclAccessPair.h"
190b57cec5SDimitry Andric #include "clang/AST/DeclBase.h"
200b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
210b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
220b57cec5SDimitry Andric #include "clang/AST/DeclarationName.h"
230b57cec5SDimitry Andric #include "clang/AST/Expr.h"
240b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
250b57cec5SDimitry Andric #include "clang/AST/NestedNameSpecifier.h"
26480093f4SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
270b57cec5SDimitry Andric #include "clang/AST/TemplateBase.h"
280b57cec5SDimitry Andric #include "clang/AST/TemplateName.h"
290b57cec5SDimitry Andric #include "clang/AST/Type.h"
300b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
310b57cec5SDimitry Andric #include "clang/AST/UnresolvedSet.h"
320b57cec5SDimitry Andric #include "clang/Basic/AddressSpaces.h"
330b57cec5SDimitry Andric #include "clang/Basic/ExceptionSpecificationType.h"
340b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
350b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
360b57cec5SDimitry Andric #include "clang/Basic/PartialDiagnostic.h"
370b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
380b57cec5SDimitry Andric #include "clang/Basic/Specifiers.h"
3906c3fb27SDimitry Andric #include "clang/Sema/EnterExpressionEvaluationContext.h"
400b57cec5SDimitry Andric #include "clang/Sema/Ownership.h"
410b57cec5SDimitry Andric #include "clang/Sema/Sema.h"
420b57cec5SDimitry Andric #include "clang/Sema/Template.h"
4306c3fb27SDimitry Andric #include "clang/Sema/TemplateDeduction.h"
440b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
450b57cec5SDimitry Andric #include "llvm/ADT/APSInt.h"
460b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
470b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
480b57cec5SDimitry Andric #include "llvm/ADT/FoldingSet.h"
490b57cec5SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
500b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
510b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
520b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
530b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
540b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
550b57cec5SDimitry Andric #include <algorithm>
560b57cec5SDimitry Andric #include <cassert>
57bdd1243dSDimitry Andric #include <optional>
580b57cec5SDimitry Andric #include <tuple>
59bdd1243dSDimitry Andric #include <type_traits>
600b57cec5SDimitry Andric #include <utility>
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric namespace clang {
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric   /// Various flags that control template argument deduction.
650b57cec5SDimitry Andric   ///
660b57cec5SDimitry Andric   /// These flags can be bitwise-OR'd together.
670b57cec5SDimitry Andric   enum TemplateDeductionFlags {
680b57cec5SDimitry Andric     /// No template argument deduction flags, which indicates the
690b57cec5SDimitry Andric     /// strictest results for template argument deduction (as used for, e.g.,
700b57cec5SDimitry Andric     /// matching class template partial specializations).
710b57cec5SDimitry Andric     TDF_None = 0,
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric     /// Within template argument deduction from a function call, we are
740b57cec5SDimitry Andric     /// matching with a parameter type for which the original parameter was
750b57cec5SDimitry Andric     /// a reference.
760b57cec5SDimitry Andric     TDF_ParamWithReferenceType = 0x1,
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric     /// Within template argument deduction from a function call, we
790b57cec5SDimitry Andric     /// are matching in a case where we ignore cv-qualifiers.
800b57cec5SDimitry Andric     TDF_IgnoreQualifiers = 0x02,
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric     /// Within template argument deduction from a function call,
830b57cec5SDimitry Andric     /// we are matching in a case where we can perform template argument
840b57cec5SDimitry Andric     /// deduction from a template-id of a derived class of the argument type.
850b57cec5SDimitry Andric     TDF_DerivedClass = 0x04,
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric     /// Allow non-dependent types to differ, e.g., when performing
880b57cec5SDimitry Andric     /// template argument deduction from a function call where conversions
890b57cec5SDimitry Andric     /// may apply.
900b57cec5SDimitry Andric     TDF_SkipNonDependent = 0x08,
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric     /// Whether we are performing template argument deduction for
930b57cec5SDimitry Andric     /// parameters and arguments in a top-level template argument
940b57cec5SDimitry Andric     TDF_TopLevelParameterTypeList = 0x10,
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric     /// Within template argument deduction from overload resolution per
970b57cec5SDimitry Andric     /// C++ [over.over] allow matching function types that are compatible in
980b57cec5SDimitry Andric     /// terms of noreturn and default calling convention adjustments, or
990b57cec5SDimitry Andric     /// similarly matching a declared template specialization against a
1000b57cec5SDimitry Andric     /// possible template, per C++ [temp.deduct.decl]. In either case, permit
1010b57cec5SDimitry Andric     /// deduction where the parameter is a function type that can be converted
1020b57cec5SDimitry Andric     /// to the argument type.
1030b57cec5SDimitry Andric     TDF_AllowCompatibleFunctionType = 0x20,
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric     /// Within template argument deduction for a conversion function, we are
1060b57cec5SDimitry Andric     /// matching with an argument type for which the original argument was
1070b57cec5SDimitry Andric     /// a reference.
1080b57cec5SDimitry Andric     TDF_ArgWithReferenceType = 0x40,
1090b57cec5SDimitry Andric   };
1100b57cec5SDimitry Andric }
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric using namespace clang;
1130b57cec5SDimitry Andric using namespace sema;
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric /// Compare two APSInts, extending and switching the sign as
1160b57cec5SDimitry Andric /// necessary to compare their values regardless of underlying type.
hasSameExtendedValue(llvm::APSInt X,llvm::APSInt Y)1170b57cec5SDimitry Andric static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
1180b57cec5SDimitry Andric   if (Y.getBitWidth() > X.getBitWidth())
1190b57cec5SDimitry Andric     X = X.extend(Y.getBitWidth());
1200b57cec5SDimitry Andric   else if (Y.getBitWidth() < X.getBitWidth())
1210b57cec5SDimitry Andric     Y = Y.extend(X.getBitWidth());
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   // If there is a signedness mismatch, correct it.
1240b57cec5SDimitry Andric   if (X.isSigned() != Y.isSigned()) {
1250b57cec5SDimitry Andric     // If the signed value is negative, then the values cannot be the same.
1260b57cec5SDimitry Andric     if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
1270b57cec5SDimitry Andric       return false;
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric     Y.setIsSigned(true);
1300b57cec5SDimitry Andric     X.setIsSigned(true);
1310b57cec5SDimitry Andric   }
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   return X == Y;
1340b57cec5SDimitry Andric }
1350b57cec5SDimitry Andric 
136*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
137349cc55cSDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, QualType Param,
138349cc55cSDimitry Andric     QualType Arg, TemplateDeductionInfo &Info,
139349cc55cSDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
140349cc55cSDimitry Andric     bool PartialOrdering = false, bool DeducedFromArrayBound = false);
1410b57cec5SDimitry Andric 
142*0fca6ea1SDimitry Andric enum class PackFold { ParameterToArgument, ArgumentToParameter };
143*0fca6ea1SDimitry Andric static TemplateDeductionResult
1440b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
145349cc55cSDimitry Andric                         ArrayRef<TemplateArgument> Ps,
146349cc55cSDimitry Andric                         ArrayRef<TemplateArgument> As,
1470b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
1480b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
149*0fca6ea1SDimitry Andric                         bool NumberOfArgumentsMustMatch,
150*0fca6ea1SDimitry Andric                         PackFold PackFold = PackFold::ParameterToArgument);
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric static void MarkUsedTemplateParameters(ASTContext &Ctx,
1530b57cec5SDimitry Andric                                        const TemplateArgument &TemplateArg,
1540b57cec5SDimitry Andric                                        bool OnlyDeduced, unsigned Depth,
1550b57cec5SDimitry Andric                                        llvm::SmallBitVector &Used);
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
1580b57cec5SDimitry Andric                                        bool OnlyDeduced, unsigned Level,
1590b57cec5SDimitry Andric                                        llvm::SmallBitVector &Deduced);
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric /// If the given expression is of a form that permits the deduction
1620b57cec5SDimitry Andric /// of a non-type template parameter, return the declaration of that
1630b57cec5SDimitry Andric /// non-type template parameter.
164e8d8bef9SDimitry Andric static const NonTypeTemplateParmDecl *
getDeducedParameterFromExpr(const Expr * E,unsigned Depth)165e8d8bef9SDimitry Andric getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
1660b57cec5SDimitry Andric   // If we are within an alias template, the expression may have undergone
1670b57cec5SDimitry Andric   // any number of parameter substitutions already.
1680b57cec5SDimitry Andric   while (true) {
169e8d8bef9SDimitry Andric     if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
1700b57cec5SDimitry Andric       E = IC->getSubExpr();
171e8d8bef9SDimitry Andric     else if (const auto *CE = dyn_cast<ConstantExpr>(E))
1720b57cec5SDimitry Andric       E = CE->getSubExpr();
173e8d8bef9SDimitry Andric     else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
1740b57cec5SDimitry Andric       E = Subst->getReplacement();
175e8d8bef9SDimitry Andric     else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
176e8d8bef9SDimitry Andric       // Look through implicit copy construction from an lvalue of the same type.
177e8d8bef9SDimitry Andric       if (CCE->getParenOrBraceRange().isValid())
178e8d8bef9SDimitry Andric         break;
179e8d8bef9SDimitry Andric       // Note, there could be default arguments.
180e8d8bef9SDimitry Andric       assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg");
181e8d8bef9SDimitry Andric       E = CCE->getArg(0);
182e8d8bef9SDimitry Andric     } else
1830b57cec5SDimitry Andric       break;
1840b57cec5SDimitry Andric   }
1850b57cec5SDimitry Andric 
186e8d8bef9SDimitry Andric   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
187e8d8bef9SDimitry Andric     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
188e8d8bef9SDimitry Andric       if (NTTP->getDepth() == Depth)
1890b57cec5SDimitry Andric         return NTTP;
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric   return nullptr;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
194e8d8bef9SDimitry Andric static const NonTypeTemplateParmDecl *
getDeducedParameterFromExpr(TemplateDeductionInfo & Info,Expr * E)195e8d8bef9SDimitry Andric getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
196e8d8bef9SDimitry Andric   return getDeducedParameterFromExpr(E, Info.getDeducedDepth());
197e8d8bef9SDimitry Andric }
198e8d8bef9SDimitry Andric 
1990b57cec5SDimitry Andric /// Determine whether two declaration pointers refer to the same
2000b57cec5SDimitry Andric /// declaration.
isSameDeclaration(Decl * X,Decl * Y)2010b57cec5SDimitry Andric static bool isSameDeclaration(Decl *X, Decl *Y) {
2020b57cec5SDimitry Andric   if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
2030b57cec5SDimitry Andric     X = NX->getUnderlyingDecl();
2040b57cec5SDimitry Andric   if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
2050b57cec5SDimitry Andric     Y = NY->getUnderlyingDecl();
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   return X->getCanonicalDecl() == Y->getCanonicalDecl();
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric /// Verify that the given, deduced template arguments are compatible.
2110b57cec5SDimitry Andric ///
2120b57cec5SDimitry Andric /// \returns The deduced template argument, or a NULL template argument if
2130b57cec5SDimitry Andric /// the deduced template arguments were incompatible.
2140b57cec5SDimitry Andric static DeducedTemplateArgument
checkDeducedTemplateArguments(ASTContext & Context,const DeducedTemplateArgument & X,const DeducedTemplateArgument & Y,bool AggregateCandidateDeduction=false)2150b57cec5SDimitry Andric checkDeducedTemplateArguments(ASTContext &Context,
2160b57cec5SDimitry Andric                               const DeducedTemplateArgument &X,
21706c3fb27SDimitry Andric                               const DeducedTemplateArgument &Y,
21806c3fb27SDimitry Andric                               bool AggregateCandidateDeduction = false) {
2190b57cec5SDimitry Andric   // We have no deduction for one or both of the arguments; they're compatible.
2200b57cec5SDimitry Andric   if (X.isNull())
2210b57cec5SDimitry Andric     return Y;
2220b57cec5SDimitry Andric   if (Y.isNull())
2230b57cec5SDimitry Andric     return X;
2240b57cec5SDimitry Andric 
2250b57cec5SDimitry Andric   // If we have two non-type template argument values deduced for the same
2260b57cec5SDimitry Andric   // parameter, they must both match the type of the parameter, and thus must
2270b57cec5SDimitry Andric   // match each other's type. As we're only keeping one of them, we must check
2280b57cec5SDimitry Andric   // for that now. The exception is that if either was deduced from an array
2290b57cec5SDimitry Andric   // bound, the type is permitted to differ.
2300b57cec5SDimitry Andric   if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
2310b57cec5SDimitry Andric     QualType XType = X.getNonTypeTemplateArgumentType();
2320b57cec5SDimitry Andric     if (!XType.isNull()) {
2330b57cec5SDimitry Andric       QualType YType = Y.getNonTypeTemplateArgumentType();
2340b57cec5SDimitry Andric       if (YType.isNull() || !Context.hasSameType(XType, YType))
2350b57cec5SDimitry Andric         return DeducedTemplateArgument();
2360b57cec5SDimitry Andric     }
2370b57cec5SDimitry Andric   }
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric   switch (X.getKind()) {
2400b57cec5SDimitry Andric   case TemplateArgument::Null:
2410b57cec5SDimitry Andric     llvm_unreachable("Non-deduced template arguments handled above");
2420b57cec5SDimitry Andric 
243bdd1243dSDimitry Andric   case TemplateArgument::Type: {
2440b57cec5SDimitry Andric     // If two template type arguments have the same type, they're compatible.
245bdd1243dSDimitry Andric     QualType TX = X.getAsType(), TY = Y.getAsType();
246bdd1243dSDimitry Andric     if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
247bdd1243dSDimitry Andric       return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
248bdd1243dSDimitry Andric                                      X.wasDeducedFromArrayBound() ||
249bdd1243dSDimitry Andric                                          Y.wasDeducedFromArrayBound());
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric     // If one of the two arguments was deduced from an array bound, the other
2520b57cec5SDimitry Andric     // supersedes it.
2530b57cec5SDimitry Andric     if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
2540b57cec5SDimitry Andric       return X.wasDeducedFromArrayBound() ? Y : X;
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric     // The arguments are not compatible.
2570b57cec5SDimitry Andric     return DeducedTemplateArgument();
258bdd1243dSDimitry Andric   }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric   case TemplateArgument::Integral:
2610b57cec5SDimitry Andric     // If we deduced a constant in one case and either a dependent expression or
2620b57cec5SDimitry Andric     // declaration in another case, keep the integral constant.
2630b57cec5SDimitry Andric     // If both are integral constants with the same value, keep that value.
2640b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Expression ||
2650b57cec5SDimitry Andric         Y.getKind() == TemplateArgument::Declaration ||
2660b57cec5SDimitry Andric         (Y.getKind() == TemplateArgument::Integral &&
2670b57cec5SDimitry Andric          hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
2680b57cec5SDimitry Andric       return X.wasDeducedFromArrayBound() ? Y : X;
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric     // All other combinations are incompatible.
2710b57cec5SDimitry Andric     return DeducedTemplateArgument();
2720b57cec5SDimitry Andric 
2737a6dacacSDimitry Andric   case TemplateArgument::StructuralValue:
2747a6dacacSDimitry Andric     // If we deduced a value and a dependent expression, keep the value.
2757a6dacacSDimitry Andric     if (Y.getKind() == TemplateArgument::Expression ||
2767a6dacacSDimitry Andric         (Y.getKind() == TemplateArgument::StructuralValue &&
2777a6dacacSDimitry Andric          X.structurallyEquals(Y)))
2787a6dacacSDimitry Andric       return X;
2797a6dacacSDimitry Andric 
2807a6dacacSDimitry Andric     // All other combinations are incompatible.
2817a6dacacSDimitry Andric     return DeducedTemplateArgument();
2827a6dacacSDimitry Andric 
2830b57cec5SDimitry Andric   case TemplateArgument::Template:
2840b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Template &&
2850b57cec5SDimitry Andric         Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
2860b57cec5SDimitry Andric       return X;
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric     // All other combinations are incompatible.
2890b57cec5SDimitry Andric     return DeducedTemplateArgument();
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   case TemplateArgument::TemplateExpansion:
2920b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::TemplateExpansion &&
2930b57cec5SDimitry Andric         Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
2940b57cec5SDimitry Andric                                     Y.getAsTemplateOrTemplatePattern()))
2950b57cec5SDimitry Andric       return X;
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric     // All other combinations are incompatible.
2980b57cec5SDimitry Andric     return DeducedTemplateArgument();
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   case TemplateArgument::Expression: {
3010b57cec5SDimitry Andric     if (Y.getKind() != TemplateArgument::Expression)
3020b57cec5SDimitry Andric       return checkDeducedTemplateArguments(Context, Y, X);
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric     // Compare the expressions for equality
3050b57cec5SDimitry Andric     llvm::FoldingSetNodeID ID1, ID2;
3060b57cec5SDimitry Andric     X.getAsExpr()->Profile(ID1, Context, true);
3070b57cec5SDimitry Andric     Y.getAsExpr()->Profile(ID2, Context, true);
3080b57cec5SDimitry Andric     if (ID1 == ID2)
3090b57cec5SDimitry Andric       return X.wasDeducedFromArrayBound() ? Y : X;
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric     // Differing dependent expressions are incompatible.
3120b57cec5SDimitry Andric     return DeducedTemplateArgument();
3130b57cec5SDimitry Andric   }
3140b57cec5SDimitry Andric 
3150b57cec5SDimitry Andric   case TemplateArgument::Declaration:
3160b57cec5SDimitry Andric     assert(!X.wasDeducedFromArrayBound());
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric     // If we deduced a declaration and a dependent expression, keep the
3190b57cec5SDimitry Andric     // declaration.
3200b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Expression)
3210b57cec5SDimitry Andric       return X;
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric     // If we deduced a declaration and an integral constant, keep the
3240b57cec5SDimitry Andric     // integral constant and whichever type did not come from an array
3250b57cec5SDimitry Andric     // bound.
3260b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Integral) {
3270b57cec5SDimitry Andric       if (Y.wasDeducedFromArrayBound())
3280b57cec5SDimitry Andric         return TemplateArgument(Context, Y.getAsIntegral(),
3290b57cec5SDimitry Andric                                 X.getParamTypeForDecl());
3300b57cec5SDimitry Andric       return Y;
3310b57cec5SDimitry Andric     }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric     // If we deduced two declarations, make sure that they refer to the
3340b57cec5SDimitry Andric     // same declaration.
3350b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Declaration &&
3360b57cec5SDimitry Andric         isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
3370b57cec5SDimitry Andric       return X;
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric     // All other combinations are incompatible.
3400b57cec5SDimitry Andric     return DeducedTemplateArgument();
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   case TemplateArgument::NullPtr:
3430b57cec5SDimitry Andric     // If we deduced a null pointer and a dependent expression, keep the
3440b57cec5SDimitry Andric     // null pointer.
3450b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Expression)
346bdd1243dSDimitry Andric       return TemplateArgument(Context.getCommonSugaredType(
347bdd1243dSDimitry Andric                                   X.getNullPtrType(), Y.getAsExpr()->getType()),
348bdd1243dSDimitry Andric                               true);
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric     // If we deduced a null pointer and an integral constant, keep the
3510b57cec5SDimitry Andric     // integral constant.
3520b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Integral)
3530b57cec5SDimitry Andric       return Y;
3540b57cec5SDimitry Andric 
3550b57cec5SDimitry Andric     // If we deduced two null pointers, they are the same.
3560b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::NullPtr)
357bdd1243dSDimitry Andric       return TemplateArgument(
358bdd1243dSDimitry Andric           Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
359bdd1243dSDimitry Andric           true);
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric     // All other combinations are incompatible.
3620b57cec5SDimitry Andric     return DeducedTemplateArgument();
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   case TemplateArgument::Pack: {
3650b57cec5SDimitry Andric     if (Y.getKind() != TemplateArgument::Pack ||
36606c3fb27SDimitry Andric         (!AggregateCandidateDeduction && X.pack_size() != Y.pack_size()))
3670b57cec5SDimitry Andric       return DeducedTemplateArgument();
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric     llvm::SmallVector<TemplateArgument, 8> NewPack;
37006c3fb27SDimitry Andric     for (TemplateArgument::pack_iterator
37106c3fb27SDimitry Andric              XA = X.pack_begin(),
37206c3fb27SDimitry Andric              XAEnd = X.pack_end(), YA = Y.pack_begin(), YAEnd = Y.pack_end();
3730b57cec5SDimitry Andric          XA != XAEnd; ++XA, ++YA) {
37406c3fb27SDimitry Andric       if (YA != YAEnd) {
3750b57cec5SDimitry Andric         TemplateArgument Merged = checkDeducedTemplateArguments(
3760b57cec5SDimitry Andric             Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
3770b57cec5SDimitry Andric             DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
3785ffd83dbSDimitry Andric         if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
3790b57cec5SDimitry Andric           return DeducedTemplateArgument();
3800b57cec5SDimitry Andric         NewPack.push_back(Merged);
38106c3fb27SDimitry Andric       } else {
38206c3fb27SDimitry Andric         NewPack.push_back(*XA);
38306c3fb27SDimitry Andric       }
3840b57cec5SDimitry Andric     }
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric     return DeducedTemplateArgument(
3870b57cec5SDimitry Andric         TemplateArgument::CreatePackCopy(Context, NewPack),
3880b57cec5SDimitry Andric         X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
3890b57cec5SDimitry Andric   }
3900b57cec5SDimitry Andric   }
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   llvm_unreachable("Invalid TemplateArgument Kind!");
3930b57cec5SDimitry Andric }
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
3960b57cec5SDimitry Andric /// as the given deduced template argument. All non-type template parameter
3970b57cec5SDimitry Andric /// deduction is funneled through here.
DeduceNonTypeTemplateArgument(Sema & S,TemplateParameterList * TemplateParams,const NonTypeTemplateParmDecl * NTTP,const DeducedTemplateArgument & NewDeduced,QualType ValueType,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced)398*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceNonTypeTemplateArgument(
3990b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
400*0fca6ea1SDimitry Andric     const NonTypeTemplateParmDecl *NTTP,
401*0fca6ea1SDimitry Andric     const DeducedTemplateArgument &NewDeduced, QualType ValueType,
402*0fca6ea1SDimitry Andric     TemplateDeductionInfo &Info,
4030b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
4040b57cec5SDimitry Andric   assert(NTTP->getDepth() == Info.getDeducedDepth() &&
4050b57cec5SDimitry Andric          "deducing non-type template argument with wrong depth");
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   DeducedTemplateArgument Result = checkDeducedTemplateArguments(
4080b57cec5SDimitry Andric       S.Context, Deduced[NTTP->getIndex()], NewDeduced);
4090b57cec5SDimitry Andric   if (Result.isNull()) {
410e8d8bef9SDimitry Andric     Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
4110b57cec5SDimitry Andric     Info.FirstArg = Deduced[NTTP->getIndex()];
4120b57cec5SDimitry Andric     Info.SecondArg = NewDeduced;
413*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Inconsistent;
4140b57cec5SDimitry Andric   }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric   Deduced[NTTP->getIndex()] = Result;
4170b57cec5SDimitry Andric   if (!S.getLangOpts().CPlusPlus17)
418*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   if (NTTP->isExpandedParameterPack())
4210b57cec5SDimitry Andric     // FIXME: We may still need to deduce parts of the type here! But we
4220b57cec5SDimitry Andric     // don't have any way to find which slice of the type to use, and the
4230b57cec5SDimitry Andric     // type stored on the NTTP itself is nonsense. Perhaps the type of an
4240b57cec5SDimitry Andric     // expanded NTTP should be a pack expansion type?
425*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric   // Get the type of the parameter for deduction. If it's a (dependent) array
4280b57cec5SDimitry Andric   // or function type, we will not have decayed it yet, so do that now.
4290b57cec5SDimitry Andric   QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
4300b57cec5SDimitry Andric   if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
4310b57cec5SDimitry Andric     ParamType = Expansion->getPattern();
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   // FIXME: It's not clear how deduction of a parameter of reference
4340b57cec5SDimitry Andric   // type from an argument (of non-reference type) should be performed.
4350b57cec5SDimitry Andric   // For now, we just remove reference types from both sides and let
4360b57cec5SDimitry Andric   // the final check for matching types sort out the mess.
437e8d8bef9SDimitry Andric   ValueType = ValueType.getNonReferenceType();
438e8d8bef9SDimitry Andric   if (ParamType->isReferenceType())
439e8d8bef9SDimitry Andric     ParamType = ParamType.getNonReferenceType();
440e8d8bef9SDimitry Andric   else
441e8d8bef9SDimitry Andric     // Top-level cv-qualifiers are irrelevant for a non-reference type.
442e8d8bef9SDimitry Andric     ValueType = ValueType.getUnqualifiedType();
443e8d8bef9SDimitry Andric 
4440b57cec5SDimitry Andric   return DeduceTemplateArgumentsByTypeMatch(
445e8d8bef9SDimitry Andric       S, TemplateParams, ParamType, ValueType, Info, Deduced,
446e8d8bef9SDimitry Andric       TDF_SkipNonDependent, /*PartialOrdering=*/false,
4470b57cec5SDimitry Andric       /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
4480b57cec5SDimitry Andric }
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
4510b57cec5SDimitry Andric /// from the given integral constant.
DeduceNonTypeTemplateArgument(Sema & S,TemplateParameterList * TemplateParams,const NonTypeTemplateParmDecl * NTTP,const llvm::APSInt & Value,QualType ValueType,bool DeducedFromArrayBound,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced)452*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceNonTypeTemplateArgument(
4530b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
454e8d8bef9SDimitry Andric     const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
4550b57cec5SDimitry Andric     QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
4560b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
4570b57cec5SDimitry Andric   return DeduceNonTypeTemplateArgument(
4580b57cec5SDimitry Andric       S, TemplateParams, NTTP,
4590b57cec5SDimitry Andric       DeducedTemplateArgument(S.Context, Value, ValueType,
4600b57cec5SDimitry Andric                               DeducedFromArrayBound),
4610b57cec5SDimitry Andric       ValueType, Info, Deduced);
4620b57cec5SDimitry Andric }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
4650b57cec5SDimitry Andric /// from the given null pointer template argument type.
DeduceNullPtrTemplateArgument(Sema & S,TemplateParameterList * TemplateParams,const NonTypeTemplateParmDecl * NTTP,QualType NullPtrType,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced)466*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceNullPtrTemplateArgument(
4670b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
468e8d8bef9SDimitry Andric     const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
4690b57cec5SDimitry Andric     TemplateDeductionInfo &Info,
4700b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
471fe6060f1SDimitry Andric   Expr *Value = S.ImpCastExprToType(
472fe6060f1SDimitry Andric                      new (S.Context) CXXNullPtrLiteralExpr(S.Context.NullPtrTy,
473fe6060f1SDimitry Andric                                                            NTTP->getLocation()),
474fe6060f1SDimitry Andric                      NullPtrType,
475fe6060f1SDimitry Andric                      NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
476fe6060f1SDimitry Andric                                                         : CK_NullToPointer)
4770b57cec5SDimitry Andric                     .get();
4780b57cec5SDimitry Andric   return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
4790b57cec5SDimitry Andric                                        DeducedTemplateArgument(Value),
4800b57cec5SDimitry Andric                                        Value->getType(), Info, Deduced);
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
4840b57cec5SDimitry Andric /// from the given type- or value-dependent expression.
4850b57cec5SDimitry Andric ///
4860b57cec5SDimitry Andric /// \returns true if deduction succeeded, false otherwise.
DeduceNonTypeTemplateArgument(Sema & S,TemplateParameterList * TemplateParams,const NonTypeTemplateParmDecl * NTTP,Expr * Value,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced)487*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceNonTypeTemplateArgument(
4880b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
489*0fca6ea1SDimitry Andric     const NonTypeTemplateParmDecl *NTTP, Expr *Value,
490*0fca6ea1SDimitry Andric     TemplateDeductionInfo &Info,
4910b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
4920b57cec5SDimitry Andric   return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
4930b57cec5SDimitry Andric                                        DeducedTemplateArgument(Value),
4940b57cec5SDimitry Andric                                        Value->getType(), Info, Deduced);
4950b57cec5SDimitry Andric }
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
4980b57cec5SDimitry Andric /// from the given declaration.
4990b57cec5SDimitry Andric ///
5000b57cec5SDimitry Andric /// \returns true if deduction succeeded, false otherwise.
DeduceNonTypeTemplateArgument(Sema & S,TemplateParameterList * TemplateParams,const NonTypeTemplateParmDecl * NTTP,ValueDecl * D,QualType T,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced)501*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceNonTypeTemplateArgument(
5020b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
503e8d8bef9SDimitry Andric     const NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
5040b57cec5SDimitry Andric     TemplateDeductionInfo &Info,
5050b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
5060b57cec5SDimitry Andric   D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5070b57cec5SDimitry Andric   TemplateArgument New(D, T);
5080b57cec5SDimitry Andric   return DeduceNonTypeTemplateArgument(
5090b57cec5SDimitry Andric       S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
5100b57cec5SDimitry Andric }
5110b57cec5SDimitry Andric 
512*0fca6ea1SDimitry Andric /// Create a shallow copy of a given template parameter declaration, with
513*0fca6ea1SDimitry Andric /// empty source locations and using the given TemplateArgument as it's
514*0fca6ea1SDimitry Andric /// default argument.
515*0fca6ea1SDimitry Andric ///
516*0fca6ea1SDimitry Andric /// \returns The new template parameter declaration.
getTemplateParameterWithDefault(Sema & S,NamedDecl * A,TemplateArgument Default)517*0fca6ea1SDimitry Andric static NamedDecl *getTemplateParameterWithDefault(Sema &S, NamedDecl *A,
518*0fca6ea1SDimitry Andric                                                   TemplateArgument Default) {
519*0fca6ea1SDimitry Andric   switch (A->getKind()) {
520*0fca6ea1SDimitry Andric   case Decl::TemplateTypeParm: {
521*0fca6ea1SDimitry Andric     auto *T = cast<TemplateTypeParmDecl>(A);
522*0fca6ea1SDimitry Andric     auto *R = TemplateTypeParmDecl::Create(
523*0fca6ea1SDimitry Andric         S.Context, A->getDeclContext(), SourceLocation(), SourceLocation(),
524*0fca6ea1SDimitry Andric         T->getDepth(), T->getIndex(), T->getIdentifier(),
525*0fca6ea1SDimitry Andric         T->wasDeclaredWithTypename(), T->isParameterPack(),
526*0fca6ea1SDimitry Andric         T->hasTypeConstraint());
527*0fca6ea1SDimitry Andric     R->setDefaultArgument(
528*0fca6ea1SDimitry Andric         S.Context,
529*0fca6ea1SDimitry Andric         S.getTrivialTemplateArgumentLoc(Default, QualType(), SourceLocation()));
530*0fca6ea1SDimitry Andric     if (R->hasTypeConstraint()) {
531*0fca6ea1SDimitry Andric       auto *C = R->getTypeConstraint();
532*0fca6ea1SDimitry Andric       R->setTypeConstraint(C->getConceptReference(),
533*0fca6ea1SDimitry Andric                            C->getImmediatelyDeclaredConstraint());
534*0fca6ea1SDimitry Andric     }
535*0fca6ea1SDimitry Andric     return R;
536*0fca6ea1SDimitry Andric   }
537*0fca6ea1SDimitry Andric   case Decl::NonTypeTemplateParm: {
538*0fca6ea1SDimitry Andric     auto *T = cast<NonTypeTemplateParmDecl>(A);
539*0fca6ea1SDimitry Andric     auto *R = NonTypeTemplateParmDecl::Create(
540*0fca6ea1SDimitry Andric         S.Context, A->getDeclContext(), SourceLocation(), SourceLocation(),
541*0fca6ea1SDimitry Andric         T->getDepth(), T->getIndex(), T->getIdentifier(), T->getType(),
542*0fca6ea1SDimitry Andric         T->isParameterPack(), T->getTypeSourceInfo());
543*0fca6ea1SDimitry Andric     R->setDefaultArgument(S.Context,
544*0fca6ea1SDimitry Andric                           S.getTrivialTemplateArgumentLoc(
545*0fca6ea1SDimitry Andric                               Default, Default.getNonTypeTemplateArgumentType(),
546*0fca6ea1SDimitry Andric                               SourceLocation()));
547*0fca6ea1SDimitry Andric     if (auto *PTC = T->getPlaceholderTypeConstraint())
548*0fca6ea1SDimitry Andric       R->setPlaceholderTypeConstraint(PTC);
549*0fca6ea1SDimitry Andric     return R;
550*0fca6ea1SDimitry Andric   }
551*0fca6ea1SDimitry Andric   case Decl::TemplateTemplateParm: {
552*0fca6ea1SDimitry Andric     auto *T = cast<TemplateTemplateParmDecl>(A);
553*0fca6ea1SDimitry Andric     auto *R = TemplateTemplateParmDecl::Create(
554*0fca6ea1SDimitry Andric         S.Context, A->getDeclContext(), SourceLocation(), T->getDepth(),
555*0fca6ea1SDimitry Andric         T->getIndex(), T->isParameterPack(), T->getIdentifier(),
556*0fca6ea1SDimitry Andric         T->wasDeclaredWithTypename(), T->getTemplateParameters());
557*0fca6ea1SDimitry Andric     R->setDefaultArgument(
558*0fca6ea1SDimitry Andric         S.Context,
559*0fca6ea1SDimitry Andric         S.getTrivialTemplateArgumentLoc(Default, QualType(), SourceLocation()));
560*0fca6ea1SDimitry Andric     return R;
561*0fca6ea1SDimitry Andric   }
562*0fca6ea1SDimitry Andric   default:
563*0fca6ea1SDimitry Andric     llvm_unreachable("Unexpected Decl Kind");
564*0fca6ea1SDimitry Andric   }
565*0fca6ea1SDimitry Andric }
566*0fca6ea1SDimitry Andric 
567*0fca6ea1SDimitry Andric static TemplateDeductionResult
DeduceTemplateArguments(Sema & S,TemplateParameterList * TemplateParams,TemplateName Param,TemplateName Arg,TemplateDeductionInfo & Info,ArrayRef<TemplateArgument> DefaultArguments,SmallVectorImpl<DeducedTemplateArgument> & Deduced)568*0fca6ea1SDimitry Andric DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
569*0fca6ea1SDimitry Andric                         TemplateName Param, TemplateName Arg,
5700b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
571*0fca6ea1SDimitry Andric                         ArrayRef<TemplateArgument> DefaultArguments,
5720b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
5730b57cec5SDimitry Andric   TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
5740b57cec5SDimitry Andric   if (!ParamDecl) {
5750b57cec5SDimitry Andric     // The parameter type is dependent and is not a template template parameter,
5760b57cec5SDimitry Andric     // so there is nothing that we can deduce.
577*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
5780b57cec5SDimitry Andric   }
5790b57cec5SDimitry Andric 
580*0fca6ea1SDimitry Andric   if (auto *TempParam = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
5810b57cec5SDimitry Andric     // If we're not deducing at this depth, there's nothing to deduce.
5820b57cec5SDimitry Andric     if (TempParam->getDepth() != Info.getDeducedDepth())
583*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
5840b57cec5SDimitry Andric 
585*0fca6ea1SDimitry Andric     auto NewDeduced = DeducedTemplateArgument(Arg);
586*0fca6ea1SDimitry Andric     // Provisional resolution for CWG2398: If Arg is also a template template
587*0fca6ea1SDimitry Andric     // param, and it names a template specialization, then we deduce a
588*0fca6ea1SDimitry Andric     // synthesized template template parameter based on A, but using the TS's
589*0fca6ea1SDimitry Andric     // arguments as defaults.
590*0fca6ea1SDimitry Andric     if (auto *TempArg = dyn_cast_or_null<TemplateTemplateParmDecl>(
591*0fca6ea1SDimitry Andric             Arg.getAsTemplateDecl())) {
592*0fca6ea1SDimitry Andric       assert(!TempArg->isExpandedParameterPack());
593*0fca6ea1SDimitry Andric 
594*0fca6ea1SDimitry Andric       TemplateParameterList *As = TempArg->getTemplateParameters();
595*0fca6ea1SDimitry Andric       if (DefaultArguments.size() != 0) {
596*0fca6ea1SDimitry Andric         assert(DefaultArguments.size() <= As->size());
597*0fca6ea1SDimitry Andric         SmallVector<NamedDecl *, 4> Params(As->size());
598*0fca6ea1SDimitry Andric         for (unsigned I = 0; I < DefaultArguments.size(); ++I)
599*0fca6ea1SDimitry Andric           Params[I] = getTemplateParameterWithDefault(S, As->getParam(I),
600*0fca6ea1SDimitry Andric                                                       DefaultArguments[I]);
601*0fca6ea1SDimitry Andric         for (unsigned I = DefaultArguments.size(); I < As->size(); ++I)
602*0fca6ea1SDimitry Andric           Params[I] = As->getParam(I);
603*0fca6ea1SDimitry Andric         // FIXME: We could unique these, and also the parameters, but we don't
604*0fca6ea1SDimitry Andric         // expect programs to contain a large enough amount of these deductions
605*0fca6ea1SDimitry Andric         // for that to be worthwhile.
606*0fca6ea1SDimitry Andric         auto *TPL = TemplateParameterList::Create(
607*0fca6ea1SDimitry Andric             S.Context, SourceLocation(), SourceLocation(), Params,
608*0fca6ea1SDimitry Andric             SourceLocation(), As->getRequiresClause());
609*0fca6ea1SDimitry Andric         NewDeduced = DeducedTemplateArgument(
610*0fca6ea1SDimitry Andric             TemplateName(TemplateTemplateParmDecl::Create(
611*0fca6ea1SDimitry Andric                 S.Context, TempArg->getDeclContext(), SourceLocation(),
612*0fca6ea1SDimitry Andric                 TempArg->getDepth(), TempArg->getPosition(),
613*0fca6ea1SDimitry Andric                 TempArg->isParameterPack(), TempArg->getIdentifier(),
614*0fca6ea1SDimitry Andric                 TempArg->wasDeclaredWithTypename(), TPL)));
615*0fca6ea1SDimitry Andric       }
616*0fca6ea1SDimitry Andric     }
617*0fca6ea1SDimitry Andric 
6180b57cec5SDimitry Andric     DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
6190b57cec5SDimitry Andric                                                  Deduced[TempParam->getIndex()],
6200b57cec5SDimitry Andric                                                                    NewDeduced);
6210b57cec5SDimitry Andric     if (Result.isNull()) {
6220b57cec5SDimitry Andric       Info.Param = TempParam;
6230b57cec5SDimitry Andric       Info.FirstArg = Deduced[TempParam->getIndex()];
6240b57cec5SDimitry Andric       Info.SecondArg = NewDeduced;
625*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Inconsistent;
6260b57cec5SDimitry Andric     }
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric     Deduced[TempParam->getIndex()] = Result;
629*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
6300b57cec5SDimitry Andric   }
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric   // Verify that the two template names are equivalent.
6330b57cec5SDimitry Andric   if (S.Context.hasSameTemplateName(Param, Arg))
634*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   // Mismatch of non-dependent template parameter to argument.
6370b57cec5SDimitry Andric   Info.FirstArg = TemplateArgument(Param);
6380b57cec5SDimitry Andric   Info.SecondArg = TemplateArgument(Arg);
639*0fca6ea1SDimitry Andric   return TemplateDeductionResult::NonDeducedMismatch;
6400b57cec5SDimitry Andric }
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric /// Deduce the template arguments by comparing the template parameter
6430b57cec5SDimitry Andric /// type (which is a template-id) with the template argument type.
6440b57cec5SDimitry Andric ///
6450b57cec5SDimitry Andric /// \param S the Sema
6460b57cec5SDimitry Andric ///
6470b57cec5SDimitry Andric /// \param TemplateParams the template parameters that we are deducing
6480b57cec5SDimitry Andric ///
64981ad6265SDimitry Andric /// \param P the parameter type
6500b57cec5SDimitry Andric ///
65181ad6265SDimitry Andric /// \param A the argument type
6520b57cec5SDimitry Andric ///
6530b57cec5SDimitry Andric /// \param Info information about the template argument deduction itself
6540b57cec5SDimitry Andric ///
6550b57cec5SDimitry Andric /// \param Deduced the deduced template arguments
6560b57cec5SDimitry Andric ///
6570b57cec5SDimitry Andric /// \returns the result of template argument deduction so far. Note that a
6580b57cec5SDimitry Andric /// "success" result means that template argument deduction has not yet failed,
6590b57cec5SDimitry Andric /// but it may still fail, later, for other reasons.
660*0fca6ea1SDimitry Andric 
getLastTemplateSpecType(QualType QT)661*0fca6ea1SDimitry Andric static const TemplateSpecializationType *getLastTemplateSpecType(QualType QT) {
662*0fca6ea1SDimitry Andric   for (const Type *T = QT.getTypePtr(); /**/; /**/) {
663*0fca6ea1SDimitry Andric     const TemplateSpecializationType *TST =
664*0fca6ea1SDimitry Andric         T->getAs<TemplateSpecializationType>();
665*0fca6ea1SDimitry Andric     assert(TST && "Expected a TemplateSpecializationType");
666*0fca6ea1SDimitry Andric     if (!TST->isSugared())
667*0fca6ea1SDimitry Andric       return TST;
668*0fca6ea1SDimitry Andric     T = TST->desugar().getTypePtr();
669*0fca6ea1SDimitry Andric   }
670*0fca6ea1SDimitry Andric }
671*0fca6ea1SDimitry Andric 
672*0fca6ea1SDimitry Andric static TemplateDeductionResult
DeduceTemplateSpecArguments(Sema & S,TemplateParameterList * TemplateParams,const QualType P,QualType A,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced)673349cc55cSDimitry Andric DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams,
674349cc55cSDimitry Andric                             const QualType P, QualType A,
6750b57cec5SDimitry Andric                             TemplateDeductionInfo &Info,
6760b57cec5SDimitry Andric                             SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
677349cc55cSDimitry Andric   QualType UP = P;
678349cc55cSDimitry Andric   if (const auto *IP = P->getAs<InjectedClassNameType>())
679349cc55cSDimitry Andric     UP = IP->getInjectedSpecializationType();
680*0fca6ea1SDimitry Andric 
681*0fca6ea1SDimitry Andric   assert(isa<TemplateSpecializationType>(UP.getCanonicalType()));
682*0fca6ea1SDimitry Andric   const TemplateSpecializationType *TP = ::getLastTemplateSpecType(UP);
683bdd1243dSDimitry Andric   TemplateName TNP = TP->getTemplateName();
684bdd1243dSDimitry Andric 
685bdd1243dSDimitry Andric   // If the parameter is an alias template, there is nothing to deduce.
686bdd1243dSDimitry Andric   if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
687*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
688bdd1243dSDimitry Andric 
689*0fca6ea1SDimitry Andric   // FIXME: To preserve sugar, the TST needs to carry sugared resolved
690*0fca6ea1SDimitry Andric   // arguments.
691*0fca6ea1SDimitry Andric   ArrayRef<TemplateArgument> PResolved =
692*0fca6ea1SDimitry Andric       TP->getCanonicalTypeInternal()
693*0fca6ea1SDimitry Andric           ->castAs<TemplateSpecializationType>()
694*0fca6ea1SDimitry Andric           ->template_arguments();
6950b57cec5SDimitry Andric 
696349cc55cSDimitry Andric   QualType UA = A;
697*0fca6ea1SDimitry Andric   std::optional<NestedNameSpecifier *> NNS;
6980b57cec5SDimitry Andric   // Treat an injected-class-name as its underlying template-id.
699*0fca6ea1SDimitry Andric   if (const auto *Elaborated = A->getAs<ElaboratedType>()) {
700*0fca6ea1SDimitry Andric     NNS = Elaborated->getQualifier();
701*0fca6ea1SDimitry Andric   } else if (const auto *Injected = A->getAs<InjectedClassNameType>()) {
702349cc55cSDimitry Andric     UA = Injected->getInjectedSpecializationType();
703*0fca6ea1SDimitry Andric     NNS = nullptr;
704*0fca6ea1SDimitry Andric   }
7050b57cec5SDimitry Andric 
7060b57cec5SDimitry Andric   // Check whether the template argument is a dependent template-id.
707*0fca6ea1SDimitry Andric   if (isa<TemplateSpecializationType>(UA.getCanonicalType())) {
708*0fca6ea1SDimitry Andric     const TemplateSpecializationType *SA = ::getLastTemplateSpecType(UA);
709bdd1243dSDimitry Andric     TemplateName TNA = SA->getTemplateName();
710bdd1243dSDimitry Andric 
711bdd1243dSDimitry Andric     // If the argument is an alias template, there is nothing to deduce.
712bdd1243dSDimitry Andric     if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
713*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
714*0fca6ea1SDimitry Andric 
715*0fca6ea1SDimitry Andric     // FIXME: To preserve sugar, the TST needs to carry sugared resolved
716*0fca6ea1SDimitry Andric     // arguments.
717*0fca6ea1SDimitry Andric     ArrayRef<TemplateArgument> AResolved =
718*0fca6ea1SDimitry Andric         SA->getCanonicalTypeInternal()
719*0fca6ea1SDimitry Andric             ->castAs<TemplateSpecializationType>()
720*0fca6ea1SDimitry Andric             ->template_arguments();
721bdd1243dSDimitry Andric 
7220b57cec5SDimitry Andric     // Perform template argument deduction for the template name.
723*0fca6ea1SDimitry Andric     if (auto Result = DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
724*0fca6ea1SDimitry Andric                                               AResolved, Deduced);
725*0fca6ea1SDimitry Andric         Result != TemplateDeductionResult::Success)
7260b57cec5SDimitry Andric       return Result;
727*0fca6ea1SDimitry Andric 
7280b57cec5SDimitry Andric     // Perform template argument deduction on each template
7290b57cec5SDimitry Andric     // argument. Ignore any missing/extra arguments, since they could be
7300b57cec5SDimitry Andric     // filled in by default arguments.
731*0fca6ea1SDimitry Andric     return DeduceTemplateArguments(S, TemplateParams, PResolved, AResolved,
732*0fca6ea1SDimitry Andric                                    Info, Deduced,
7330b57cec5SDimitry Andric                                    /*NumberOfArgumentsMustMatch=*/false);
7340b57cec5SDimitry Andric   }
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   // If the argument type is a class template specialization, we
7370b57cec5SDimitry Andric   // perform template argument deduction using its template
7380b57cec5SDimitry Andric   // arguments.
739349cc55cSDimitry Andric   const auto *RA = UA->getAs<RecordType>();
740349cc55cSDimitry Andric   const auto *SA =
741349cc55cSDimitry Andric       RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
742349cc55cSDimitry Andric   if (!SA) {
743349cc55cSDimitry Andric     Info.FirstArg = TemplateArgument(P);
744349cc55cSDimitry Andric     Info.SecondArg = TemplateArgument(A);
745*0fca6ea1SDimitry Andric     return TemplateDeductionResult::NonDeducedMismatch;
7460b57cec5SDimitry Andric   }
7470b57cec5SDimitry Andric 
748*0fca6ea1SDimitry Andric   TemplateName TNA = TemplateName(SA->getSpecializedTemplate());
749*0fca6ea1SDimitry Andric   if (NNS)
750*0fca6ea1SDimitry Andric     TNA = S.Context.getQualifiedTemplateName(
751*0fca6ea1SDimitry Andric         *NNS, false, TemplateName(SA->getSpecializedTemplate()));
752*0fca6ea1SDimitry Andric 
7530b57cec5SDimitry Andric   // Perform template argument deduction for the template name.
754*0fca6ea1SDimitry Andric   if (auto Result =
755*0fca6ea1SDimitry Andric           DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info,
756*0fca6ea1SDimitry Andric                                   SA->getTemplateArgs().asArray(), Deduced);
757*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
7580b57cec5SDimitry Andric     return Result;
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   // Perform template argument deduction for the template arguments.
761349cc55cSDimitry Andric   return DeduceTemplateArguments(S, TemplateParams, PResolved,
762349cc55cSDimitry Andric                                  SA->getTemplateArgs().asArray(), Info, Deduced,
763349cc55cSDimitry Andric                                  /*NumberOfArgumentsMustMatch=*/true);
7640b57cec5SDimitry Andric }
7650b57cec5SDimitry Andric 
IsPossiblyOpaquelyQualifiedTypeInternal(const Type * T)766349cc55cSDimitry Andric static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T) {
767349cc55cSDimitry Andric   assert(T->isCanonicalUnqualified());
768349cc55cSDimitry Andric 
7690b57cec5SDimitry Andric   switch (T->getTypeClass()) {
7700b57cec5SDimitry Andric   case Type::TypeOfExpr:
7710b57cec5SDimitry Andric   case Type::TypeOf:
7720b57cec5SDimitry Andric   case Type::DependentName:
7730b57cec5SDimitry Andric   case Type::Decltype:
774*0fca6ea1SDimitry Andric   case Type::PackIndexing:
7750b57cec5SDimitry Andric   case Type::UnresolvedUsing:
7760b57cec5SDimitry Andric   case Type::TemplateTypeParm:
777*0fca6ea1SDimitry Andric   case Type::Auto:
7780b57cec5SDimitry Andric     return true;
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric   case Type::ConstantArray:
7810b57cec5SDimitry Andric   case Type::IncompleteArray:
7820b57cec5SDimitry Andric   case Type::VariableArray:
7830b57cec5SDimitry Andric   case Type::DependentSizedArray:
784349cc55cSDimitry Andric     return IsPossiblyOpaquelyQualifiedTypeInternal(
785349cc55cSDimitry Andric         cast<ArrayType>(T)->getElementType().getTypePtr());
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric   default:
7880b57cec5SDimitry Andric     return false;
7890b57cec5SDimitry Andric   }
7900b57cec5SDimitry Andric }
7910b57cec5SDimitry Andric 
792349cc55cSDimitry Andric /// Determines whether the given type is an opaque type that
793349cc55cSDimitry Andric /// might be more qualified when instantiated.
IsPossiblyOpaquelyQualifiedType(QualType T)794349cc55cSDimitry Andric static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
795349cc55cSDimitry Andric   return IsPossiblyOpaquelyQualifiedTypeInternal(
796349cc55cSDimitry Andric       T->getCanonicalTypeInternal().getTypePtr());
797349cc55cSDimitry Andric }
798349cc55cSDimitry Andric 
7990b57cec5SDimitry Andric /// Helper function to build a TemplateParameter when we don't
8000b57cec5SDimitry Andric /// know its type statically.
makeTemplateParameter(Decl * D)8010b57cec5SDimitry Andric static TemplateParameter makeTemplateParameter(Decl *D) {
8020b57cec5SDimitry Andric   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
8030b57cec5SDimitry Andric     return TemplateParameter(TTP);
8040b57cec5SDimitry Andric   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
8050b57cec5SDimitry Andric     return TemplateParameter(NTTP);
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
8080b57cec5SDimitry Andric }
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric /// A pack that we're currently deducing.
8110b57cec5SDimitry Andric struct clang::DeducedPack {
8120b57cec5SDimitry Andric   // The index of the pack.
8130b57cec5SDimitry Andric   unsigned Index;
8140b57cec5SDimitry Andric 
8150b57cec5SDimitry Andric   // The old value of the pack before we started deducing it.
8160b57cec5SDimitry Andric   DeducedTemplateArgument Saved;
8170b57cec5SDimitry Andric 
8180b57cec5SDimitry Andric   // A deferred value of this pack from an inner deduction, that couldn't be
8190b57cec5SDimitry Andric   // deduced because this deduction hadn't happened yet.
8200b57cec5SDimitry Andric   DeducedTemplateArgument DeferredDeduction;
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric   // The new value of the pack.
8230b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> New;
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   // The outer deduction for this pack, if any.
8260b57cec5SDimitry Andric   DeducedPack *Outer = nullptr;
8270b57cec5SDimitry Andric 
DeducedPackclang::DeducedPack8280b57cec5SDimitry Andric   DeducedPack(unsigned Index) : Index(Index) {}
8290b57cec5SDimitry Andric };
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric namespace {
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric /// A scope in which we're performing pack deduction.
8340b57cec5SDimitry Andric class PackDeductionScope {
8350b57cec5SDimitry Andric public:
8360b57cec5SDimitry Andric   /// Prepare to deduce the packs named within Pattern.
PackDeductionScope(Sema & S,TemplateParameterList * TemplateParams,SmallVectorImpl<DeducedTemplateArgument> & Deduced,TemplateDeductionInfo & Info,TemplateArgument Pattern,bool DeducePackIfNotAlreadyDeduced=false)8370b57cec5SDimitry Andric   PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
8380b57cec5SDimitry Andric                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
83906c3fb27SDimitry Andric                      TemplateDeductionInfo &Info, TemplateArgument Pattern,
84006c3fb27SDimitry Andric                      bool DeducePackIfNotAlreadyDeduced = false)
84106c3fb27SDimitry Andric       : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info),
84206c3fb27SDimitry Andric         DeducePackIfNotAlreadyDeduced(DeducePackIfNotAlreadyDeduced){
8430b57cec5SDimitry Andric     unsigned NumNamedPacks = addPacks(Pattern);
8440b57cec5SDimitry Andric     finishConstruction(NumNamedPacks);
8450b57cec5SDimitry Andric   }
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   /// Prepare to directly deduce arguments of the parameter with index \p Index.
PackDeductionScope(Sema & S,TemplateParameterList * TemplateParams,SmallVectorImpl<DeducedTemplateArgument> & Deduced,TemplateDeductionInfo & Info,unsigned Index)8480b57cec5SDimitry Andric   PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
8490b57cec5SDimitry Andric                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8500b57cec5SDimitry Andric                      TemplateDeductionInfo &Info, unsigned Index)
8510b57cec5SDimitry Andric       : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
8520b57cec5SDimitry Andric     addPack(Index);
8530b57cec5SDimitry Andric     finishConstruction(1);
8540b57cec5SDimitry Andric   }
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric private:
addPack(unsigned Index)8570b57cec5SDimitry Andric   void addPack(unsigned Index) {
8580b57cec5SDimitry Andric     // Save the deduced template argument for the parameter pack expanded
8590b57cec5SDimitry Andric     // by this pack expansion, then clear out the deduction.
860*0fca6ea1SDimitry Andric     DeducedFromEarlierParameter = !Deduced[Index].isNull();
8610b57cec5SDimitry Andric     DeducedPack Pack(Index);
8620b57cec5SDimitry Andric     Pack.Saved = Deduced[Index];
8630b57cec5SDimitry Andric     Deduced[Index] = TemplateArgument();
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric     // FIXME: What if we encounter multiple packs with different numbers of
8660b57cec5SDimitry Andric     // pre-expanded expansions? (This should already have been diagnosed
8670b57cec5SDimitry Andric     // during substitution.)
868bdd1243dSDimitry Andric     if (std::optional<unsigned> ExpandedPackExpansions =
8690b57cec5SDimitry Andric             getExpandedPackSize(TemplateParams->getParam(Index)))
8700b57cec5SDimitry Andric       FixedNumExpansions = ExpandedPackExpansions;
8710b57cec5SDimitry Andric 
8720b57cec5SDimitry Andric     Packs.push_back(Pack);
8730b57cec5SDimitry Andric   }
8740b57cec5SDimitry Andric 
addPacks(TemplateArgument Pattern)8750b57cec5SDimitry Andric   unsigned addPacks(TemplateArgument Pattern) {
8760b57cec5SDimitry Andric     // Compute the set of template parameter indices that correspond to
8770b57cec5SDimitry Andric     // parameter packs expanded by the pack expansion.
8780b57cec5SDimitry Andric     llvm::SmallBitVector SawIndices(TemplateParams->size());
87955e4f9d5SDimitry Andric     llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric     auto AddPack = [&](unsigned Index) {
8820b57cec5SDimitry Andric       if (SawIndices[Index])
8830b57cec5SDimitry Andric         return;
8840b57cec5SDimitry Andric       SawIndices[Index] = true;
8850b57cec5SDimitry Andric       addPack(Index);
88655e4f9d5SDimitry Andric 
88755e4f9d5SDimitry Andric       // Deducing a parameter pack that is a pack expansion also constrains the
88855e4f9d5SDimitry Andric       // packs appearing in that parameter to have the same deduced arity. Also,
88955e4f9d5SDimitry Andric       // in C++17 onwards, deducing a non-type template parameter deduces its
89055e4f9d5SDimitry Andric       // type, so we need to collect the pending deduced values for those packs.
89155e4f9d5SDimitry Andric       if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
89255e4f9d5SDimitry Andric               TemplateParams->getParam(Index))) {
8935ffd83dbSDimitry Andric         if (!NTTP->isExpandedParameterPack())
89455e4f9d5SDimitry Andric           if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
89555e4f9d5SDimitry Andric             ExtraDeductions.push_back(Expansion->getPattern());
89655e4f9d5SDimitry Andric       }
89755e4f9d5SDimitry Andric       // FIXME: Also collect the unexpanded packs in any type and template
89855e4f9d5SDimitry Andric       // parameter packs that are pack expansions.
8990b57cec5SDimitry Andric     };
9000b57cec5SDimitry Andric 
90155e4f9d5SDimitry Andric     auto Collect = [&](TemplateArgument Pattern) {
9020b57cec5SDimitry Andric       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
9030b57cec5SDimitry Andric       S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
9040b57cec5SDimitry Andric       for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
9051ac55f4cSDimitry Andric         unsigned Depth, Index;
9061ac55f4cSDimitry Andric         std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
9070b57cec5SDimitry Andric         if (Depth == Info.getDeducedDepth())
9080b57cec5SDimitry Andric           AddPack(Index);
9090b57cec5SDimitry Andric       }
91055e4f9d5SDimitry Andric     };
91155e4f9d5SDimitry Andric 
91255e4f9d5SDimitry Andric     // Look for unexpanded packs in the pattern.
91355e4f9d5SDimitry Andric     Collect(Pattern);
9140b57cec5SDimitry Andric     assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric     unsigned NumNamedPacks = Packs.size();
9170b57cec5SDimitry Andric 
91855e4f9d5SDimitry Andric     // Also look for unexpanded packs that are indirectly deduced by deducing
91955e4f9d5SDimitry Andric     // the sizes of the packs in this pattern.
92055e4f9d5SDimitry Andric     while (!ExtraDeductions.empty())
92155e4f9d5SDimitry Andric       Collect(ExtraDeductions.pop_back_val());
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric     return NumNamedPacks;
9240b57cec5SDimitry Andric   }
9250b57cec5SDimitry Andric 
finishConstruction(unsigned NumNamedPacks)9260b57cec5SDimitry Andric   void finishConstruction(unsigned NumNamedPacks) {
9270b57cec5SDimitry Andric     // Dig out the partially-substituted pack, if there is one.
9280b57cec5SDimitry Andric     const TemplateArgument *PartialPackArgs = nullptr;
9290b57cec5SDimitry Andric     unsigned NumPartialPackArgs = 0;
9300b57cec5SDimitry Andric     std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
9310b57cec5SDimitry Andric     if (auto *Scope = S.CurrentInstantiationScope)
9320b57cec5SDimitry Andric       if (auto *Partial = Scope->getPartiallySubstitutedPack(
9330b57cec5SDimitry Andric               &PartialPackArgs, &NumPartialPackArgs))
9340b57cec5SDimitry Andric         PartialPackDepthIndex = getDepthAndIndex(Partial);
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric     // This pack expansion will have been partially or fully expanded if
9370b57cec5SDimitry Andric     // it only names explicitly-specified parameter packs (including the
9380b57cec5SDimitry Andric     // partially-substituted one, if any).
9390b57cec5SDimitry Andric     bool IsExpanded = true;
9400b57cec5SDimitry Andric     for (unsigned I = 0; I != NumNamedPacks; ++I) {
9410b57cec5SDimitry Andric       if (Packs[I].Index >= Info.getNumExplicitArgs()) {
9420b57cec5SDimitry Andric         IsExpanded = false;
9430b57cec5SDimitry Andric         IsPartiallyExpanded = false;
9440b57cec5SDimitry Andric         break;
9450b57cec5SDimitry Andric       }
9460b57cec5SDimitry Andric       if (PartialPackDepthIndex ==
9470b57cec5SDimitry Andric             std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
9480b57cec5SDimitry Andric         IsPartiallyExpanded = true;
9490b57cec5SDimitry Andric       }
9500b57cec5SDimitry Andric     }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric     // Skip over the pack elements that were expanded into separate arguments.
9530b57cec5SDimitry Andric     // If we partially expanded, this is the number of partial arguments.
9540b57cec5SDimitry Andric     if (IsPartiallyExpanded)
9550b57cec5SDimitry Andric       PackElements += NumPartialPackArgs;
9560b57cec5SDimitry Andric     else if (IsExpanded)
9570b57cec5SDimitry Andric       PackElements += *FixedNumExpansions;
9580b57cec5SDimitry Andric 
9590b57cec5SDimitry Andric     for (auto &Pack : Packs) {
9600b57cec5SDimitry Andric       if (Info.PendingDeducedPacks.size() > Pack.Index)
9610b57cec5SDimitry Andric         Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
9620b57cec5SDimitry Andric       else
9630b57cec5SDimitry Andric         Info.PendingDeducedPacks.resize(Pack.Index + 1);
9640b57cec5SDimitry Andric       Info.PendingDeducedPacks[Pack.Index] = &Pack;
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric       if (PartialPackDepthIndex ==
9670b57cec5SDimitry Andric             std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
9680b57cec5SDimitry Andric         Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
9690b57cec5SDimitry Andric         // We pre-populate the deduced value of the partially-substituted
9700b57cec5SDimitry Andric         // pack with the specified value. This is not entirely correct: the
9710b57cec5SDimitry Andric         // value is supposed to have been substituted, not deduced, but the
9720b57cec5SDimitry Andric         // cases where this is observable require an exact type match anyway.
9730b57cec5SDimitry Andric         //
9740b57cec5SDimitry Andric         // FIXME: If we could represent a "depth i, index j, pack elem k"
9750b57cec5SDimitry Andric         // parameter, we could substitute the partially-substituted pack
9760b57cec5SDimitry Andric         // everywhere and avoid this.
9770b57cec5SDimitry Andric         if (!IsPartiallyExpanded)
9780b57cec5SDimitry Andric           Deduced[Pack.Index] = Pack.New[PackElements];
9790b57cec5SDimitry Andric       }
9800b57cec5SDimitry Andric     }
9810b57cec5SDimitry Andric   }
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric public:
~PackDeductionScope()9840b57cec5SDimitry Andric   ~PackDeductionScope() {
9850b57cec5SDimitry Andric     for (auto &Pack : Packs)
9860b57cec5SDimitry Andric       Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
9870b57cec5SDimitry Andric   }
9880b57cec5SDimitry Andric 
989*0fca6ea1SDimitry Andric   // Return the size of the saved packs if all of them has the same size.
getSavedPackSizeIfAllEqual() const990*0fca6ea1SDimitry Andric   std::optional<unsigned> getSavedPackSizeIfAllEqual() const {
991*0fca6ea1SDimitry Andric     unsigned PackSize = Packs[0].Saved.pack_size();
992*0fca6ea1SDimitry Andric 
993*0fca6ea1SDimitry Andric     if (std::all_of(Packs.begin() + 1, Packs.end(), [&PackSize](const auto &P) {
994*0fca6ea1SDimitry Andric           return P.Saved.pack_size() == PackSize;
995*0fca6ea1SDimitry Andric         }))
996*0fca6ea1SDimitry Andric       return PackSize;
997*0fca6ea1SDimitry Andric     return {};
998*0fca6ea1SDimitry Andric   }
999*0fca6ea1SDimitry Andric 
1000*0fca6ea1SDimitry Andric   /// Determine whether this pack has already been deduced from a previous
1001*0fca6ea1SDimitry Andric   /// argument.
isDeducedFromEarlierParameter() const1002*0fca6ea1SDimitry Andric   bool isDeducedFromEarlierParameter() const {
1003*0fca6ea1SDimitry Andric     return DeducedFromEarlierParameter;
1004*0fca6ea1SDimitry Andric   }
1005*0fca6ea1SDimitry Andric 
10060b57cec5SDimitry Andric   /// Determine whether this pack has already been partially expanded into a
10070b57cec5SDimitry Andric   /// sequence of (prior) function parameters / template arguments.
isPartiallyExpanded()10080b57cec5SDimitry Andric   bool isPartiallyExpanded() { return IsPartiallyExpanded; }
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   /// Determine whether this pack expansion scope has a known, fixed arity.
10110b57cec5SDimitry Andric   /// This happens if it involves a pack from an outer template that has
10120b57cec5SDimitry Andric   /// (notionally) already been expanded.
hasFixedArity()101381ad6265SDimitry Andric   bool hasFixedArity() { return FixedNumExpansions.has_value(); }
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric   /// Determine whether the next element of the argument is still part of this
10160b57cec5SDimitry Andric   /// pack. This is the case unless the pack is already expanded to a fixed
10170b57cec5SDimitry Andric   /// length.
hasNextElement()10180b57cec5SDimitry Andric   bool hasNextElement() {
10190b57cec5SDimitry Andric     return !FixedNumExpansions || *FixedNumExpansions > PackElements;
10200b57cec5SDimitry Andric   }
10210b57cec5SDimitry Andric 
10220b57cec5SDimitry Andric   /// Move to deducing the next element in each pack that is being deduced.
nextPackElement()10230b57cec5SDimitry Andric   void nextPackElement() {
10240b57cec5SDimitry Andric     // Capture the deduced template arguments for each parameter pack expanded
10250b57cec5SDimitry Andric     // by this pack expansion, add them to the list of arguments we've deduced
10260b57cec5SDimitry Andric     // for that pack, then clear out the deduced argument.
10270b57cec5SDimitry Andric     for (auto &Pack : Packs) {
10280b57cec5SDimitry Andric       DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
10290b57cec5SDimitry Andric       if (!Pack.New.empty() || !DeducedArg.isNull()) {
10300b57cec5SDimitry Andric         while (Pack.New.size() < PackElements)
10310b57cec5SDimitry Andric           Pack.New.push_back(DeducedTemplateArgument());
10320b57cec5SDimitry Andric         if (Pack.New.size() == PackElements)
10330b57cec5SDimitry Andric           Pack.New.push_back(DeducedArg);
10340b57cec5SDimitry Andric         else
10350b57cec5SDimitry Andric           Pack.New[PackElements] = DeducedArg;
10360b57cec5SDimitry Andric         DeducedArg = Pack.New.size() > PackElements + 1
10370b57cec5SDimitry Andric                          ? Pack.New[PackElements + 1]
10380b57cec5SDimitry Andric                          : DeducedTemplateArgument();
10390b57cec5SDimitry Andric       }
10400b57cec5SDimitry Andric     }
10410b57cec5SDimitry Andric     ++PackElements;
10420b57cec5SDimitry Andric   }
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric   /// Finish template argument deduction for a set of argument packs,
10450b57cec5SDimitry Andric   /// producing the argument packs and checking for consistency with prior
10460b57cec5SDimitry Andric   /// deductions.
finish()1047*0fca6ea1SDimitry Andric   TemplateDeductionResult finish() {
10480b57cec5SDimitry Andric     // Build argument packs for each of the parameter packs expanded by this
10490b57cec5SDimitry Andric     // pack expansion.
10500b57cec5SDimitry Andric     for (auto &Pack : Packs) {
10510b57cec5SDimitry Andric       // Put back the old value for this pack.
10520b57cec5SDimitry Andric       Deduced[Pack.Index] = Pack.Saved;
10530b57cec5SDimitry Andric 
1054480093f4SDimitry Andric       // Always make sure the size of this pack is correct, even if we didn't
1055480093f4SDimitry Andric       // deduce any values for it.
1056480093f4SDimitry Andric       //
1057480093f4SDimitry Andric       // FIXME: This isn't required by the normative wording, but substitution
1058480093f4SDimitry Andric       // and post-substitution checking will always fail if the arity of any
1059480093f4SDimitry Andric       // pack is not equal to the number of elements we processed. (Either that
1060480093f4SDimitry Andric       // or something else has gone *very* wrong.) We're permitted to skip any
1061480093f4SDimitry Andric       // hard errors from those follow-on steps by the intent (but not the
1062480093f4SDimitry Andric       // wording) of C++ [temp.inst]p8:
1063480093f4SDimitry Andric       //
1064480093f4SDimitry Andric       //   If the function selected by overload resolution can be determined
1065480093f4SDimitry Andric       //   without instantiating a class template definition, it is unspecified
1066480093f4SDimitry Andric       //   whether that instantiation actually takes place
10670b57cec5SDimitry Andric       Pack.New.resize(PackElements);
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric       // Build or find a new value for this pack.
10700b57cec5SDimitry Andric       DeducedTemplateArgument NewPack;
1071480093f4SDimitry Andric       if (Pack.New.empty()) {
10720b57cec5SDimitry Andric         // If we deduced an empty argument pack, create it now.
10730b57cec5SDimitry Andric         NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
10740b57cec5SDimitry Andric       } else {
10750b57cec5SDimitry Andric         TemplateArgument *ArgumentPack =
10760b57cec5SDimitry Andric             new (S.Context) TemplateArgument[Pack.New.size()];
10770b57cec5SDimitry Andric         std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
10780b57cec5SDimitry Andric         NewPack = DeducedTemplateArgument(
1079bdd1243dSDimitry Andric             TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
10800b57cec5SDimitry Andric             // FIXME: This is wrong, it's possible that some pack elements are
10810b57cec5SDimitry Andric             // deduced from an array bound and others are not:
10820b57cec5SDimitry Andric             //   template<typename ...T, T ...V> void g(const T (&...p)[V]);
10830b57cec5SDimitry Andric             //   g({1, 2, 3}, {{}, {}});
10840b57cec5SDimitry Andric             // ... should deduce T = {int, size_t (from array bound)}.
10850b57cec5SDimitry Andric             Pack.New[0].wasDeducedFromArrayBound());
10860b57cec5SDimitry Andric       }
10870b57cec5SDimitry Andric 
10880b57cec5SDimitry Andric       // Pick where we're going to put the merged pack.
10890b57cec5SDimitry Andric       DeducedTemplateArgument *Loc;
10900b57cec5SDimitry Andric       if (Pack.Outer) {
10910b57cec5SDimitry Andric         if (Pack.Outer->DeferredDeduction.isNull()) {
10920b57cec5SDimitry Andric           // Defer checking this pack until we have a complete pack to compare
10930b57cec5SDimitry Andric           // it against.
10940b57cec5SDimitry Andric           Pack.Outer->DeferredDeduction = NewPack;
10950b57cec5SDimitry Andric           continue;
10960b57cec5SDimitry Andric         }
10970b57cec5SDimitry Andric         Loc = &Pack.Outer->DeferredDeduction;
10980b57cec5SDimitry Andric       } else {
10990b57cec5SDimitry Andric         Loc = &Deduced[Pack.Index];
11000b57cec5SDimitry Andric       }
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric       // Check the new pack matches any previous value.
11030b57cec5SDimitry Andric       DeducedTemplateArgument OldPack = *Loc;
110406c3fb27SDimitry Andric       DeducedTemplateArgument Result = checkDeducedTemplateArguments(
110506c3fb27SDimitry Andric           S.Context, OldPack, NewPack, DeducePackIfNotAlreadyDeduced);
110606c3fb27SDimitry Andric 
110706c3fb27SDimitry Andric       Info.AggregateDeductionCandidateHasMismatchedArity =
110806c3fb27SDimitry Andric           OldPack.getKind() == TemplateArgument::Pack &&
110906c3fb27SDimitry Andric           NewPack.getKind() == TemplateArgument::Pack &&
111006c3fb27SDimitry Andric           OldPack.pack_size() != NewPack.pack_size() && !Result.isNull();
11110b57cec5SDimitry Andric 
11120b57cec5SDimitry Andric       // If we deferred a deduction of this pack, check that one now too.
11130b57cec5SDimitry Andric       if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
11140b57cec5SDimitry Andric         OldPack = Result;
11150b57cec5SDimitry Andric         NewPack = Pack.DeferredDeduction;
11160b57cec5SDimitry Andric         Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
11170b57cec5SDimitry Andric       }
11180b57cec5SDimitry Andric 
11190b57cec5SDimitry Andric       NamedDecl *Param = TemplateParams->getParam(Pack.Index);
11200b57cec5SDimitry Andric       if (Result.isNull()) {
11210b57cec5SDimitry Andric         Info.Param = makeTemplateParameter(Param);
11220b57cec5SDimitry Andric         Info.FirstArg = OldPack;
11230b57cec5SDimitry Andric         Info.SecondArg = NewPack;
1124*0fca6ea1SDimitry Andric         return TemplateDeductionResult::Inconsistent;
11250b57cec5SDimitry Andric       }
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric       // If we have a pre-expanded pack and we didn't deduce enough elements
11280b57cec5SDimitry Andric       // for it, fail deduction.
1129bdd1243dSDimitry Andric       if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
11300b57cec5SDimitry Andric         if (*Expansions != PackElements) {
11310b57cec5SDimitry Andric           Info.Param = makeTemplateParameter(Param);
11320b57cec5SDimitry Andric           Info.FirstArg = Result;
1133*0fca6ea1SDimitry Andric           return TemplateDeductionResult::IncompletePack;
11340b57cec5SDimitry Andric         }
11350b57cec5SDimitry Andric       }
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric       *Loc = Result;
11380b57cec5SDimitry Andric     }
11390b57cec5SDimitry Andric 
1140*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
11410b57cec5SDimitry Andric   }
11420b57cec5SDimitry Andric 
11430b57cec5SDimitry Andric private:
11440b57cec5SDimitry Andric   Sema &S;
11450b57cec5SDimitry Andric   TemplateParameterList *TemplateParams;
11460b57cec5SDimitry Andric   SmallVectorImpl<DeducedTemplateArgument> &Deduced;
11470b57cec5SDimitry Andric   TemplateDeductionInfo &Info;
11480b57cec5SDimitry Andric   unsigned PackElements = 0;
11490b57cec5SDimitry Andric   bool IsPartiallyExpanded = false;
115006c3fb27SDimitry Andric   bool DeducePackIfNotAlreadyDeduced = false;
1151*0fca6ea1SDimitry Andric   bool DeducedFromEarlierParameter = false;
11520b57cec5SDimitry Andric   /// The number of expansions, if we have a fully-expanded pack in this scope.
1153bdd1243dSDimitry Andric   std::optional<unsigned> FixedNumExpansions;
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric   SmallVector<DeducedPack, 2> Packs;
11560b57cec5SDimitry Andric };
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric } // namespace
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric /// Deduce the template arguments by comparing the list of parameter
11610b57cec5SDimitry Andric /// types to the list of argument types, as in the parameter-type-lists of
11620b57cec5SDimitry Andric /// function types (C++ [temp.deduct.type]p10).
11630b57cec5SDimitry Andric ///
11640b57cec5SDimitry Andric /// \param S The semantic analysis object within which we are deducing
11650b57cec5SDimitry Andric ///
11660b57cec5SDimitry Andric /// \param TemplateParams The template parameters that we are deducing
11670b57cec5SDimitry Andric ///
11680b57cec5SDimitry Andric /// \param Params The list of parameter types
11690b57cec5SDimitry Andric ///
11700b57cec5SDimitry Andric /// \param NumParams The number of types in \c Params
11710b57cec5SDimitry Andric ///
11720b57cec5SDimitry Andric /// \param Args The list of argument types
11730b57cec5SDimitry Andric ///
11740b57cec5SDimitry Andric /// \param NumArgs The number of types in \c Args
11750b57cec5SDimitry Andric ///
11760b57cec5SDimitry Andric /// \param Info information about the template argument deduction itself
11770b57cec5SDimitry Andric ///
11780b57cec5SDimitry Andric /// \param Deduced the deduced template arguments
11790b57cec5SDimitry Andric ///
11800b57cec5SDimitry Andric /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
11810b57cec5SDimitry Andric /// how template argument deduction is performed.
11820b57cec5SDimitry Andric ///
11830b57cec5SDimitry Andric /// \param PartialOrdering If true, we are performing template argument
11840b57cec5SDimitry Andric /// deduction for during partial ordering for a call
11850b57cec5SDimitry Andric /// (C++0x [temp.deduct.partial]).
11860b57cec5SDimitry Andric ///
11870b57cec5SDimitry Andric /// \returns the result of template argument deduction so far. Note that a
11880b57cec5SDimitry Andric /// "success" result means that template argument deduction has not yet failed,
11890b57cec5SDimitry Andric /// but it may still fail, later, for other reasons.
1190*0fca6ea1SDimitry Andric static TemplateDeductionResult
DeduceTemplateArguments(Sema & S,TemplateParameterList * TemplateParams,const QualType * Params,unsigned NumParams,const QualType * Args,unsigned NumArgs,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced,unsigned TDF,bool PartialOrdering=false)1191*0fca6ea1SDimitry Andric DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
11920b57cec5SDimitry Andric                         const QualType *Params, unsigned NumParams,
11930b57cec5SDimitry Andric                         const QualType *Args, unsigned NumArgs,
11940b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
11950b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1196*0fca6ea1SDimitry Andric                         unsigned TDF, bool PartialOrdering = false) {
11970b57cec5SDimitry Andric   // C++0x [temp.deduct.type]p10:
11980b57cec5SDimitry Andric   //   Similarly, if P has a form that contains (T), then each parameter type
11990b57cec5SDimitry Andric   //   Pi of the respective parameter-type- list of P is compared with the
12000b57cec5SDimitry Andric   //   corresponding parameter type Ai of the corresponding parameter-type-list
12010b57cec5SDimitry Andric   //   of A. [...]
12020b57cec5SDimitry Andric   unsigned ArgIdx = 0, ParamIdx = 0;
12030b57cec5SDimitry Andric   for (; ParamIdx != NumParams; ++ParamIdx) {
12040b57cec5SDimitry Andric     // Check argument types.
12050b57cec5SDimitry Andric     const PackExpansionType *Expansion
12060b57cec5SDimitry Andric                                 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
12070b57cec5SDimitry Andric     if (!Expansion) {
12080b57cec5SDimitry Andric       // Simple case: compare the parameter and argument types at this point.
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric       // Make sure we have an argument.
12110b57cec5SDimitry Andric       if (ArgIdx >= NumArgs)
1212*0fca6ea1SDimitry Andric         return TemplateDeductionResult::MiscellaneousDeductionFailure;
12130b57cec5SDimitry Andric 
12140b57cec5SDimitry Andric       if (isa<PackExpansionType>(Args[ArgIdx])) {
12150b57cec5SDimitry Andric         // C++0x [temp.deduct.type]p22:
12160b57cec5SDimitry Andric         //   If the original function parameter associated with A is a function
12170b57cec5SDimitry Andric         //   parameter pack and the function parameter associated with P is not
12180b57cec5SDimitry Andric         //   a function parameter pack, then template argument deduction fails.
1219*0fca6ea1SDimitry Andric         return TemplateDeductionResult::MiscellaneousDeductionFailure;
12200b57cec5SDimitry Andric       }
12210b57cec5SDimitry Andric 
1222*0fca6ea1SDimitry Andric       if (TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch(
1223349cc55cSDimitry Andric               S, TemplateParams, Params[ParamIdx].getUnqualifiedType(),
1224349cc55cSDimitry Andric               Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1225349cc55cSDimitry Andric               PartialOrdering,
1226*0fca6ea1SDimitry Andric               /*DeducedFromArrayBound=*/false);
1227*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
12280b57cec5SDimitry Andric         return Result;
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric       ++ArgIdx;
12310b57cec5SDimitry Andric       continue;
12320b57cec5SDimitry Andric     }
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric     // C++0x [temp.deduct.type]p10:
12350b57cec5SDimitry Andric     //   If the parameter-declaration corresponding to Pi is a function
12360b57cec5SDimitry Andric     //   parameter pack, then the type of its declarator- id is compared with
12370b57cec5SDimitry Andric     //   each remaining parameter type in the parameter-type-list of A. Each
12380b57cec5SDimitry Andric     //   comparison deduces template arguments for subsequent positions in the
12390b57cec5SDimitry Andric     //   template parameter packs expanded by the function parameter pack.
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric     QualType Pattern = Expansion->getPattern();
12420b57cec5SDimitry Andric     PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
12430b57cec5SDimitry Andric 
12440b57cec5SDimitry Andric     // A pack scope with fixed arity is not really a pack any more, so is not
12450b57cec5SDimitry Andric     // a non-deduced context.
12460b57cec5SDimitry Andric     if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
12470b57cec5SDimitry Andric       for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
12480b57cec5SDimitry Andric         // Deduce template arguments from the pattern.
1249*0fca6ea1SDimitry Andric         if (TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch(
1250349cc55cSDimitry Andric                 S, TemplateParams, Pattern.getUnqualifiedType(),
1251349cc55cSDimitry Andric                 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1252*0fca6ea1SDimitry Andric                 PartialOrdering, /*DeducedFromArrayBound=*/false);
1253*0fca6ea1SDimitry Andric             Result != TemplateDeductionResult::Success)
12540b57cec5SDimitry Andric           return Result;
12550b57cec5SDimitry Andric 
12560b57cec5SDimitry Andric         PackScope.nextPackElement();
12570b57cec5SDimitry Andric       }
12580b57cec5SDimitry Andric     } else {
12590b57cec5SDimitry Andric       // C++0x [temp.deduct.type]p5:
12600b57cec5SDimitry Andric       //   The non-deduced contexts are:
12610b57cec5SDimitry Andric       //     - A function parameter pack that does not occur at the end of the
12620b57cec5SDimitry Andric       //       parameter-declaration-clause.
12630b57cec5SDimitry Andric       //
12640b57cec5SDimitry Andric       // FIXME: There is no wording to say what we should do in this case. We
12650b57cec5SDimitry Andric       // choose to resolve this by applying the same rule that is applied for a
12660b57cec5SDimitry Andric       // function call: that is, deduce all contained packs to their
12670b57cec5SDimitry Andric       // explicitly-specified values (or to <> if there is no such value).
12680b57cec5SDimitry Andric       //
12690b57cec5SDimitry Andric       // This is seemingly-arbitrarily different from the case of a template-id
12700b57cec5SDimitry Andric       // with a non-trailing pack-expansion in its arguments, which renders the
12710b57cec5SDimitry Andric       // entire template-argument-list a non-deduced context.
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric       // If the parameter type contains an explicitly-specified pack that we
12740b57cec5SDimitry Andric       // could not expand, skip the number of parameters notionally created
12750b57cec5SDimitry Andric       // by the expansion.
1276bdd1243dSDimitry Andric       std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
12770b57cec5SDimitry Andric       if (NumExpansions && !PackScope.isPartiallyExpanded()) {
12780b57cec5SDimitry Andric         for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
12790b57cec5SDimitry Andric              ++I, ++ArgIdx)
12800b57cec5SDimitry Andric           PackScope.nextPackElement();
12810b57cec5SDimitry Andric       }
12820b57cec5SDimitry Andric     }
12830b57cec5SDimitry Andric 
12840b57cec5SDimitry Andric     // Build argument packs for each of the parameter packs expanded by this
12850b57cec5SDimitry Andric     // pack expansion.
1286*0fca6ea1SDimitry Andric     if (auto Result = PackScope.finish();
1287*0fca6ea1SDimitry Andric         Result != TemplateDeductionResult::Success)
12880b57cec5SDimitry Andric       return Result;
12890b57cec5SDimitry Andric   }
12900b57cec5SDimitry Andric 
1291bdd1243dSDimitry Andric   // DR692, DR1395
1292bdd1243dSDimitry Andric   // C++0x [temp.deduct.type]p10:
1293bdd1243dSDimitry Andric   // If the parameter-declaration corresponding to P_i ...
1294bdd1243dSDimitry Andric   // During partial ordering, if Ai was originally a function parameter pack:
1295bdd1243dSDimitry Andric   // - if P does not contain a function parameter type corresponding to Ai then
1296bdd1243dSDimitry Andric   //   Ai is ignored;
1297bdd1243dSDimitry Andric   if (PartialOrdering && ArgIdx + 1 == NumArgs &&
1298bdd1243dSDimitry Andric       isa<PackExpansionType>(Args[ArgIdx]))
1299*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
1300bdd1243dSDimitry Andric 
13010b57cec5SDimitry Andric   // Make sure we don't have any extra arguments.
13020b57cec5SDimitry Andric   if (ArgIdx < NumArgs)
1303*0fca6ea1SDimitry Andric     return TemplateDeductionResult::MiscellaneousDeductionFailure;
13040b57cec5SDimitry Andric 
1305*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric 
13080b57cec5SDimitry Andric /// Determine whether the parameter has qualifiers that the argument
13090b57cec5SDimitry Andric /// lacks. Put another way, determine whether there is no way to add
13100b57cec5SDimitry Andric /// a deduced set of qualifiers to the ParamType that would result in
13110b57cec5SDimitry Andric /// its qualifiers matching those of the ArgType.
hasInconsistentOrSupersetQualifiersOf(QualType ParamType,QualType ArgType)13120b57cec5SDimitry Andric static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
13130b57cec5SDimitry Andric                                                   QualType ArgType) {
13140b57cec5SDimitry Andric   Qualifiers ParamQs = ParamType.getQualifiers();
13150b57cec5SDimitry Andric   Qualifiers ArgQs = ArgType.getQualifiers();
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric   if (ParamQs == ArgQs)
13180b57cec5SDimitry Andric     return false;
13190b57cec5SDimitry Andric 
13200b57cec5SDimitry Andric   // Mismatched (but not missing) Objective-C GC attributes.
13210b57cec5SDimitry Andric   if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
13220b57cec5SDimitry Andric       ParamQs.hasObjCGCAttr())
13230b57cec5SDimitry Andric     return true;
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   // Mismatched (but not missing) address spaces.
13260b57cec5SDimitry Andric   if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
13270b57cec5SDimitry Andric       ParamQs.hasAddressSpace())
13280b57cec5SDimitry Andric     return true;
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric   // Mismatched (but not missing) Objective-C lifetime qualifiers.
13310b57cec5SDimitry Andric   if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
13320b57cec5SDimitry Andric       ParamQs.hasObjCLifetime())
13330b57cec5SDimitry Andric     return true;
13340b57cec5SDimitry Andric 
13350b57cec5SDimitry Andric   // CVR qualifiers inconsistent or a superset.
13360b57cec5SDimitry Andric   return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
13370b57cec5SDimitry Andric }
13380b57cec5SDimitry Andric 
isSameOrCompatibleFunctionType(QualType P,QualType A)1339349cc55cSDimitry Andric bool Sema::isSameOrCompatibleFunctionType(QualType P, QualType A) {
1340349cc55cSDimitry Andric   const FunctionType *PF = P->getAs<FunctionType>(),
1341349cc55cSDimitry Andric                      *AF = A->getAs<FunctionType>();
13420b57cec5SDimitry Andric 
13430b57cec5SDimitry Andric   // Just compare if not functions.
1344349cc55cSDimitry Andric   if (!PF || !AF)
1345349cc55cSDimitry Andric     return Context.hasSameType(P, A);
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric   // Noreturn and noexcept adjustment.
1348*0fca6ea1SDimitry Andric   if (QualType AdjustedParam; IsFunctionConversion(P, A, AdjustedParam))
1349*0fca6ea1SDimitry Andric     P = AdjustedParam;
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric   // FIXME: Compatible calling conventions.
1352*0fca6ea1SDimitry Andric   return Context.hasSameFunctionTypeIgnoringExceptionSpec(P, A);
13530b57cec5SDimitry Andric }
13540b57cec5SDimitry Andric 
13550b57cec5SDimitry Andric /// Get the index of the first template parameter that was originally from the
13560b57cec5SDimitry Andric /// innermost template-parameter-list. This is 0 except when we concatenate
13570b57cec5SDimitry Andric /// the template parameter lists of a class template and a constructor template
13580b57cec5SDimitry Andric /// when forming an implicit deduction guide.
getFirstInnerIndex(FunctionTemplateDecl * FTD)13590b57cec5SDimitry Andric static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
13600b57cec5SDimitry Andric   auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
13610b57cec5SDimitry Andric   if (!Guide || !Guide->isImplicit())
13620b57cec5SDimitry Andric     return 0;
13630b57cec5SDimitry Andric   return Guide->getDeducedTemplate()->getTemplateParameters()->size();
13640b57cec5SDimitry Andric }
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric /// Determine whether a type denotes a forwarding reference.
isForwardingReference(QualType Param,unsigned FirstInnerIndex)13670b57cec5SDimitry Andric static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
13680b57cec5SDimitry Andric   // C++1z [temp.deduct.call]p3:
13690b57cec5SDimitry Andric   //   A forwarding reference is an rvalue reference to a cv-unqualified
13700b57cec5SDimitry Andric   //   template parameter that does not represent a template parameter of a
13710b57cec5SDimitry Andric   //   class template.
13720b57cec5SDimitry Andric   if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
13730b57cec5SDimitry Andric     if (ParamRef->getPointeeType().getQualifiers())
13740b57cec5SDimitry Andric       return false;
13750b57cec5SDimitry Andric     auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
13760b57cec5SDimitry Andric     return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
13770b57cec5SDimitry Andric   }
13780b57cec5SDimitry Andric   return false;
13790b57cec5SDimitry Andric }
13800b57cec5SDimitry Andric 
getCanonicalRD(QualType T)1381349cc55cSDimitry Andric static CXXRecordDecl *getCanonicalRD(QualType T) {
1382349cc55cSDimitry Andric   return cast<CXXRecordDecl>(
1383349cc55cSDimitry Andric       T->castAs<RecordType>()->getDecl()->getCanonicalDecl());
1384349cc55cSDimitry Andric }
1385349cc55cSDimitry Andric 
1386e8d8bef9SDimitry Andric ///  Attempt to deduce the template arguments by checking the base types
1387e8d8bef9SDimitry Andric ///  according to (C++20 [temp.deduct.call] p4b3.
1388e8d8bef9SDimitry Andric ///
1389e8d8bef9SDimitry Andric /// \param S the semantic analysis object within which we are deducing.
1390e8d8bef9SDimitry Andric ///
139181ad6265SDimitry Andric /// \param RD the top level record object we are deducing against.
1392e8d8bef9SDimitry Andric ///
1393e8d8bef9SDimitry Andric /// \param TemplateParams the template parameters that we are deducing.
1394e8d8bef9SDimitry Andric ///
139581ad6265SDimitry Andric /// \param P the template specialization parameter type.
1396e8d8bef9SDimitry Andric ///
1397e8d8bef9SDimitry Andric /// \param Info information about the template argument deduction itself.
1398e8d8bef9SDimitry Andric ///
1399e8d8bef9SDimitry Andric /// \param Deduced the deduced template arguments.
1400e8d8bef9SDimitry Andric ///
1401e8d8bef9SDimitry Andric /// \returns the result of template argument deduction with the bases. "invalid"
1402e8d8bef9SDimitry Andric /// means no matches, "success" found a single item, and the
1403e8d8bef9SDimitry Andric /// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1404*0fca6ea1SDimitry Andric static TemplateDeductionResult
DeduceTemplateBases(Sema & S,const CXXRecordDecl * RD,TemplateParameterList * TemplateParams,QualType P,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced)1405349cc55cSDimitry Andric DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD,
1406349cc55cSDimitry Andric                     TemplateParameterList *TemplateParams, QualType P,
1407349cc55cSDimitry Andric                     TemplateDeductionInfo &Info,
1408e8d8bef9SDimitry Andric                     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1409e8d8bef9SDimitry Andric   // C++14 [temp.deduct.call] p4b3:
1410e8d8bef9SDimitry Andric   //   If P is a class and P has the form simple-template-id, then the
1411e8d8bef9SDimitry Andric   //   transformed A can be a derived class of the deduced A. Likewise if
1412e8d8bef9SDimitry Andric   //   P is a pointer to a class of the form simple-template-id, the
1413e8d8bef9SDimitry Andric   //   transformed A can be a pointer to a derived class pointed to by the
1414e8d8bef9SDimitry Andric   //   deduced A. However, if there is a class C that is a (direct or
1415e8d8bef9SDimitry Andric   //   indirect) base class of D and derived (directly or indirectly) from a
1416e8d8bef9SDimitry Andric   //   class B and that would be a valid deduced A, the deduced A cannot be
1417e8d8bef9SDimitry Andric   //   B or pointer to B, respectively.
1418e8d8bef9SDimitry Andric   //
1419e8d8bef9SDimitry Andric   //   These alternatives are considered only if type deduction would
1420e8d8bef9SDimitry Andric   //   otherwise fail. If they yield more than one possible deduced A, the
1421e8d8bef9SDimitry Andric   //   type deduction fails.
1422e8d8bef9SDimitry Andric 
1423e8d8bef9SDimitry Andric   // Use a breadth-first search through the bases to collect the set of
1424e8d8bef9SDimitry Andric   // successful matches. Visited contains the set of nodes we have already
1425e8d8bef9SDimitry Andric   // visited, while ToVisit is our stack of records that we still need to
1426e8d8bef9SDimitry Andric   // visit.  Matches contains a list of matches that have yet to be
1427e8d8bef9SDimitry Andric   // disqualified.
1428349cc55cSDimitry Andric   llvm::SmallPtrSet<const CXXRecordDecl *, 8> Visited;
1429349cc55cSDimitry Andric   SmallVector<QualType, 8> ToVisit;
1430e8d8bef9SDimitry Andric   // We iterate over this later, so we have to use MapVector to ensure
1431e8d8bef9SDimitry Andric   // determinism.
1432349cc55cSDimitry Andric   llvm::MapVector<const CXXRecordDecl *,
1433349cc55cSDimitry Andric                   SmallVector<DeducedTemplateArgument, 8>>
1434e8d8bef9SDimitry Andric       Matches;
1435e8d8bef9SDimitry Andric 
1436349cc55cSDimitry Andric   auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1437e8d8bef9SDimitry Andric     for (const auto &Base : RD->bases()) {
1438349cc55cSDimitry Andric       QualType T = Base.getType();
1439349cc55cSDimitry Andric       assert(T->isRecordType() && "Base class that isn't a record?");
1440349cc55cSDimitry Andric       if (Visited.insert(::getCanonicalRD(T)).second)
1441349cc55cSDimitry Andric         ToVisit.push_back(T);
1442e8d8bef9SDimitry Andric     }
1443e8d8bef9SDimitry Andric   };
1444e8d8bef9SDimitry Andric 
1445e8d8bef9SDimitry Andric   // Set up the loop by adding all the bases.
1446349cc55cSDimitry Andric   AddBases(RD);
1447e8d8bef9SDimitry Andric 
1448e8d8bef9SDimitry Andric   // Search each path of bases until we either run into a successful match
1449e8d8bef9SDimitry Andric   // (where all bases of it are invalid), or we run out of bases.
1450e8d8bef9SDimitry Andric   while (!ToVisit.empty()) {
1451349cc55cSDimitry Andric     QualType NextT = ToVisit.pop_back_val();
1452e8d8bef9SDimitry Andric 
1453e8d8bef9SDimitry Andric     SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1454e8d8bef9SDimitry Andric                                                         Deduced.end());
1455e8d8bef9SDimitry Andric     TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info);
1456*0fca6ea1SDimitry Andric     TemplateDeductionResult BaseResult = DeduceTemplateSpecArguments(
1457349cc55cSDimitry Andric         S, TemplateParams, P, NextT, BaseInfo, DeducedCopy);
1458e8d8bef9SDimitry Andric 
1459e8d8bef9SDimitry Andric     // If this was a successful deduction, add it to the list of matches,
1460e8d8bef9SDimitry Andric     // otherwise we need to continue searching its bases.
1461349cc55cSDimitry Andric     const CXXRecordDecl *RD = ::getCanonicalRD(NextT);
1462*0fca6ea1SDimitry Andric     if (BaseResult == TemplateDeductionResult::Success)
1463349cc55cSDimitry Andric       Matches.insert({RD, DeducedCopy});
1464e8d8bef9SDimitry Andric     else
1465349cc55cSDimitry Andric       AddBases(RD);
1466e8d8bef9SDimitry Andric   }
1467e8d8bef9SDimitry Andric 
1468e8d8bef9SDimitry Andric   // At this point, 'Matches' contains a list of seemingly valid bases, however
1469e8d8bef9SDimitry Andric   // in the event that we have more than 1 match, it is possible that the base
1470e8d8bef9SDimitry Andric   // of one of the matches might be disqualified for being a base of another
1471e8d8bef9SDimitry Andric   // valid match. We can count on cyclical instantiations being invalid to
1472e8d8bef9SDimitry Andric   // simplify the disqualifications.  That is, if A & B are both matches, and B
1473e8d8bef9SDimitry Andric   // inherits from A (disqualifying A), we know that A cannot inherit from B.
1474e8d8bef9SDimitry Andric   if (Matches.size() > 1) {
1475e8d8bef9SDimitry Andric     Visited.clear();
1476e8d8bef9SDimitry Andric     for (const auto &Match : Matches)
1477e8d8bef9SDimitry Andric       AddBases(Match.first);
1478e8d8bef9SDimitry Andric 
1479e8d8bef9SDimitry Andric     // We can give up once we have a single item (or have run out of things to
1480349cc55cSDimitry Andric     // search) since cyclical inheritance isn't valid.
1481e8d8bef9SDimitry Andric     while (Matches.size() > 1 && !ToVisit.empty()) {
1482349cc55cSDimitry Andric       const CXXRecordDecl *RD = ::getCanonicalRD(ToVisit.pop_back_val());
1483349cc55cSDimitry Andric       Matches.erase(RD);
1484e8d8bef9SDimitry Andric 
1485349cc55cSDimitry Andric       // Always add all bases, since the inheritance tree can contain
1486e8d8bef9SDimitry Andric       // disqualifications for multiple matches.
1487349cc55cSDimitry Andric       AddBases(RD);
1488e8d8bef9SDimitry Andric     }
1489e8d8bef9SDimitry Andric   }
1490e8d8bef9SDimitry Andric 
1491e8d8bef9SDimitry Andric   if (Matches.empty())
1492*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Invalid;
1493e8d8bef9SDimitry Andric   if (Matches.size() > 1)
1494*0fca6ea1SDimitry Andric     return TemplateDeductionResult::MiscellaneousDeductionFailure;
1495e8d8bef9SDimitry Andric 
1496e8d8bef9SDimitry Andric   std::swap(Matches.front().second, Deduced);
1497*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
1498e8d8bef9SDimitry Andric }
1499e8d8bef9SDimitry Andric 
15000b57cec5SDimitry Andric /// Deduce the template arguments by comparing the parameter type and
15010b57cec5SDimitry Andric /// the argument type (C++ [temp.deduct.type]).
15020b57cec5SDimitry Andric ///
15030b57cec5SDimitry Andric /// \param S the semantic analysis object within which we are deducing
15040b57cec5SDimitry Andric ///
15050b57cec5SDimitry Andric /// \param TemplateParams the template parameters that we are deducing
15060b57cec5SDimitry Andric ///
150781ad6265SDimitry Andric /// \param P the parameter type
15080b57cec5SDimitry Andric ///
150981ad6265SDimitry Andric /// \param A the argument type
15100b57cec5SDimitry Andric ///
15110b57cec5SDimitry Andric /// \param Info information about the template argument deduction itself
15120b57cec5SDimitry Andric ///
15130b57cec5SDimitry Andric /// \param Deduced the deduced template arguments
15140b57cec5SDimitry Andric ///
15150b57cec5SDimitry Andric /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
15160b57cec5SDimitry Andric /// how template argument deduction is performed.
15170b57cec5SDimitry Andric ///
15180b57cec5SDimitry Andric /// \param PartialOrdering Whether we're performing template argument deduction
15190b57cec5SDimitry Andric /// in the context of partial ordering (C++0x [temp.deduct.partial]).
15200b57cec5SDimitry Andric ///
15210b57cec5SDimitry Andric /// \returns the result of template argument deduction so far. Note that a
15220b57cec5SDimitry Andric /// "success" result means that template argument deduction has not yet failed,
15230b57cec5SDimitry Andric /// but it may still fail, later, for other reasons.
DeduceTemplateArgumentsByTypeMatch(Sema & S,TemplateParameterList * TemplateParams,QualType P,QualType A,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced,unsigned TDF,bool PartialOrdering,bool DeducedFromArrayBound)1524*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
1525349cc55cSDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
15260b57cec5SDimitry Andric     TemplateDeductionInfo &Info,
1527349cc55cSDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1528349cc55cSDimitry Andric     bool PartialOrdering, bool DeducedFromArrayBound) {
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric   // If the argument type is a pack expansion, look at its pattern.
15310b57cec5SDimitry Andric   // This isn't explicitly called out
1532349cc55cSDimitry Andric   if (const auto *AExp = dyn_cast<PackExpansionType>(A))
1533349cc55cSDimitry Andric     A = AExp->getPattern();
1534349cc55cSDimitry Andric   assert(!isa<PackExpansionType>(A.getCanonicalType()));
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric   if (PartialOrdering) {
15370b57cec5SDimitry Andric     // C++11 [temp.deduct.partial]p5:
15380b57cec5SDimitry Andric     //   Before the partial ordering is done, certain transformations are
15390b57cec5SDimitry Andric     //   performed on the types used for partial ordering:
15400b57cec5SDimitry Andric     //     - If P is a reference type, P is replaced by the type referred to.
1541349cc55cSDimitry Andric     const ReferenceType *PRef = P->getAs<ReferenceType>();
1542349cc55cSDimitry Andric     if (PRef)
1543349cc55cSDimitry Andric       P = PRef->getPointeeType();
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric     //     - If A is a reference type, A is replaced by the type referred to.
1546349cc55cSDimitry Andric     const ReferenceType *ARef = A->getAs<ReferenceType>();
1547349cc55cSDimitry Andric     if (ARef)
1548349cc55cSDimitry Andric       A = A->getPointeeType();
15490b57cec5SDimitry Andric 
1550349cc55cSDimitry Andric     if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
15510b57cec5SDimitry Andric       // C++11 [temp.deduct.partial]p9:
15520b57cec5SDimitry Andric       //   If, for a given type, deduction succeeds in both directions (i.e.,
15530b57cec5SDimitry Andric       //   the types are identical after the transformations above) and both
15540b57cec5SDimitry Andric       //   P and A were reference types [...]:
15550b57cec5SDimitry Andric       //     - if [one type] was an lvalue reference and [the other type] was
15560b57cec5SDimitry Andric       //       not, [the other type] is not considered to be at least as
15570b57cec5SDimitry Andric       //       specialized as [the first type]
15580b57cec5SDimitry Andric       //     - if [one type] is more cv-qualified than [the other type],
15590b57cec5SDimitry Andric       //       [the other type] is not considered to be at least as specialized
15600b57cec5SDimitry Andric       //       as [the first type]
15610b57cec5SDimitry Andric       // Objective-C ARC adds:
15620b57cec5SDimitry Andric       //     - [one type] has non-trivial lifetime, [the other type] has
15630b57cec5SDimitry Andric       //       __unsafe_unretained lifetime, and the types are otherwise
15640b57cec5SDimitry Andric       //       identical
15650b57cec5SDimitry Andric       //
15660b57cec5SDimitry Andric       // A is "considered to be at least as specialized" as P iff deduction
15670b57cec5SDimitry Andric       // succeeds, so we model this as a deduction failure. Note that
15680b57cec5SDimitry Andric       // [the first type] is P and [the other type] is A here; the standard
15690b57cec5SDimitry Andric       // gets this backwards.
1570349cc55cSDimitry Andric       Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1571349cc55cSDimitry Andric       if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1572349cc55cSDimitry Andric           PQuals.isStrictSupersetOf(AQuals) ||
1573349cc55cSDimitry Andric           (PQuals.hasNonTrivialObjCLifetime() &&
1574349cc55cSDimitry Andric            AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1575349cc55cSDimitry Andric            PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1576349cc55cSDimitry Andric         Info.FirstArg = TemplateArgument(P);
1577349cc55cSDimitry Andric         Info.SecondArg = TemplateArgument(A);
1578*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
15790b57cec5SDimitry Andric       }
15800b57cec5SDimitry Andric     }
1581349cc55cSDimitry Andric     Qualifiers DiscardedQuals;
15820b57cec5SDimitry Andric     // C++11 [temp.deduct.partial]p7:
15830b57cec5SDimitry Andric     //   Remove any top-level cv-qualifiers:
15840b57cec5SDimitry Andric     //     - If P is a cv-qualified type, P is replaced by the cv-unqualified
15850b57cec5SDimitry Andric     //       version of P.
1586349cc55cSDimitry Andric     P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
15870b57cec5SDimitry Andric     //     - If A is a cv-qualified type, A is replaced by the cv-unqualified
15880b57cec5SDimitry Andric     //       version of A.
1589349cc55cSDimitry Andric     A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
15900b57cec5SDimitry Andric   } else {
15910b57cec5SDimitry Andric     // C++0x [temp.deduct.call]p4 bullet 1:
15920b57cec5SDimitry Andric     //   - If the original P is a reference type, the deduced A (i.e., the type
15930b57cec5SDimitry Andric     //     referred to by the reference) can be more cv-qualified than the
15940b57cec5SDimitry Andric     //     transformed A.
15950b57cec5SDimitry Andric     if (TDF & TDF_ParamWithReferenceType) {
15960b57cec5SDimitry Andric       Qualifiers Quals;
1597349cc55cSDimitry Andric       QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1598349cc55cSDimitry Andric       Quals.setCVRQualifiers(Quals.getCVRQualifiers() & A.getCVRQualifiers());
1599349cc55cSDimitry Andric       P = S.Context.getQualifiedType(UnqualP, Quals);
16000b57cec5SDimitry Andric     }
16010b57cec5SDimitry Andric 
1602349cc55cSDimitry Andric     if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
16030b57cec5SDimitry Andric       // C++0x [temp.deduct.type]p10:
16040b57cec5SDimitry Andric       //   If P and A are function types that originated from deduction when
16050b57cec5SDimitry Andric       //   taking the address of a function template (14.8.2.2) or when deducing
16060b57cec5SDimitry Andric       //   template arguments from a function declaration (14.8.2.6) and Pi and
16070b57cec5SDimitry Andric       //   Ai are parameters of the top-level parameter-type-list of P and A,
16080b57cec5SDimitry Andric       //   respectively, Pi is adjusted if it is a forwarding reference and Ai
16090b57cec5SDimitry Andric       //   is an lvalue reference, in
16100b57cec5SDimitry Andric       //   which case the type of Pi is changed to be the template parameter
16110b57cec5SDimitry Andric       //   type (i.e., T&& is changed to simply T). [ Note: As a result, when
16120b57cec5SDimitry Andric       //   Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
16130b57cec5SDimitry Andric       //   deduced as X&. - end note ]
16140b57cec5SDimitry Andric       TDF &= ~TDF_TopLevelParameterTypeList;
1615349cc55cSDimitry Andric       if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1616349cc55cSDimitry Andric           A->isLValueReferenceType())
1617349cc55cSDimitry Andric         P = P->getPointeeType();
16180b57cec5SDimitry Andric     }
16190b57cec5SDimitry Andric   }
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric   // C++ [temp.deduct.type]p9:
16220b57cec5SDimitry Andric   //   A template type argument T, a template template argument TT or a
16230b57cec5SDimitry Andric   //   template non-type argument i can be deduced if P and A have one of
16240b57cec5SDimitry Andric   //   the following forms:
16250b57cec5SDimitry Andric   //
16260b57cec5SDimitry Andric   //     T
16270b57cec5SDimitry Andric   //     cv-list T
1628349cc55cSDimitry Andric   if (const auto *TTP = P->getAs<TemplateTypeParmType>()) {
16290b57cec5SDimitry Andric     // Just skip any attempts to deduce from a placeholder type or a parameter
16300b57cec5SDimitry Andric     // at a different depth.
1631349cc55cSDimitry Andric     if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1632*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
16330b57cec5SDimitry Andric 
1634349cc55cSDimitry Andric     unsigned Index = TTP->getIndex();
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric     // If the argument type is an array type, move the qualifiers up to the
16370b57cec5SDimitry Andric     // top level, so they can be matched with the qualifiers on the parameter.
1638349cc55cSDimitry Andric     if (A->isArrayType()) {
16390b57cec5SDimitry Andric       Qualifiers Quals;
1640349cc55cSDimitry Andric       A = S.Context.getUnqualifiedArrayType(A, Quals);
1641349cc55cSDimitry Andric       if (Quals)
1642349cc55cSDimitry Andric         A = S.Context.getQualifiedType(A, Quals);
16430b57cec5SDimitry Andric     }
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric     // The argument type can not be less qualified than the parameter
16460b57cec5SDimitry Andric     // type.
16470b57cec5SDimitry Andric     if (!(TDF & TDF_IgnoreQualifiers) &&
1648349cc55cSDimitry Andric         hasInconsistentOrSupersetQualifiersOf(P, A)) {
16490b57cec5SDimitry Andric       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1650349cc55cSDimitry Andric       Info.FirstArg = TemplateArgument(P);
1651349cc55cSDimitry Andric       Info.SecondArg = TemplateArgument(A);
1652*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Underqualified;
16530b57cec5SDimitry Andric     }
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric     // Do not match a function type with a cv-qualified type.
16560b57cec5SDimitry Andric     // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1657349cc55cSDimitry Andric     if (A->isFunctionType() && P.hasQualifiers())
1658*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
16590b57cec5SDimitry Andric 
1660349cc55cSDimitry Andric     assert(TTP->getDepth() == Info.getDeducedDepth() &&
16610b57cec5SDimitry Andric            "saw template type parameter with wrong depth");
1662349cc55cSDimitry Andric     assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&
1663349cc55cSDimitry Andric            "Unresolved overloaded function");
1664349cc55cSDimitry Andric     QualType DeducedType = A;
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric     // Remove any qualifiers on the parameter from the deduced type.
16670b57cec5SDimitry Andric     // We checked the qualifiers for consistency above.
16680b57cec5SDimitry Andric     Qualifiers DeducedQs = DeducedType.getQualifiers();
1669349cc55cSDimitry Andric     Qualifiers ParamQs = P.getQualifiers();
16700b57cec5SDimitry Andric     DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
16710b57cec5SDimitry Andric     if (ParamQs.hasObjCGCAttr())
16720b57cec5SDimitry Andric       DeducedQs.removeObjCGCAttr();
16730b57cec5SDimitry Andric     if (ParamQs.hasAddressSpace())
16740b57cec5SDimitry Andric       DeducedQs.removeAddressSpace();
16750b57cec5SDimitry Andric     if (ParamQs.hasObjCLifetime())
16760b57cec5SDimitry Andric       DeducedQs.removeObjCLifetime();
16770b57cec5SDimitry Andric 
16780b57cec5SDimitry Andric     // Objective-C ARC:
16790b57cec5SDimitry Andric     //   If template deduction would produce a lifetime qualifier on a type
16800b57cec5SDimitry Andric     //   that is not a lifetime type, template argument deduction fails.
16810b57cec5SDimitry Andric     if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
16820b57cec5SDimitry Andric         !DeducedType->isDependentType()) {
16830b57cec5SDimitry Andric       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1684349cc55cSDimitry Andric       Info.FirstArg = TemplateArgument(P);
1685349cc55cSDimitry Andric       Info.SecondArg = TemplateArgument(A);
1686*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Underqualified;
16870b57cec5SDimitry Andric     }
16880b57cec5SDimitry Andric 
16890b57cec5SDimitry Andric     // Objective-C ARC:
16900b57cec5SDimitry Andric     //   If template deduction would produce an argument type with lifetime type
16910b57cec5SDimitry Andric     //   but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1692349cc55cSDimitry Andric     if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
16930b57cec5SDimitry Andric         !DeducedQs.hasObjCLifetime())
16940b57cec5SDimitry Andric       DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
16950b57cec5SDimitry Andric 
1696349cc55cSDimitry Andric     DeducedType =
1697349cc55cSDimitry Andric         S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric     DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1700349cc55cSDimitry Andric     DeducedTemplateArgument Result =
1701349cc55cSDimitry Andric         checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
17020b57cec5SDimitry Andric     if (Result.isNull()) {
17030b57cec5SDimitry Andric       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
17040b57cec5SDimitry Andric       Info.FirstArg = Deduced[Index];
17050b57cec5SDimitry Andric       Info.SecondArg = NewDeduced;
1706*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Inconsistent;
17070b57cec5SDimitry Andric     }
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric     Deduced[Index] = Result;
1710*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
17110b57cec5SDimitry Andric   }
17120b57cec5SDimitry Andric 
17130b57cec5SDimitry Andric   // Set up the template argument deduction information for a failure.
1714349cc55cSDimitry Andric   Info.FirstArg = TemplateArgument(P);
1715349cc55cSDimitry Andric   Info.SecondArg = TemplateArgument(A);
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric   // If the parameter is an already-substituted template parameter
17180b57cec5SDimitry Andric   // pack, do nothing: we don't know which of its arguments to look
17190b57cec5SDimitry Andric   // at, so we have to wait until all of the parameter packs in this
17200b57cec5SDimitry Andric   // expansion have arguments.
1721349cc55cSDimitry Andric   if (P->getAs<SubstTemplateTypeParmPackType>())
1722*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
17230b57cec5SDimitry Andric 
17240b57cec5SDimitry Andric   // Check the cv-qualifiers on the parameter and argument types.
17250b57cec5SDimitry Andric   if (!(TDF & TDF_IgnoreQualifiers)) {
17260b57cec5SDimitry Andric     if (TDF & TDF_ParamWithReferenceType) {
1727349cc55cSDimitry Andric       if (hasInconsistentOrSupersetQualifiersOf(P, A))
1728*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
17290b57cec5SDimitry Andric     } else if (TDF & TDF_ArgWithReferenceType) {
17300b57cec5SDimitry Andric       // C++ [temp.deduct.conv]p4:
17310b57cec5SDimitry Andric       //   If the original A is a reference type, A can be more cv-qualified
17320b57cec5SDimitry Andric       //   than the deduced A
1733349cc55cSDimitry Andric       if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers()))
1734*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
17350b57cec5SDimitry Andric 
17360b57cec5SDimitry Andric       // Strip out all extra qualifiers from the argument to figure out the
17370b57cec5SDimitry Andric       // type we're converting to, prior to the qualification conversion.
17380b57cec5SDimitry Andric       Qualifiers Quals;
1739349cc55cSDimitry Andric       A = S.Context.getUnqualifiedArrayType(A, Quals);
1740349cc55cSDimitry Andric       A = S.Context.getQualifiedType(A, P.getQualifiers());
1741349cc55cSDimitry Andric     } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1742349cc55cSDimitry Andric       if (P.getCVRQualifiers() != A.getCVRQualifiers())
1743*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
17440b57cec5SDimitry Andric     }
1745349cc55cSDimitry Andric   }
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric   // If the parameter type is not dependent, there is nothing to deduce.
1748349cc55cSDimitry Andric   if (!P->isDependentType()) {
1749349cc55cSDimitry Andric     if (TDF & TDF_SkipNonDependent)
1750*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
1751349cc55cSDimitry Andric     if ((TDF & TDF_IgnoreQualifiers) ? S.Context.hasSameUnqualifiedType(P, A)
1752349cc55cSDimitry Andric                                      : S.Context.hasSameType(P, A))
1753*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
1754349cc55cSDimitry Andric     if (TDF & TDF_AllowCompatibleFunctionType &&
1755349cc55cSDimitry Andric         S.isSameOrCompatibleFunctionType(P, A))
1756*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
1757349cc55cSDimitry Andric     if (!(TDF & TDF_IgnoreQualifiers))
1758*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
1759349cc55cSDimitry Andric     // Otherwise, when ignoring qualifiers, the types not having the same
1760349cc55cSDimitry Andric     // unqualified type does not mean they do not match, so in this case we
1761349cc55cSDimitry Andric     // must keep going and analyze with a non-dependent parameter type.
17620b57cec5SDimitry Andric   }
17630b57cec5SDimitry Andric 
1764349cc55cSDimitry Andric   switch (P.getCanonicalType()->getTypeClass()) {
17650b57cec5SDimitry Andric     // Non-canonical types cannot appear here.
17660b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(Class, Base) \
17670b57cec5SDimitry Andric   case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
17680b57cec5SDimitry Andric #define TYPE(Class, Base)
1769a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
17700b57cec5SDimitry Andric 
17710b57cec5SDimitry Andric     case Type::TemplateTypeParm:
17720b57cec5SDimitry Andric     case Type::SubstTemplateTypeParmPack:
17730b57cec5SDimitry Andric       llvm_unreachable("Type nodes handled above");
17740b57cec5SDimitry Andric 
1775349cc55cSDimitry Andric     case Type::Auto:
177606c3fb27SDimitry Andric       // C++23 [temp.deduct.funcaddr]/3:
177706c3fb27SDimitry Andric       //   A placeholder type in the return type of a function template is a
177806c3fb27SDimitry Andric       //   non-deduced context.
177906c3fb27SDimitry Andric       // There's no corresponding wording for [temp.deduct.decl], but we treat
178006c3fb27SDimitry Andric       // it the same to match other compilers.
1781349cc55cSDimitry Andric       if (P->isDependentType())
1782*0fca6ea1SDimitry Andric         return TemplateDeductionResult::Success;
1783bdd1243dSDimitry Andric       [[fallthrough]];
17840b57cec5SDimitry Andric     case Type::Builtin:
17850b57cec5SDimitry Andric     case Type::VariableArray:
17860b57cec5SDimitry Andric     case Type::Vector:
17870b57cec5SDimitry Andric     case Type::FunctionNoProto:
17880b57cec5SDimitry Andric     case Type::Record:
17890b57cec5SDimitry Andric     case Type::Enum:
17900b57cec5SDimitry Andric     case Type::ObjCObject:
17910b57cec5SDimitry Andric     case Type::ObjCInterface:
17920b57cec5SDimitry Andric     case Type::ObjCObjectPointer:
17930eae32dcSDimitry Andric     case Type::BitInt:
1794349cc55cSDimitry Andric       return (TDF & TDF_SkipNonDependent) ||
1795349cc55cSDimitry Andric                      ((TDF & TDF_IgnoreQualifiers)
1796349cc55cSDimitry Andric                           ? S.Context.hasSameUnqualifiedType(P, A)
1797349cc55cSDimitry Andric                           : S.Context.hasSameType(P, A))
1798*0fca6ea1SDimitry Andric                  ? TemplateDeductionResult::Success
1799*0fca6ea1SDimitry Andric                  : TemplateDeductionResult::NonDeducedMismatch;
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric     //     _Complex T   [placeholder extension]
1802349cc55cSDimitry Andric     case Type::Complex: {
1803349cc55cSDimitry Andric       const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1804349cc55cSDimitry Andric       if (!CA)
1805*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
1806349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
1807349cc55cSDimitry Andric           S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1808349cc55cSDimitry Andric           Deduced, TDF);
1809349cc55cSDimitry Andric     }
18100b57cec5SDimitry Andric 
18110b57cec5SDimitry Andric     //     _Atomic T   [extension]
1812349cc55cSDimitry Andric     case Type::Atomic: {
1813349cc55cSDimitry Andric       const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1814349cc55cSDimitry Andric       if (!AA)
1815*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
1816349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
1817349cc55cSDimitry Andric           S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1818349cc55cSDimitry Andric           Deduced, TDF);
1819349cc55cSDimitry Andric     }
18200b57cec5SDimitry Andric 
18210b57cec5SDimitry Andric     //     T *
18220b57cec5SDimitry Andric     case Type::Pointer: {
18230b57cec5SDimitry Andric       QualType PointeeType;
1824349cc55cSDimitry Andric       if (const auto *PA = A->getAs<PointerType>()) {
1825349cc55cSDimitry Andric         PointeeType = PA->getPointeeType();
1826349cc55cSDimitry Andric       } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1827349cc55cSDimitry Andric         PointeeType = PA->getPointeeType();
18280b57cec5SDimitry Andric       } else {
1829*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
18300b57cec5SDimitry Andric       }
1831349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
1832349cc55cSDimitry Andric           S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1833349cc55cSDimitry Andric           PointeeType, Info, Deduced,
1834349cc55cSDimitry Andric           TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass));
18350b57cec5SDimitry Andric     }
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric     //     T &
18380b57cec5SDimitry Andric     case Type::LValueReference: {
1839349cc55cSDimitry Andric       const auto *RP = P->castAs<LValueReferenceType>(),
1840349cc55cSDimitry Andric                  *RA = A->getAs<LValueReferenceType>();
1841349cc55cSDimitry Andric       if (!RA)
1842*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
18430b57cec5SDimitry Andric 
1844349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
1845349cc55cSDimitry Andric           S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1846349cc55cSDimitry Andric           Deduced, 0);
18470b57cec5SDimitry Andric     }
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric     //     T && [C++0x]
18500b57cec5SDimitry Andric     case Type::RValueReference: {
1851349cc55cSDimitry Andric       const auto *RP = P->castAs<RValueReferenceType>(),
1852349cc55cSDimitry Andric                  *RA = A->getAs<RValueReferenceType>();
1853349cc55cSDimitry Andric       if (!RA)
1854*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
18550b57cec5SDimitry Andric 
1856349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
1857349cc55cSDimitry Andric           S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1858349cc55cSDimitry Andric           Deduced, 0);
18590b57cec5SDimitry Andric     }
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric     //     T [] (implied, but not stated explicitly)
18620b57cec5SDimitry Andric     case Type::IncompleteArray: {
1863349cc55cSDimitry Andric       const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1864349cc55cSDimitry Andric       if (!IAA)
1865*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
18660b57cec5SDimitry Andric 
186706c3fb27SDimitry Andric       const auto *IAP = S.Context.getAsIncompleteArrayType(P);
186806c3fb27SDimitry Andric       assert(IAP && "Template parameter not of incomplete array type");
186906c3fb27SDimitry Andric 
1870349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
187106c3fb27SDimitry Andric           S, TemplateParams, IAP->getElementType(), IAA->getElementType(), Info,
187206c3fb27SDimitry Andric           Deduced, TDF & TDF_IgnoreQualifiers);
18730b57cec5SDimitry Andric     }
18740b57cec5SDimitry Andric 
18750b57cec5SDimitry Andric     //     T [integer-constant]
18760b57cec5SDimitry Andric     case Type::ConstantArray: {
1877349cc55cSDimitry Andric       const auto *CAA = S.Context.getAsConstantArrayType(A),
1878349cc55cSDimitry Andric                  *CAP = S.Context.getAsConstantArrayType(P);
1879349cc55cSDimitry Andric       assert(CAP);
1880349cc55cSDimitry Andric       if (!CAA || CAA->getSize() != CAP->getSize())
1881*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
18820b57cec5SDimitry Andric 
1883349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
1884349cc55cSDimitry Andric           S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1885349cc55cSDimitry Andric           Deduced, TDF & TDF_IgnoreQualifiers);
18860b57cec5SDimitry Andric     }
18870b57cec5SDimitry Andric 
18880b57cec5SDimitry Andric     //     type [i]
18890b57cec5SDimitry Andric     case Type::DependentSizedArray: {
1890349cc55cSDimitry Andric       const auto *AA = S.Context.getAsArrayType(A);
1891349cc55cSDimitry Andric       if (!AA)
1892*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
18930b57cec5SDimitry Andric 
18940b57cec5SDimitry Andric       // Check the element type of the arrays
1895349cc55cSDimitry Andric       const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1896349cc55cSDimitry Andric       assert(DAP);
1897349cc55cSDimitry Andric       if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1898349cc55cSDimitry Andric               S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1899*0fca6ea1SDimitry Andric               Info, Deduced, TDF & TDF_IgnoreQualifiers);
1900*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
19010b57cec5SDimitry Andric         return Result;
19020b57cec5SDimitry Andric 
19030b57cec5SDimitry Andric       // Determine the array bound is something we can deduce.
1904349cc55cSDimitry Andric       const NonTypeTemplateParmDecl *NTTP =
1905349cc55cSDimitry Andric           getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
19060b57cec5SDimitry Andric       if (!NTTP)
1907*0fca6ea1SDimitry Andric         return TemplateDeductionResult::Success;
19080b57cec5SDimitry Andric 
19090b57cec5SDimitry Andric       // We can perform template argument deduction for the given non-type
19100b57cec5SDimitry Andric       // template parameter.
19110b57cec5SDimitry Andric       assert(NTTP->getDepth() == Info.getDeducedDepth() &&
19120b57cec5SDimitry Andric              "saw non-type template parameter with wrong depth");
1913349cc55cSDimitry Andric       if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1914349cc55cSDimitry Andric         llvm::APSInt Size(CAA->getSize());
1915349cc55cSDimitry Andric         return DeduceNonTypeTemplateArgument(
1916349cc55cSDimitry Andric             S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1917349cc55cSDimitry Andric             /*ArrayBound=*/true, Info, Deduced);
19180b57cec5SDimitry Andric       }
1919349cc55cSDimitry Andric       if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1920349cc55cSDimitry Andric         if (DAA->getSizeExpr())
1921349cc55cSDimitry Andric           return DeduceNonTypeTemplateArgument(
1922349cc55cSDimitry Andric               S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced);
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric       // Incomplete type does not match a dependently-sized array type
1925*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
19260b57cec5SDimitry Andric     }
19270b57cec5SDimitry Andric 
19280b57cec5SDimitry Andric     //     type(*)(T)
19290b57cec5SDimitry Andric     //     T(*)()
19300b57cec5SDimitry Andric     //     T(*)(T)
19310b57cec5SDimitry Andric     case Type::FunctionProto: {
1932349cc55cSDimitry Andric       const auto *FPP = P->castAs<FunctionProtoType>(),
1933349cc55cSDimitry Andric                  *FPA = A->getAs<FunctionProtoType>();
1934349cc55cSDimitry Andric       if (!FPA)
1935*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
19360b57cec5SDimitry Andric 
1937349cc55cSDimitry Andric       if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1938349cc55cSDimitry Andric           FPP->getRefQualifier() != FPA->getRefQualifier() ||
1939349cc55cSDimitry Andric           FPP->isVariadic() != FPA->isVariadic())
1940*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
19410b57cec5SDimitry Andric 
19420b57cec5SDimitry Andric       // Check return types.
19430b57cec5SDimitry Andric       if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1944349cc55cSDimitry Andric               S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1945349cc55cSDimitry Andric               Info, Deduced, 0,
1946349cc55cSDimitry Andric               /*PartialOrdering=*/false,
1947*0fca6ea1SDimitry Andric               /*DeducedFromArrayBound=*/false);
1948*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
19490b57cec5SDimitry Andric         return Result;
19500b57cec5SDimitry Andric 
19510b57cec5SDimitry Andric       // Check parameter types.
19520b57cec5SDimitry Andric       if (auto Result = DeduceTemplateArguments(
1953349cc55cSDimitry Andric               S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(),
1954349cc55cSDimitry Andric               FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced,
1955*0fca6ea1SDimitry Andric               TDF & TDF_TopLevelParameterTypeList, PartialOrdering);
1956*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
19570b57cec5SDimitry Andric         return Result;
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric       if (TDF & TDF_AllowCompatibleFunctionType)
1960*0fca6ea1SDimitry Andric         return TemplateDeductionResult::Success;
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric       // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
19630b57cec5SDimitry Andric       // deducing through the noexcept-specifier if it's part of the canonical
19640b57cec5SDimitry Andric       // type. libstdc++ relies on this.
1965349cc55cSDimitry Andric       Expr *NoexceptExpr = FPP->getNoexceptExpr();
1966e8d8bef9SDimitry Andric       if (const NonTypeTemplateParmDecl *NTTP =
19670b57cec5SDimitry Andric               NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
19680b57cec5SDimitry Andric                            : nullptr) {
19690b57cec5SDimitry Andric         assert(NTTP->getDepth() == Info.getDeducedDepth() &&
19700b57cec5SDimitry Andric                "saw non-type template parameter with wrong depth");
19710b57cec5SDimitry Andric 
19720b57cec5SDimitry Andric         llvm::APSInt Noexcept(1);
1973349cc55cSDimitry Andric         switch (FPA->canThrow()) {
19740b57cec5SDimitry Andric         case CT_Cannot:
19750b57cec5SDimitry Andric           Noexcept = 1;
1976bdd1243dSDimitry Andric           [[fallthrough]];
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric         case CT_Can:
19790b57cec5SDimitry Andric           // We give E in noexcept(E) the "deduced from array bound" treatment.
19800b57cec5SDimitry Andric           // FIXME: Should we?
19810b57cec5SDimitry Andric           return DeduceNonTypeTemplateArgument(
19820b57cec5SDimitry Andric               S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1983349cc55cSDimitry Andric               /*DeducedFromArrayBound=*/true, Info, Deduced);
19840b57cec5SDimitry Andric 
19850b57cec5SDimitry Andric         case CT_Dependent:
1986349cc55cSDimitry Andric           if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
19870b57cec5SDimitry Andric             return DeduceNonTypeTemplateArgument(
19880b57cec5SDimitry Andric                 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
19890b57cec5SDimitry Andric           // Can't deduce anything from throw(T...).
19900b57cec5SDimitry Andric           break;
19910b57cec5SDimitry Andric         }
19920b57cec5SDimitry Andric       }
19930b57cec5SDimitry Andric       // FIXME: Detect non-deduced exception specification mismatches?
19940b57cec5SDimitry Andric       //
19950b57cec5SDimitry Andric       // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
19960b57cec5SDimitry Andric       // top-level differences in noexcept-specifications.
19970b57cec5SDimitry Andric 
1998*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
19990b57cec5SDimitry Andric     }
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric     case Type::InjectedClassName:
20020b57cec5SDimitry Andric       // Treat a template's injected-class-name as if the template
20030b57cec5SDimitry Andric       // specialization type had been used.
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric     //     template-name<T> (where template-name refers to a class template)
20060b57cec5SDimitry Andric     //     template-name<i>
20070b57cec5SDimitry Andric     //     TT<T>
20080b57cec5SDimitry Andric     //     TT<i>
20090b57cec5SDimitry Andric     //     TT<>
20100b57cec5SDimitry Andric     case Type::TemplateSpecialization: {
20110b57cec5SDimitry Andric       // When Arg cannot be a derived class, we can just try to deduce template
20120b57cec5SDimitry Andric       // arguments from the template-id.
2013349cc55cSDimitry Andric       if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
2014349cc55cSDimitry Andric         return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
20150b57cec5SDimitry Andric                                            Deduced);
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric       SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
20180b57cec5SDimitry Andric                                                           Deduced.end());
20190b57cec5SDimitry Andric 
2020349cc55cSDimitry Andric       auto Result =
2021349cc55cSDimitry Andric           DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, Deduced);
2022*0fca6ea1SDimitry Andric       if (Result == TemplateDeductionResult::Success)
20230b57cec5SDimitry Andric         return Result;
20240b57cec5SDimitry Andric 
20250b57cec5SDimitry Andric       // We cannot inspect base classes as part of deduction when the type
20260b57cec5SDimitry Andric       // is incomplete, so either instantiate any templates necessary to
20270b57cec5SDimitry Andric       // complete the type, or skip over it if it cannot be completed.
2028349cc55cSDimitry Andric       if (!S.isCompleteType(Info.getLocation(), A))
20290b57cec5SDimitry Andric         return Result;
20300b57cec5SDimitry Andric 
2031*0fca6ea1SDimitry Andric       if (getCanonicalRD(A)->isInvalidDecl())
2032*0fca6ea1SDimitry Andric         return Result;
2033*0fca6ea1SDimitry Andric 
20340b57cec5SDimitry Andric       // Reset the incorrectly deduced argument from above.
20350b57cec5SDimitry Andric       Deduced = DeducedOrig;
20360b57cec5SDimitry Andric 
2037e8d8bef9SDimitry Andric       // Check bases according to C++14 [temp.deduct.call] p4b3:
2038349cc55cSDimitry Andric       auto BaseResult = DeduceTemplateBases(S, getCanonicalRD(A),
2039349cc55cSDimitry Andric                                             TemplateParams, P, Info, Deduced);
2040*0fca6ea1SDimitry Andric       return BaseResult != TemplateDeductionResult::Invalid ? BaseResult
2041*0fca6ea1SDimitry Andric                                                             : Result;
20420b57cec5SDimitry Andric     }
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric     //     T type::*
20450b57cec5SDimitry Andric     //     T T::*
20460b57cec5SDimitry Andric     //     T (type::*)()
20470b57cec5SDimitry Andric     //     type (T::*)()
20480b57cec5SDimitry Andric     //     type (type::*)(T)
20490b57cec5SDimitry Andric     //     type (T::*)(T)
20500b57cec5SDimitry Andric     //     T (type::*)(T)
20510b57cec5SDimitry Andric     //     T (T::*)()
20520b57cec5SDimitry Andric     //     T (T::*)(T)
20530b57cec5SDimitry Andric     case Type::MemberPointer: {
2054349cc55cSDimitry Andric       const auto *MPP = P->castAs<MemberPointerType>(),
2055349cc55cSDimitry Andric                  *MPA = A->getAs<MemberPointerType>();
2056349cc55cSDimitry Andric       if (!MPA)
2057*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
20580b57cec5SDimitry Andric 
2059349cc55cSDimitry Andric       QualType PPT = MPP->getPointeeType();
2060349cc55cSDimitry Andric       if (PPT->isFunctionType())
20615f757f3fSDimitry Andric         S.adjustMemberFunctionCC(PPT, /*HasThisPointer=*/false,
20620b57cec5SDimitry Andric                                  /*IsCtorOrDtor=*/false, Info.getLocation());
2063349cc55cSDimitry Andric       QualType APT = MPA->getPointeeType();
2064349cc55cSDimitry Andric       if (APT->isFunctionType())
20655f757f3fSDimitry Andric         S.adjustMemberFunctionCC(APT, /*HasThisPointer=*/false,
20660b57cec5SDimitry Andric                                  /*IsCtorOrDtor=*/false, Info.getLocation());
20670b57cec5SDimitry Andric 
2068349cc55cSDimitry Andric       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
2069349cc55cSDimitry Andric       if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2070*0fca6ea1SDimitry Andric               S, TemplateParams, PPT, APT, Info, Deduced, SubTDF);
2071*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
20720b57cec5SDimitry Andric         return Result;
2073349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
2074349cc55cSDimitry Andric           S, TemplateParams, QualType(MPP->getClass(), 0),
2075349cc55cSDimitry Andric           QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
20760b57cec5SDimitry Andric     }
20770b57cec5SDimitry Andric 
20780b57cec5SDimitry Andric     //     (clang extension)
20790b57cec5SDimitry Andric     //
20800b57cec5SDimitry Andric     //     type(^)(T)
20810b57cec5SDimitry Andric     //     T(^)()
20820b57cec5SDimitry Andric     //     T(^)(T)
20830b57cec5SDimitry Andric     case Type::BlockPointer: {
2084349cc55cSDimitry Andric       const auto *BPP = P->castAs<BlockPointerType>(),
2085349cc55cSDimitry Andric                  *BPA = A->getAs<BlockPointerType>();
2086349cc55cSDimitry Andric       if (!BPA)
2087*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
2088349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
2089349cc55cSDimitry Andric           S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
2090349cc55cSDimitry Andric           Deduced, 0);
20910b57cec5SDimitry Andric     }
20920b57cec5SDimitry Andric 
20930b57cec5SDimitry Andric     //     (clang extension)
20940b57cec5SDimitry Andric     //
20950b57cec5SDimitry Andric     //     T __attribute__(((ext_vector_type(<integral constant>))))
20960b57cec5SDimitry Andric     case Type::ExtVector: {
2097349cc55cSDimitry Andric       const auto *VP = P->castAs<ExtVectorType>();
2098349cc55cSDimitry Andric       QualType ElementType;
2099349cc55cSDimitry Andric       if (const auto *VA = A->getAs<ExtVectorType>()) {
21000b57cec5SDimitry Andric         // Make sure that the vectors have the same number of elements.
2101349cc55cSDimitry Andric         if (VP->getNumElements() != VA->getNumElements())
2102*0fca6ea1SDimitry Andric           return TemplateDeductionResult::NonDeducedMismatch;
2103349cc55cSDimitry Andric         ElementType = VA->getElementType();
2104349cc55cSDimitry Andric       } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
21050b57cec5SDimitry Andric         // We can't check the number of elements, since the argument has a
21060b57cec5SDimitry Andric         // dependent number of elements. This can only occur during partial
21070b57cec5SDimitry Andric         // ordering.
2108349cc55cSDimitry Andric         ElementType = VA->getElementType();
2109349cc55cSDimitry Andric       } else {
2110*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
21110b57cec5SDimitry Andric       }
2112349cc55cSDimitry Andric       // Perform deduction on the element types.
2113349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
2114349cc55cSDimitry Andric           S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
2115349cc55cSDimitry Andric           TDF);
2116349cc55cSDimitry Andric     }
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric     case Type::DependentVector: {
2119349cc55cSDimitry Andric       const auto *VP = P->castAs<DependentVectorType>();
21200b57cec5SDimitry Andric 
2121349cc55cSDimitry Andric       if (const auto *VA = A->getAs<VectorType>()) {
21220b57cec5SDimitry Andric         // Perform deduction on the element types.
2123349cc55cSDimitry Andric         if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2124349cc55cSDimitry Andric                 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2125*0fca6ea1SDimitry Andric                 Info, Deduced, TDF);
2126*0fca6ea1SDimitry Andric             Result != TemplateDeductionResult::Success)
21270b57cec5SDimitry Andric           return Result;
21280b57cec5SDimitry Andric 
21290b57cec5SDimitry Andric         // Perform deduction on the vector size, if we can.
2130e8d8bef9SDimitry Andric         const NonTypeTemplateParmDecl *NTTP =
2131349cc55cSDimitry Andric             getDeducedParameterFromExpr(Info, VP->getSizeExpr());
21320b57cec5SDimitry Andric         if (!NTTP)
2133*0fca6ea1SDimitry Andric           return TemplateDeductionResult::Success;
21340b57cec5SDimitry Andric 
21350b57cec5SDimitry Andric         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2136349cc55cSDimitry Andric         ArgSize = VA->getNumElements();
21370b57cec5SDimitry Andric         // Note that we use the "array bound" rules here; just like in that
21380b57cec5SDimitry Andric         // case, we don't have any particular type for the vector size, but
21390b57cec5SDimitry Andric         // we can provide one if necessary.
21400b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
21410b57cec5SDimitry Andric                                              S.Context.UnsignedIntTy, true,
21420b57cec5SDimitry Andric                                              Info, Deduced);
21430b57cec5SDimitry Andric       }
21440b57cec5SDimitry Andric 
2145349cc55cSDimitry Andric       if (const auto *VA = A->getAs<DependentVectorType>()) {
21460b57cec5SDimitry Andric         // Perform deduction on the element types.
2147349cc55cSDimitry Andric         if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2148349cc55cSDimitry Andric                 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2149*0fca6ea1SDimitry Andric                 Info, Deduced, TDF);
2150*0fca6ea1SDimitry Andric             Result != TemplateDeductionResult::Success)
21510b57cec5SDimitry Andric           return Result;
21520b57cec5SDimitry Andric 
21530b57cec5SDimitry Andric         // Perform deduction on the vector size, if we can.
2154349cc55cSDimitry Andric         const NonTypeTemplateParmDecl *NTTP =
2155349cc55cSDimitry Andric             getDeducedParameterFromExpr(Info, VP->getSizeExpr());
21560b57cec5SDimitry Andric         if (!NTTP)
2157*0fca6ea1SDimitry Andric           return TemplateDeductionResult::Success;
21580b57cec5SDimitry Andric 
2159349cc55cSDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2160349cc55cSDimitry Andric                                              VA->getSizeExpr(), Info, Deduced);
21610b57cec5SDimitry Andric       }
21620b57cec5SDimitry Andric 
2163*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
21640b57cec5SDimitry Andric     }
21650b57cec5SDimitry Andric 
21660b57cec5SDimitry Andric     //     (clang extension)
21670b57cec5SDimitry Andric     //
21680b57cec5SDimitry Andric     //     T __attribute__(((ext_vector_type(N))))
21690b57cec5SDimitry Andric     case Type::DependentSizedExtVector: {
2170349cc55cSDimitry Andric       const auto *VP = P->castAs<DependentSizedExtVectorType>();
21710b57cec5SDimitry Andric 
2172349cc55cSDimitry Andric       if (const auto *VA = A->getAs<ExtVectorType>()) {
21730b57cec5SDimitry Andric         // Perform deduction on the element types.
2174349cc55cSDimitry Andric         if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2175349cc55cSDimitry Andric                 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2176*0fca6ea1SDimitry Andric                 Info, Deduced, TDF);
2177*0fca6ea1SDimitry Andric             Result != TemplateDeductionResult::Success)
21780b57cec5SDimitry Andric           return Result;
21790b57cec5SDimitry Andric 
21800b57cec5SDimitry Andric         // Perform deduction on the vector size, if we can.
2181e8d8bef9SDimitry Andric         const NonTypeTemplateParmDecl *NTTP =
2182349cc55cSDimitry Andric             getDeducedParameterFromExpr(Info, VP->getSizeExpr());
21830b57cec5SDimitry Andric         if (!NTTP)
2184*0fca6ea1SDimitry Andric           return TemplateDeductionResult::Success;
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2187349cc55cSDimitry Andric         ArgSize = VA->getNumElements();
21880b57cec5SDimitry Andric         // Note that we use the "array bound" rules here; just like in that
21890b57cec5SDimitry Andric         // case, we don't have any particular type for the vector size, but
21900b57cec5SDimitry Andric         // we can provide one if necessary.
21910b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
21920b57cec5SDimitry Andric                                              S.Context.IntTy, true, Info,
21930b57cec5SDimitry Andric                                              Deduced);
21940b57cec5SDimitry Andric       }
21950b57cec5SDimitry Andric 
2196349cc55cSDimitry Andric       if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
21970b57cec5SDimitry Andric         // Perform deduction on the element types.
2198349cc55cSDimitry Andric         if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2199349cc55cSDimitry Andric                 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2200*0fca6ea1SDimitry Andric                 Info, Deduced, TDF);
2201*0fca6ea1SDimitry Andric             Result != TemplateDeductionResult::Success)
22020b57cec5SDimitry Andric           return Result;
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric         // Perform deduction on the vector size, if we can.
2205e8d8bef9SDimitry Andric         const NonTypeTemplateParmDecl *NTTP =
2206349cc55cSDimitry Andric             getDeducedParameterFromExpr(Info, VP->getSizeExpr());
22070b57cec5SDimitry Andric         if (!NTTP)
2208*0fca6ea1SDimitry Andric           return TemplateDeductionResult::Success;
22090b57cec5SDimitry Andric 
22100b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2211349cc55cSDimitry Andric                                              VA->getSizeExpr(), Info, Deduced);
22120b57cec5SDimitry Andric       }
22130b57cec5SDimitry Andric 
2214*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
22150b57cec5SDimitry Andric     }
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric     //     (clang extension)
22180b57cec5SDimitry Andric     //
22195ffd83dbSDimitry Andric     //     T __attribute__((matrix_type(<integral constant>,
22205ffd83dbSDimitry Andric     //                                  <integral constant>)))
22215ffd83dbSDimitry Andric     case Type::ConstantMatrix: {
2222349cc55cSDimitry Andric       const auto *MP = P->castAs<ConstantMatrixType>(),
2223349cc55cSDimitry Andric                  *MA = A->getAs<ConstantMatrixType>();
2224349cc55cSDimitry Andric       if (!MA)
2225*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
22265ffd83dbSDimitry Andric 
22275ffd83dbSDimitry Andric       // Check that the dimensions are the same
2228349cc55cSDimitry Andric       if (MP->getNumRows() != MA->getNumRows() ||
2229349cc55cSDimitry Andric           MP->getNumColumns() != MA->getNumColumns()) {
2230*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
22315ffd83dbSDimitry Andric       }
22325ffd83dbSDimitry Andric       // Perform deduction on element types.
22335ffd83dbSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
2234349cc55cSDimitry Andric           S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2235349cc55cSDimitry Andric           Deduced, TDF);
22365ffd83dbSDimitry Andric     }
22375ffd83dbSDimitry Andric 
22385ffd83dbSDimitry Andric     case Type::DependentSizedMatrix: {
2239349cc55cSDimitry Andric       const auto *MP = P->castAs<DependentSizedMatrixType>();
2240349cc55cSDimitry Andric       const auto *MA = A->getAs<MatrixType>();
2241349cc55cSDimitry Andric       if (!MA)
2242*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
22435ffd83dbSDimitry Andric 
22445ffd83dbSDimitry Andric       // Check the element type of the matrixes.
2245349cc55cSDimitry Andric       if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2246349cc55cSDimitry Andric               S, TemplateParams, MP->getElementType(), MA->getElementType(),
2247*0fca6ea1SDimitry Andric               Info, Deduced, TDF);
2248*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
22495ffd83dbSDimitry Andric         return Result;
22505ffd83dbSDimitry Andric 
22515ffd83dbSDimitry Andric       // Try to deduce a matrix dimension.
22525ffd83dbSDimitry Andric       auto DeduceMatrixArg =
22535ffd83dbSDimitry Andric           [&S, &Info, &Deduced, &TemplateParams](
2254349cc55cSDimitry Andric               Expr *ParamExpr, const MatrixType *A,
22555ffd83dbSDimitry Andric               unsigned (ConstantMatrixType::*GetArgDimension)() const,
22565ffd83dbSDimitry Andric               Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2257349cc55cSDimitry Andric             const auto *ACM = dyn_cast<ConstantMatrixType>(A);
2258349cc55cSDimitry Andric             const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
22595ffd83dbSDimitry Andric             if (!ParamExpr->isValueDependent()) {
2260bdd1243dSDimitry Andric               std::optional<llvm::APSInt> ParamConst =
2261e8d8bef9SDimitry Andric                   ParamExpr->getIntegerConstantExpr(S.Context);
2262e8d8bef9SDimitry Andric               if (!ParamConst)
2263*0fca6ea1SDimitry Andric                 return TemplateDeductionResult::NonDeducedMismatch;
22645ffd83dbSDimitry Andric 
2265349cc55cSDimitry Andric               if (ACM) {
2266349cc55cSDimitry Andric                 if ((ACM->*GetArgDimension)() == *ParamConst)
2267*0fca6ea1SDimitry Andric                   return TemplateDeductionResult::Success;
2268*0fca6ea1SDimitry Andric                 return TemplateDeductionResult::NonDeducedMismatch;
22695ffd83dbSDimitry Andric               }
22705ffd83dbSDimitry Andric 
2271349cc55cSDimitry Andric               Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2272bdd1243dSDimitry Andric               if (std::optional<llvm::APSInt> ArgConst =
2273e8d8bef9SDimitry Andric                       ArgExpr->getIntegerConstantExpr(S.Context))
2274e8d8bef9SDimitry Andric                 if (*ArgConst == *ParamConst)
2275*0fca6ea1SDimitry Andric                   return TemplateDeductionResult::Success;
2276*0fca6ea1SDimitry Andric               return TemplateDeductionResult::NonDeducedMismatch;
22775ffd83dbSDimitry Andric             }
22785ffd83dbSDimitry Andric 
2279e8d8bef9SDimitry Andric             const NonTypeTemplateParmDecl *NTTP =
22805ffd83dbSDimitry Andric                 getDeducedParameterFromExpr(Info, ParamExpr);
22815ffd83dbSDimitry Andric             if (!NTTP)
2282*0fca6ea1SDimitry Andric               return TemplateDeductionResult::Success;
22835ffd83dbSDimitry Andric 
2284349cc55cSDimitry Andric             if (ACM) {
22855ffd83dbSDimitry Andric               llvm::APSInt ArgConst(
22865ffd83dbSDimitry Andric                   S.Context.getTypeSize(S.Context.getSizeType()));
2287349cc55cSDimitry Andric               ArgConst = (ACM->*GetArgDimension)();
22885ffd83dbSDimitry Andric               return DeduceNonTypeTemplateArgument(
22895ffd83dbSDimitry Andric                   S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
22905ffd83dbSDimitry Andric                   /*ArrayBound=*/true, Info, Deduced);
22915ffd83dbSDimitry Andric             }
22925ffd83dbSDimitry Andric 
2293349cc55cSDimitry Andric             return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2294349cc55cSDimitry Andric                                                  (ADM->*GetArgDimensionExpr)(),
22955ffd83dbSDimitry Andric                                                  Info, Deduced);
22965ffd83dbSDimitry Andric           };
22975ffd83dbSDimitry Andric 
2298349cc55cSDimitry Andric       if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
22995ffd83dbSDimitry Andric                                         &ConstantMatrixType::getNumRows,
2300*0fca6ea1SDimitry Andric                                         &DependentSizedMatrixType::getRowExpr);
2301*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
23025ffd83dbSDimitry Andric         return Result;
23035ffd83dbSDimitry Andric 
2304349cc55cSDimitry Andric       return DeduceMatrixArg(MP->getColumnExpr(), MA,
23055ffd83dbSDimitry Andric                              &ConstantMatrixType::getNumColumns,
23065ffd83dbSDimitry Andric                              &DependentSizedMatrixType::getColumnExpr);
23075ffd83dbSDimitry Andric     }
23085ffd83dbSDimitry Andric 
23095ffd83dbSDimitry Andric     //     (clang extension)
23105ffd83dbSDimitry Andric     //
23110b57cec5SDimitry Andric     //     T __attribute__(((address_space(N))))
23120b57cec5SDimitry Andric     case Type::DependentAddressSpace: {
2313349cc55cSDimitry Andric       const auto *ASP = P->castAs<DependentAddressSpaceType>();
23140b57cec5SDimitry Andric 
2315349cc55cSDimitry Andric       if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
23160b57cec5SDimitry Andric         // Perform deduction on the pointer type.
2317349cc55cSDimitry Andric         if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2318349cc55cSDimitry Andric                 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2319*0fca6ea1SDimitry Andric                 Info, Deduced, TDF);
2320*0fca6ea1SDimitry Andric             Result != TemplateDeductionResult::Success)
23210b57cec5SDimitry Andric           return Result;
23220b57cec5SDimitry Andric 
23230b57cec5SDimitry Andric         // Perform deduction on the address space, if we can.
2324349cc55cSDimitry Andric         const NonTypeTemplateParmDecl *NTTP =
2325349cc55cSDimitry Andric             getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
23260b57cec5SDimitry Andric         if (!NTTP)
2327*0fca6ea1SDimitry Andric           return TemplateDeductionResult::Success;
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(
2330349cc55cSDimitry Andric             S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
23310b57cec5SDimitry Andric       }
23320b57cec5SDimitry Andric 
2333349cc55cSDimitry Andric       if (isTargetAddressSpace(A.getAddressSpace())) {
23340b57cec5SDimitry Andric         llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
23350b57cec5SDimitry Andric                                      false);
2336349cc55cSDimitry Andric         ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
23370b57cec5SDimitry Andric 
23380b57cec5SDimitry Andric         // Perform deduction on the pointer types.
2339349cc55cSDimitry Andric         if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2340349cc55cSDimitry Andric                 S, TemplateParams, ASP->getPointeeType(),
2341*0fca6ea1SDimitry Andric                 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF);
2342*0fca6ea1SDimitry Andric             Result != TemplateDeductionResult::Success)
23430b57cec5SDimitry Andric           return Result;
23440b57cec5SDimitry Andric 
23450b57cec5SDimitry Andric         // Perform deduction on the address space, if we can.
2346349cc55cSDimitry Andric         const NonTypeTemplateParmDecl *NTTP =
2347349cc55cSDimitry Andric             getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
23480b57cec5SDimitry Andric         if (!NTTP)
2349*0fca6ea1SDimitry Andric           return TemplateDeductionResult::Success;
23500b57cec5SDimitry Andric 
23510b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
23520b57cec5SDimitry Andric                                              ArgAddressSpace, S.Context.IntTy,
23530b57cec5SDimitry Andric                                              true, Info, Deduced);
23540b57cec5SDimitry Andric       }
23550b57cec5SDimitry Andric 
2356*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
23570b57cec5SDimitry Andric     }
23580eae32dcSDimitry Andric     case Type::DependentBitInt: {
23590eae32dcSDimitry Andric       const auto *IP = P->castAs<DependentBitIntType>();
23605ffd83dbSDimitry Andric 
23610eae32dcSDimitry Andric       if (const auto *IA = A->getAs<BitIntType>()) {
2362349cc55cSDimitry Andric         if (IP->isUnsigned() != IA->isUnsigned())
2363*0fca6ea1SDimitry Andric           return TemplateDeductionResult::NonDeducedMismatch;
23645ffd83dbSDimitry Andric 
2365e8d8bef9SDimitry Andric         const NonTypeTemplateParmDecl *NTTP =
2366349cc55cSDimitry Andric             getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
23675ffd83dbSDimitry Andric         if (!NTTP)
2368*0fca6ea1SDimitry Andric           return TemplateDeductionResult::Success;
23695ffd83dbSDimitry Andric 
23705ffd83dbSDimitry Andric         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2371349cc55cSDimitry Andric         ArgSize = IA->getNumBits();
23725ffd83dbSDimitry Andric 
23735ffd83dbSDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
23745ffd83dbSDimitry Andric                                              S.Context.IntTy, true, Info,
23755ffd83dbSDimitry Andric                                              Deduced);
23765ffd83dbSDimitry Andric       }
23775ffd83dbSDimitry Andric 
23780eae32dcSDimitry Andric       if (const auto *IA = A->getAs<DependentBitIntType>()) {
2379349cc55cSDimitry Andric         if (IP->isUnsigned() != IA->isUnsigned())
2380*0fca6ea1SDimitry Andric           return TemplateDeductionResult::NonDeducedMismatch;
2381*0fca6ea1SDimitry Andric         return TemplateDeductionResult::Success;
23825ffd83dbSDimitry Andric       }
2383349cc55cSDimitry Andric 
2384*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
23855ffd83dbSDimitry Andric     }
23860b57cec5SDimitry Andric 
23870b57cec5SDimitry Andric     case Type::TypeOfExpr:
23880b57cec5SDimitry Andric     case Type::TypeOf:
23890b57cec5SDimitry Andric     case Type::DependentName:
23900b57cec5SDimitry Andric     case Type::UnresolvedUsing:
23910b57cec5SDimitry Andric     case Type::Decltype:
23920b57cec5SDimitry Andric     case Type::UnaryTransform:
23930b57cec5SDimitry Andric     case Type::DeducedTemplateSpecialization:
23940b57cec5SDimitry Andric     case Type::DependentTemplateSpecialization:
23950b57cec5SDimitry Andric     case Type::PackExpansion:
23960b57cec5SDimitry Andric     case Type::Pipe:
2397*0fca6ea1SDimitry Andric     case Type::ArrayParameter:
23980b57cec5SDimitry Andric       // No template argument deduction for these types
2399*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
2400*0fca6ea1SDimitry Andric 
2401*0fca6ea1SDimitry Andric     case Type::PackIndexing: {
2402*0fca6ea1SDimitry Andric       const PackIndexingType *PIT = P->getAs<PackIndexingType>();
2403*0fca6ea1SDimitry Andric       if (PIT->hasSelectedType()) {
2404*0fca6ea1SDimitry Andric         return DeduceTemplateArgumentsByTypeMatch(
2405*0fca6ea1SDimitry Andric             S, TemplateParams, PIT->getSelectedType(), A, Info, Deduced, TDF);
2406*0fca6ea1SDimitry Andric       }
2407*0fca6ea1SDimitry Andric       return TemplateDeductionResult::IncompletePack;
2408*0fca6ea1SDimitry Andric     }
24090b57cec5SDimitry Andric     }
24100b57cec5SDimitry Andric 
24110b57cec5SDimitry Andric   llvm_unreachable("Invalid Type Class!");
24120b57cec5SDimitry Andric }
24130b57cec5SDimitry Andric 
2414*0fca6ea1SDimitry Andric static TemplateDeductionResult
DeduceTemplateArguments(Sema & S,TemplateParameterList * TemplateParams,const TemplateArgument & P,TemplateArgument A,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced)2415349cc55cSDimitry Andric DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2416349cc55cSDimitry Andric                         const TemplateArgument &P, TemplateArgument A,
24170b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
24180b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
24190b57cec5SDimitry Andric   // If the template argument is a pack expansion, perform template argument
24200b57cec5SDimitry Andric   // deduction against the pattern of that expansion. This only occurs during
24210b57cec5SDimitry Andric   // partial ordering.
2422349cc55cSDimitry Andric   if (A.isPackExpansion())
2423349cc55cSDimitry Andric     A = A.getPackExpansionPattern();
24240b57cec5SDimitry Andric 
2425349cc55cSDimitry Andric   switch (P.getKind()) {
24260b57cec5SDimitry Andric   case TemplateArgument::Null:
24270b57cec5SDimitry Andric     llvm_unreachable("Null template argument in parameter list");
24280b57cec5SDimitry Andric 
24290b57cec5SDimitry Andric   case TemplateArgument::Type:
2430349cc55cSDimitry Andric     if (A.getKind() == TemplateArgument::Type)
2431349cc55cSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
2432349cc55cSDimitry Andric           S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0);
2433349cc55cSDimitry Andric     Info.FirstArg = P;
2434349cc55cSDimitry Andric     Info.SecondArg = A;
2435*0fca6ea1SDimitry Andric     return TemplateDeductionResult::NonDeducedMismatch;
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric   case TemplateArgument::Template:
2438349cc55cSDimitry Andric     if (A.getKind() == TemplateArgument::Template)
2439349cc55cSDimitry Andric       return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(),
2440*0fca6ea1SDimitry Andric                                      A.getAsTemplate(), Info,
2441*0fca6ea1SDimitry Andric                                      /*DefaultArguments=*/{}, Deduced);
2442349cc55cSDimitry Andric     Info.FirstArg = P;
2443349cc55cSDimitry Andric     Info.SecondArg = A;
2444*0fca6ea1SDimitry Andric     return TemplateDeductionResult::NonDeducedMismatch;
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric   case TemplateArgument::TemplateExpansion:
24470b57cec5SDimitry Andric     llvm_unreachable("caller should handle pack expansions");
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric   case TemplateArgument::Declaration:
2450349cc55cSDimitry Andric     if (A.getKind() == TemplateArgument::Declaration &&
2451349cc55cSDimitry Andric         isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2452*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
24530b57cec5SDimitry Andric 
2454349cc55cSDimitry Andric     Info.FirstArg = P;
2455349cc55cSDimitry Andric     Info.SecondArg = A;
2456*0fca6ea1SDimitry Andric     return TemplateDeductionResult::NonDeducedMismatch;
24570b57cec5SDimitry Andric 
24580b57cec5SDimitry Andric   case TemplateArgument::NullPtr:
2459349cc55cSDimitry Andric     if (A.getKind() == TemplateArgument::NullPtr &&
2460349cc55cSDimitry Andric         S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2461*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
24620b57cec5SDimitry Andric 
2463349cc55cSDimitry Andric     Info.FirstArg = P;
2464349cc55cSDimitry Andric     Info.SecondArg = A;
2465*0fca6ea1SDimitry Andric     return TemplateDeductionResult::NonDeducedMismatch;
24660b57cec5SDimitry Andric 
24670b57cec5SDimitry Andric   case TemplateArgument::Integral:
2468349cc55cSDimitry Andric     if (A.getKind() == TemplateArgument::Integral) {
2469349cc55cSDimitry Andric       if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2470*0fca6ea1SDimitry Andric         return TemplateDeductionResult::Success;
24710b57cec5SDimitry Andric     }
2472349cc55cSDimitry Andric     Info.FirstArg = P;
2473349cc55cSDimitry Andric     Info.SecondArg = A;
2474*0fca6ea1SDimitry Andric     return TemplateDeductionResult::NonDeducedMismatch;
24750b57cec5SDimitry Andric 
24767a6dacacSDimitry Andric   case TemplateArgument::StructuralValue:
24777a6dacacSDimitry Andric     if (A.getKind() == TemplateArgument::StructuralValue &&
24787a6dacacSDimitry Andric         A.structurallyEquals(P))
2479*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
24800b57cec5SDimitry Andric 
2481349cc55cSDimitry Andric     Info.FirstArg = P;
2482349cc55cSDimitry Andric     Info.SecondArg = A;
2483*0fca6ea1SDimitry Andric     return TemplateDeductionResult::NonDeducedMismatch;
24847a6dacacSDimitry Andric 
24857a6dacacSDimitry Andric   case TemplateArgument::Expression:
24867a6dacacSDimitry Andric     if (const NonTypeTemplateParmDecl *NTTP =
24877a6dacacSDimitry Andric             getDeducedParameterFromExpr(Info, P.getAsExpr())) {
24887a6dacacSDimitry Andric       switch (A.getKind()) {
24897a6dacacSDimitry Andric       case TemplateArgument::Integral:
24907a6dacacSDimitry Andric       case TemplateArgument::Expression:
24917a6dacacSDimitry Andric       case TemplateArgument::StructuralValue:
24927a6dacacSDimitry Andric         return DeduceNonTypeTemplateArgument(
24937a6dacacSDimitry Andric             S, TemplateParams, NTTP, DeducedTemplateArgument(A),
24947a6dacacSDimitry Andric             A.getNonTypeTemplateArgumentType(), Info, Deduced);
24957a6dacacSDimitry Andric 
24967a6dacacSDimitry Andric       case TemplateArgument::NullPtr:
24977a6dacacSDimitry Andric         return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
24987a6dacacSDimitry Andric                                              A.getNullPtrType(), Info, Deduced);
24997a6dacacSDimitry Andric 
25007a6dacacSDimitry Andric       case TemplateArgument::Declaration:
25017a6dacacSDimitry Andric         return DeduceNonTypeTemplateArgument(
25027a6dacacSDimitry Andric             S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
25037a6dacacSDimitry Andric             Info, Deduced);
25047a6dacacSDimitry Andric 
25057a6dacacSDimitry Andric       case TemplateArgument::Null:
25067a6dacacSDimitry Andric       case TemplateArgument::Type:
25077a6dacacSDimitry Andric       case TemplateArgument::Template:
25087a6dacacSDimitry Andric       case TemplateArgument::TemplateExpansion:
25097a6dacacSDimitry Andric       case TemplateArgument::Pack:
25107a6dacacSDimitry Andric         Info.FirstArg = P;
25117a6dacacSDimitry Andric         Info.SecondArg = A;
2512*0fca6ea1SDimitry Andric         return TemplateDeductionResult::NonDeducedMismatch;
25137a6dacacSDimitry Andric       }
25147a6dacacSDimitry Andric       llvm_unreachable("Unknown template argument kind");
25150b57cec5SDimitry Andric     }
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric     // Can't deduce anything, but that's okay.
2518*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
25190b57cec5SDimitry Andric   case TemplateArgument::Pack:
25200b57cec5SDimitry Andric     llvm_unreachable("Argument packs should be expanded by the caller!");
25210b57cec5SDimitry Andric   }
25220b57cec5SDimitry Andric 
25230b57cec5SDimitry Andric   llvm_unreachable("Invalid TemplateArgument Kind!");
25240b57cec5SDimitry Andric }
25250b57cec5SDimitry Andric 
25260b57cec5SDimitry Andric /// Determine whether there is a template argument to be used for
25270b57cec5SDimitry Andric /// deduction.
25280b57cec5SDimitry Andric ///
25290b57cec5SDimitry Andric /// This routine "expands" argument packs in-place, overriding its input
25300b57cec5SDimitry Andric /// parameters so that \c Args[ArgIdx] will be the available template argument.
25310b57cec5SDimitry Andric ///
25320b57cec5SDimitry Andric /// \returns true if there is another template argument (which will be at
25330b57cec5SDimitry Andric /// \c Args[ArgIdx]), false otherwise.
hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> & Args,unsigned & ArgIdx)25340b57cec5SDimitry Andric static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
25350b57cec5SDimitry Andric                                             unsigned &ArgIdx) {
25360b57cec5SDimitry Andric   if (ArgIdx == Args.size())
25370b57cec5SDimitry Andric     return false;
25380b57cec5SDimitry Andric 
25390b57cec5SDimitry Andric   const TemplateArgument &Arg = Args[ArgIdx];
25400b57cec5SDimitry Andric   if (Arg.getKind() != TemplateArgument::Pack)
25410b57cec5SDimitry Andric     return true;
25420b57cec5SDimitry Andric 
25430b57cec5SDimitry Andric   assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
25440b57cec5SDimitry Andric   Args = Arg.pack_elements();
25450b57cec5SDimitry Andric   ArgIdx = 0;
25460b57cec5SDimitry Andric   return ArgIdx < Args.size();
25470b57cec5SDimitry Andric }
25480b57cec5SDimitry Andric 
25490b57cec5SDimitry Andric /// Determine whether the given set of template arguments has a pack
25500b57cec5SDimitry Andric /// expansion that is not the last template argument.
hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args)25510b57cec5SDimitry Andric static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
25520b57cec5SDimitry Andric   bool FoundPackExpansion = false;
25530b57cec5SDimitry Andric   for (const auto &A : Args) {
25540b57cec5SDimitry Andric     if (FoundPackExpansion)
25550b57cec5SDimitry Andric       return true;
25560b57cec5SDimitry Andric 
25570b57cec5SDimitry Andric     if (A.getKind() == TemplateArgument::Pack)
25580b57cec5SDimitry Andric       return hasPackExpansionBeforeEnd(A.pack_elements());
25590b57cec5SDimitry Andric 
25600b57cec5SDimitry Andric     // FIXME: If this is a fixed-arity pack expansion from an outer level of
25610b57cec5SDimitry Andric     // templates, it should not be treated as a pack expansion.
25620b57cec5SDimitry Andric     if (A.isPackExpansion())
25630b57cec5SDimitry Andric       FoundPackExpansion = true;
25640b57cec5SDimitry Andric   }
25650b57cec5SDimitry Andric 
25660b57cec5SDimitry Andric   return false;
25670b57cec5SDimitry Andric }
25680b57cec5SDimitry Andric 
2569*0fca6ea1SDimitry Andric static TemplateDeductionResult
DeduceTemplateArguments(Sema & S,TemplateParameterList * TemplateParams,ArrayRef<TemplateArgument> Ps,ArrayRef<TemplateArgument> As,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced,bool NumberOfArgumentsMustMatch,PackFold PackFold)25700b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2571349cc55cSDimitry Andric                         ArrayRef<TemplateArgument> Ps,
2572349cc55cSDimitry Andric                         ArrayRef<TemplateArgument> As,
25730b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
25740b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2575*0fca6ea1SDimitry Andric                         bool NumberOfArgumentsMustMatch, PackFold PackFold) {
2576*0fca6ea1SDimitry Andric   if (PackFold == PackFold::ArgumentToParameter)
2577*0fca6ea1SDimitry Andric     std::swap(Ps, As);
25780b57cec5SDimitry Andric   // C++0x [temp.deduct.type]p9:
25790b57cec5SDimitry Andric   //   If the template argument list of P contains a pack expansion that is not
25800b57cec5SDimitry Andric   //   the last template argument, the entire template argument list is a
25810b57cec5SDimitry Andric   //   non-deduced context.
2582349cc55cSDimitry Andric   if (hasPackExpansionBeforeEnd(Ps))
2583*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
25840b57cec5SDimitry Andric 
25850b57cec5SDimitry Andric   // C++0x [temp.deduct.type]p9:
25860b57cec5SDimitry Andric   //   If P has a form that contains <T> or <i>, then each argument Pi of the
25870b57cec5SDimitry Andric   //   respective template argument list P is compared with the corresponding
25880b57cec5SDimitry Andric   //   argument Ai of the corresponding template argument list of A.
25890b57cec5SDimitry Andric   unsigned ArgIdx = 0, ParamIdx = 0;
2590349cc55cSDimitry Andric   for (; hasTemplateArgumentForDeduction(Ps, ParamIdx); ++ParamIdx) {
2591349cc55cSDimitry Andric     const TemplateArgument &P = Ps[ParamIdx];
2592349cc55cSDimitry Andric     if (!P.isPackExpansion()) {
25930b57cec5SDimitry Andric       // The simple case: deduce template arguments by matching Pi and Ai.
25940b57cec5SDimitry Andric 
25950b57cec5SDimitry Andric       // Check whether we have enough arguments.
2596349cc55cSDimitry Andric       if (!hasTemplateArgumentForDeduction(As, ArgIdx))
25970b57cec5SDimitry Andric         return NumberOfArgumentsMustMatch
2598*0fca6ea1SDimitry Andric                    ? TemplateDeductionResult::MiscellaneousDeductionFailure
2599*0fca6ea1SDimitry Andric                    : TemplateDeductionResult::Success;
26000b57cec5SDimitry Andric 
26010b57cec5SDimitry Andric       // C++1z [temp.deduct.type]p9:
26020b57cec5SDimitry Andric       //   During partial ordering, if Ai was originally a pack expansion [and]
26030b57cec5SDimitry Andric       //   Pi is not a pack expansion, template argument deduction fails.
2604349cc55cSDimitry Andric       if (As[ArgIdx].isPackExpansion())
2605*0fca6ea1SDimitry Andric         return TemplateDeductionResult::MiscellaneousDeductionFailure;
26060b57cec5SDimitry Andric 
26070b57cec5SDimitry Andric       // Perform deduction for this Pi/Ai pair.
2608*0fca6ea1SDimitry Andric       TemplateArgument Pi = P, Ai = As[ArgIdx];
2609*0fca6ea1SDimitry Andric       if (PackFold == PackFold::ArgumentToParameter)
2610*0fca6ea1SDimitry Andric         std::swap(Pi, Ai);
2611*0fca6ea1SDimitry Andric       if (auto Result =
2612*0fca6ea1SDimitry Andric               DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info, Deduced);
2613*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
26140b57cec5SDimitry Andric         return Result;
26150b57cec5SDimitry Andric 
26160b57cec5SDimitry Andric       // Move to the next argument.
26170b57cec5SDimitry Andric       ++ArgIdx;
26180b57cec5SDimitry Andric       continue;
26190b57cec5SDimitry Andric     }
26200b57cec5SDimitry Andric 
26210b57cec5SDimitry Andric     // The parameter is a pack expansion.
26220b57cec5SDimitry Andric 
26230b57cec5SDimitry Andric     // C++0x [temp.deduct.type]p9:
26240b57cec5SDimitry Andric     //   If Pi is a pack expansion, then the pattern of Pi is compared with
26250b57cec5SDimitry Andric     //   each remaining argument in the template argument list of A. Each
26260b57cec5SDimitry Andric     //   comparison deduces template arguments for subsequent positions in the
26270b57cec5SDimitry Andric     //   template parameter packs expanded by Pi.
2628349cc55cSDimitry Andric     TemplateArgument Pattern = P.getPackExpansionPattern();
26290b57cec5SDimitry Andric 
26300b57cec5SDimitry Andric     // Prepare to deduce the packs within the pattern.
26310b57cec5SDimitry Andric     PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
26320b57cec5SDimitry Andric 
26330b57cec5SDimitry Andric     // Keep track of the deduced template arguments for each parameter pack
26340b57cec5SDimitry Andric     // expanded by this pack expansion (the outer index) and for each
26350b57cec5SDimitry Andric     // template argument (the inner SmallVectors).
2636349cc55cSDimitry Andric     for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
26370b57cec5SDimitry Andric            PackScope.hasNextElement();
26380b57cec5SDimitry Andric          ++ArgIdx) {
2639*0fca6ea1SDimitry Andric       TemplateArgument Pi = Pattern, Ai = As[ArgIdx];
2640*0fca6ea1SDimitry Andric       if (PackFold == PackFold::ArgumentToParameter)
2641*0fca6ea1SDimitry Andric         std::swap(Pi, Ai);
26420b57cec5SDimitry Andric       // Deduce template arguments from the pattern.
2643*0fca6ea1SDimitry Andric       if (auto Result =
2644*0fca6ea1SDimitry Andric               DeduceTemplateArguments(S, TemplateParams, Pi, Ai, Info, Deduced);
2645*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
26460b57cec5SDimitry Andric         return Result;
26470b57cec5SDimitry Andric 
26480b57cec5SDimitry Andric       PackScope.nextPackElement();
26490b57cec5SDimitry Andric     }
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric     // Build argument packs for each of the parameter packs expanded by this
26520b57cec5SDimitry Andric     // pack expansion.
2653*0fca6ea1SDimitry Andric     if (auto Result = PackScope.finish();
2654*0fca6ea1SDimitry Andric         Result != TemplateDeductionResult::Success)
26550b57cec5SDimitry Andric       return Result;
26560b57cec5SDimitry Andric   }
26570b57cec5SDimitry Andric 
2658*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
26590b57cec5SDimitry Andric }
26600b57cec5SDimitry Andric 
DeduceTemplateArguments(TemplateParameterList * TemplateParams,ArrayRef<TemplateArgument> Ps,ArrayRef<TemplateArgument> As,sema::TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced,bool NumberOfArgumentsMustMatch)2661*0fca6ea1SDimitry Andric TemplateDeductionResult Sema::DeduceTemplateArguments(
2662*0fca6ea1SDimitry Andric     TemplateParameterList *TemplateParams, ArrayRef<TemplateArgument> Ps,
2663*0fca6ea1SDimitry Andric     ArrayRef<TemplateArgument> As, sema::TemplateDeductionInfo &Info,
2664*0fca6ea1SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2665*0fca6ea1SDimitry Andric     bool NumberOfArgumentsMustMatch) {
2666*0fca6ea1SDimitry Andric   return ::DeduceTemplateArguments(*this, TemplateParams, Ps, As, Info, Deduced,
2667*0fca6ea1SDimitry Andric                                    NumberOfArgumentsMustMatch);
26680b57cec5SDimitry Andric }
26690b57cec5SDimitry Andric 
26700b57cec5SDimitry Andric /// Determine whether two template arguments are the same.
isSameTemplateArg(ASTContext & Context,TemplateArgument X,const TemplateArgument & Y,bool PartialOrdering,bool PackExpansionMatchesPack=false)26710b57cec5SDimitry Andric static bool isSameTemplateArg(ASTContext &Context,
26720b57cec5SDimitry Andric                               TemplateArgument X,
26730b57cec5SDimitry Andric                               const TemplateArgument &Y,
2674bdd1243dSDimitry Andric                               bool PartialOrdering,
26750b57cec5SDimitry Andric                               bool PackExpansionMatchesPack = false) {
26760b57cec5SDimitry Andric   // If we're checking deduced arguments (X) against original arguments (Y),
26770b57cec5SDimitry Andric   // we will have flattened packs to non-expansions in X.
26780b57cec5SDimitry Andric   if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
26790b57cec5SDimitry Andric     X = X.getPackExpansionPattern();
26800b57cec5SDimitry Andric 
26810b57cec5SDimitry Andric   if (X.getKind() != Y.getKind())
26820b57cec5SDimitry Andric     return false;
26830b57cec5SDimitry Andric 
26840b57cec5SDimitry Andric   switch (X.getKind()) {
26850b57cec5SDimitry Andric     case TemplateArgument::Null:
26860b57cec5SDimitry Andric       llvm_unreachable("Comparing NULL template argument");
26870b57cec5SDimitry Andric 
26880b57cec5SDimitry Andric     case TemplateArgument::Type:
26890b57cec5SDimitry Andric       return Context.getCanonicalType(X.getAsType()) ==
26900b57cec5SDimitry Andric              Context.getCanonicalType(Y.getAsType());
26910b57cec5SDimitry Andric 
26920b57cec5SDimitry Andric     case TemplateArgument::Declaration:
26930b57cec5SDimitry Andric       return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
26940b57cec5SDimitry Andric 
26950b57cec5SDimitry Andric     case TemplateArgument::NullPtr:
26960b57cec5SDimitry Andric       return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
26970b57cec5SDimitry Andric 
26980b57cec5SDimitry Andric     case TemplateArgument::Template:
26990b57cec5SDimitry Andric     case TemplateArgument::TemplateExpansion:
27000b57cec5SDimitry Andric       return Context.getCanonicalTemplateName(
27010b57cec5SDimitry Andric                     X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
27020b57cec5SDimitry Andric              Context.getCanonicalTemplateName(
27030b57cec5SDimitry Andric                     Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
27040b57cec5SDimitry Andric 
27050b57cec5SDimitry Andric     case TemplateArgument::Integral:
27060b57cec5SDimitry Andric       return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
27070b57cec5SDimitry Andric 
27087a6dacacSDimitry Andric     case TemplateArgument::StructuralValue:
27097a6dacacSDimitry Andric       return X.structurallyEquals(Y);
27107a6dacacSDimitry Andric 
27110b57cec5SDimitry Andric     case TemplateArgument::Expression: {
27120b57cec5SDimitry Andric       llvm::FoldingSetNodeID XID, YID;
27130b57cec5SDimitry Andric       X.getAsExpr()->Profile(XID, Context, true);
27140b57cec5SDimitry Andric       Y.getAsExpr()->Profile(YID, Context, true);
27150b57cec5SDimitry Andric       return XID == YID;
27160b57cec5SDimitry Andric     }
27170b57cec5SDimitry Andric 
2718bdd1243dSDimitry Andric     case TemplateArgument::Pack: {
2719bdd1243dSDimitry Andric       unsigned PackIterationSize = X.pack_size();
2720bdd1243dSDimitry Andric       if (X.pack_size() != Y.pack_size()) {
2721bdd1243dSDimitry Andric         if (!PartialOrdering)
27220b57cec5SDimitry Andric           return false;
27230b57cec5SDimitry Andric 
2724bdd1243dSDimitry Andric         // C++0x [temp.deduct.type]p9:
2725bdd1243dSDimitry Andric         // During partial ordering, if Ai was originally a pack expansion:
2726bdd1243dSDimitry Andric         // - if P does not contain a template argument corresponding to Ai
2727bdd1243dSDimitry Andric         //   then Ai is ignored;
2728bdd1243dSDimitry Andric         bool XHasMoreArg = X.pack_size() > Y.pack_size();
2729bdd1243dSDimitry Andric         if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2730bdd1243dSDimitry Andric             !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
27310b57cec5SDimitry Andric           return false;
27320b57cec5SDimitry Andric 
2733bdd1243dSDimitry Andric         if (XHasMoreArg)
2734bdd1243dSDimitry Andric           PackIterationSize = Y.pack_size();
2735bdd1243dSDimitry Andric       }
2736bdd1243dSDimitry Andric 
2737bdd1243dSDimitry Andric       ArrayRef<TemplateArgument> XP = X.pack_elements();
2738bdd1243dSDimitry Andric       ArrayRef<TemplateArgument> YP = Y.pack_elements();
2739bdd1243dSDimitry Andric       for (unsigned i = 0; i < PackIterationSize; ++i)
2740bdd1243dSDimitry Andric         if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2741bdd1243dSDimitry Andric                                PackExpansionMatchesPack))
2742bdd1243dSDimitry Andric           return false;
27430b57cec5SDimitry Andric       return true;
27440b57cec5SDimitry Andric     }
2745bdd1243dSDimitry Andric   }
27460b57cec5SDimitry Andric 
27470b57cec5SDimitry Andric   llvm_unreachable("Invalid TemplateArgument Kind!");
27480b57cec5SDimitry Andric }
27490b57cec5SDimitry Andric 
27500b57cec5SDimitry Andric TemplateArgumentLoc
getTrivialTemplateArgumentLoc(const TemplateArgument & Arg,QualType NTTPType,SourceLocation Loc,NamedDecl * TemplateParam)27510b57cec5SDimitry Andric Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2752*0fca6ea1SDimitry Andric                                     QualType NTTPType, SourceLocation Loc,
2753*0fca6ea1SDimitry Andric                                     NamedDecl *TemplateParam) {
27540b57cec5SDimitry Andric   switch (Arg.getKind()) {
27550b57cec5SDimitry Andric   case TemplateArgument::Null:
27560b57cec5SDimitry Andric     llvm_unreachable("Can't get a NULL template argument here");
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric   case TemplateArgument::Type:
27590b57cec5SDimitry Andric     return TemplateArgumentLoc(
27600b57cec5SDimitry Andric         Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric   case TemplateArgument::Declaration: {
27630b57cec5SDimitry Andric     if (NTTPType.isNull())
27640b57cec5SDimitry Andric       NTTPType = Arg.getParamTypeForDecl();
2765*0fca6ea1SDimitry Andric     Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc,
2766*0fca6ea1SDimitry Andric                                                       TemplateParam)
27670b57cec5SDimitry Andric                   .getAs<Expr>();
27680b57cec5SDimitry Andric     return TemplateArgumentLoc(TemplateArgument(E), E);
27690b57cec5SDimitry Andric   }
27700b57cec5SDimitry Andric 
27710b57cec5SDimitry Andric   case TemplateArgument::NullPtr: {
27720b57cec5SDimitry Andric     if (NTTPType.isNull())
27730b57cec5SDimitry Andric       NTTPType = Arg.getNullPtrType();
27740b57cec5SDimitry Andric     Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
27750b57cec5SDimitry Andric                   .getAs<Expr>();
27760b57cec5SDimitry Andric     return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
27770b57cec5SDimitry Andric                                E);
27780b57cec5SDimitry Andric   }
27790b57cec5SDimitry Andric 
27807a6dacacSDimitry Andric   case TemplateArgument::Integral:
27817a6dacacSDimitry Andric   case TemplateArgument::StructuralValue: {
27827a6dacacSDimitry Andric     Expr *E = BuildExpressionFromNonTypeTemplateArgument(Arg, Loc).get();
27830b57cec5SDimitry Andric     return TemplateArgumentLoc(TemplateArgument(E), E);
27840b57cec5SDimitry Andric   }
27850b57cec5SDimitry Andric 
27860b57cec5SDimitry Andric     case TemplateArgument::Template:
27870b57cec5SDimitry Andric     case TemplateArgument::TemplateExpansion: {
27880b57cec5SDimitry Andric       NestedNameSpecifierLocBuilder Builder;
278913138422SDimitry Andric       TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
27900b57cec5SDimitry Andric       if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
27910b57cec5SDimitry Andric         Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
27920b57cec5SDimitry Andric       else if (QualifiedTemplateName *QTN =
27930b57cec5SDimitry Andric                    Template.getAsQualifiedTemplateName())
27940b57cec5SDimitry Andric         Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
27950b57cec5SDimitry Andric 
27960b57cec5SDimitry Andric       if (Arg.getKind() == TemplateArgument::Template)
2797e8d8bef9SDimitry Andric         return TemplateArgumentLoc(Context, Arg,
2798e8d8bef9SDimitry Andric                                    Builder.getWithLocInContext(Context), Loc);
27990b57cec5SDimitry Andric 
2800e8d8bef9SDimitry Andric       return TemplateArgumentLoc(
2801e8d8bef9SDimitry Andric           Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
28020b57cec5SDimitry Andric     }
28030b57cec5SDimitry Andric 
28040b57cec5SDimitry Andric   case TemplateArgument::Expression:
28050b57cec5SDimitry Andric     return TemplateArgumentLoc(Arg, Arg.getAsExpr());
28060b57cec5SDimitry Andric 
28070b57cec5SDimitry Andric   case TemplateArgument::Pack:
28080b57cec5SDimitry Andric     return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
28090b57cec5SDimitry Andric   }
28100b57cec5SDimitry Andric 
28110b57cec5SDimitry Andric   llvm_unreachable("Invalid TemplateArgument Kind!");
28120b57cec5SDimitry Andric }
28130b57cec5SDimitry Andric 
2814480093f4SDimitry Andric TemplateArgumentLoc
getIdentityTemplateArgumentLoc(NamedDecl * TemplateParm,SourceLocation Location)281513138422SDimitry Andric Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm,
2816480093f4SDimitry Andric                                      SourceLocation Location) {
2817480093f4SDimitry Andric   return getTrivialTemplateArgumentLoc(
281813138422SDimitry Andric       Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2819480093f4SDimitry Andric }
2820480093f4SDimitry Andric 
28210b57cec5SDimitry Andric /// Convert the given deduced template argument and add it to the set of
28220b57cec5SDimitry Andric /// fully-converted template arguments.
ConvertDeducedTemplateArgument(Sema & S,NamedDecl * Param,DeducedTemplateArgument Arg,NamedDecl * Template,TemplateDeductionInfo & Info,bool IsDeduced,SmallVectorImpl<TemplateArgument> & SugaredOutput,SmallVectorImpl<TemplateArgument> & CanonicalOutput)2823bdd1243dSDimitry Andric static bool ConvertDeducedTemplateArgument(
2824bdd1243dSDimitry Andric     Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2825bdd1243dSDimitry Andric     TemplateDeductionInfo &Info, bool IsDeduced,
2826bdd1243dSDimitry Andric     SmallVectorImpl<TemplateArgument> &SugaredOutput,
2827bdd1243dSDimitry Andric     SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
28280b57cec5SDimitry Andric   auto ConvertArg = [&](DeducedTemplateArgument Arg,
28290b57cec5SDimitry Andric                         unsigned ArgumentPackIndex) {
28300b57cec5SDimitry Andric     // Convert the deduced template argument into a template
28310b57cec5SDimitry Andric     // argument that we can check, almost as if the user had written
28320b57cec5SDimitry Andric     // the template argument explicitly.
2833*0fca6ea1SDimitry Andric     TemplateArgumentLoc ArgLoc = S.getTrivialTemplateArgumentLoc(
2834*0fca6ea1SDimitry Andric         Arg, QualType(), Info.getLocation(), Param);
28350b57cec5SDimitry Andric 
28360b57cec5SDimitry Andric     // Check the template argument, converting it as necessary.
28370b57cec5SDimitry Andric     return S.CheckTemplateArgument(
28380b57cec5SDimitry Andric         Param, ArgLoc, Template, Template->getLocation(),
2839bdd1243dSDimitry Andric         Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2840bdd1243dSDimitry Andric         CanonicalOutput,
28410b57cec5SDimitry Andric         IsDeduced
28420b57cec5SDimitry Andric             ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
28430b57cec5SDimitry Andric                                               : Sema::CTAK_Deduced)
28440b57cec5SDimitry Andric             : Sema::CTAK_Specified);
28450b57cec5SDimitry Andric   };
28460b57cec5SDimitry Andric 
28470b57cec5SDimitry Andric   if (Arg.getKind() == TemplateArgument::Pack) {
28480b57cec5SDimitry Andric     // This is a template argument pack, so check each of its arguments against
28490b57cec5SDimitry Andric     // the template parameter.
2850bdd1243dSDimitry Andric     SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2851bdd1243dSDimitry Andric         CanonicalPackedArgsBuilder;
28520b57cec5SDimitry Andric     for (const auto &P : Arg.pack_elements()) {
28530b57cec5SDimitry Andric       // When converting the deduced template argument, append it to the
28540b57cec5SDimitry Andric       // general output list. We need to do this so that the template argument
28550b57cec5SDimitry Andric       // checking logic has all of the prior template arguments available.
28560b57cec5SDimitry Andric       DeducedTemplateArgument InnerArg(P);
28570b57cec5SDimitry Andric       InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
28580b57cec5SDimitry Andric       assert(InnerArg.getKind() != TemplateArgument::Pack &&
28590b57cec5SDimitry Andric              "deduced nested pack");
28600b57cec5SDimitry Andric       if (P.isNull()) {
28610b57cec5SDimitry Andric         // We deduced arguments for some elements of this pack, but not for
28620b57cec5SDimitry Andric         // all of them. This happens if we get a conditionally-non-deduced
28630b57cec5SDimitry Andric         // context in a pack expansion (such as an overload set in one of the
28640b57cec5SDimitry Andric         // arguments).
28650b57cec5SDimitry Andric         S.Diag(Param->getLocation(),
28660b57cec5SDimitry Andric                diag::err_template_arg_deduced_incomplete_pack)
28670b57cec5SDimitry Andric           << Arg << Param;
28680b57cec5SDimitry Andric         return true;
28690b57cec5SDimitry Andric       }
2870bdd1243dSDimitry Andric       if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
28710b57cec5SDimitry Andric         return true;
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric       // Move the converted template argument into our argument pack.
2874bdd1243dSDimitry Andric       SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2875bdd1243dSDimitry Andric       CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
28760b57cec5SDimitry Andric     }
28770b57cec5SDimitry Andric 
28780b57cec5SDimitry Andric     // If the pack is empty, we still need to substitute into the parameter
28790b57cec5SDimitry Andric     // itself, in case that substitution fails.
2880bdd1243dSDimitry Andric     if (SugaredPackedArgsBuilder.empty()) {
28810b57cec5SDimitry Andric       LocalInstantiationScope Scope(S);
2882bdd1243dSDimitry Andric       MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2883bdd1243dSDimitry Andric                                           /*Final=*/true);
28840b57cec5SDimitry Andric 
28850b57cec5SDimitry Andric       if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
28860b57cec5SDimitry Andric         Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2887bdd1243dSDimitry Andric                                          NTTP, SugaredOutput,
28880b57cec5SDimitry Andric                                          Template->getSourceRange());
28890b57cec5SDimitry Andric         if (Inst.isInvalid() ||
28900b57cec5SDimitry Andric             S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
28910b57cec5SDimitry Andric                         NTTP->getDeclName()).isNull())
28920b57cec5SDimitry Andric           return true;
28930b57cec5SDimitry Andric       } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
28940b57cec5SDimitry Andric         Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2895bdd1243dSDimitry Andric                                          TTP, SugaredOutput,
28960b57cec5SDimitry Andric                                          Template->getSourceRange());
28970b57cec5SDimitry Andric         if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
28980b57cec5SDimitry Andric           return true;
28990b57cec5SDimitry Andric       }
29000b57cec5SDimitry Andric       // For type parameters, no substitution is ever required.
29010b57cec5SDimitry Andric     }
29020b57cec5SDimitry Andric 
29030b57cec5SDimitry Andric     // Create the resulting argument pack.
2904bdd1243dSDimitry Andric     SugaredOutput.push_back(
2905bdd1243dSDimitry Andric         TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2906bdd1243dSDimitry Andric     CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2907bdd1243dSDimitry Andric         S.Context, CanonicalPackedArgsBuilder));
29080b57cec5SDimitry Andric     return false;
29090b57cec5SDimitry Andric   }
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric   return ConvertArg(Arg, 0);
29120b57cec5SDimitry Andric }
29130b57cec5SDimitry Andric 
29140b57cec5SDimitry Andric // FIXME: This should not be a template, but
29150b57cec5SDimitry Andric // ClassTemplatePartialSpecializationDecl sadly does not derive from
29160b57cec5SDimitry Andric // TemplateDecl.
29170b57cec5SDimitry Andric template <typename TemplateDeclT>
ConvertDeducedTemplateArguments(Sema & S,TemplateDeclT * Template,bool IsDeduced,SmallVectorImpl<DeducedTemplateArgument> & Deduced,TemplateDeductionInfo & Info,SmallVectorImpl<TemplateArgument> & SugaredBuilder,SmallVectorImpl<TemplateArgument> & CanonicalBuilder,LocalInstantiationScope * CurrentInstantiationScope=nullptr,unsigned NumAlreadyConverted=0,bool PartialOverloading=false)2918*0fca6ea1SDimitry Andric static TemplateDeductionResult ConvertDeducedTemplateArguments(
29190b57cec5SDimitry Andric     Sema &S, TemplateDeclT *Template, bool IsDeduced,
29200b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2921bdd1243dSDimitry Andric     TemplateDeductionInfo &Info,
2922bdd1243dSDimitry Andric     SmallVectorImpl<TemplateArgument> &SugaredBuilder,
2923bdd1243dSDimitry Andric     SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
29240b57cec5SDimitry Andric     LocalInstantiationScope *CurrentInstantiationScope = nullptr,
29250b57cec5SDimitry Andric     unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
29260b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = Template->getTemplateParameters();
29270b57cec5SDimitry Andric 
29280b57cec5SDimitry Andric   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
29290b57cec5SDimitry Andric     NamedDecl *Param = TemplateParams->getParam(I);
29300b57cec5SDimitry Andric 
29310b57cec5SDimitry Andric     // C++0x [temp.arg.explicit]p3:
29320b57cec5SDimitry Andric     //    A trailing template parameter pack (14.5.3) not otherwise deduced will
29330b57cec5SDimitry Andric     //    be deduced to an empty sequence of template arguments.
29340b57cec5SDimitry Andric     // FIXME: Where did the word "trailing" come from?
29350b57cec5SDimitry Andric     if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2936480093f4SDimitry Andric       if (auto Result =
2937*0fca6ea1SDimitry Andric               PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish();
2938*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
29390b57cec5SDimitry Andric         return Result;
29400b57cec5SDimitry Andric     }
29410b57cec5SDimitry Andric 
29420b57cec5SDimitry Andric     if (!Deduced[I].isNull()) {
29430b57cec5SDimitry Andric       if (I < NumAlreadyConverted) {
29440b57cec5SDimitry Andric         // We may have had explicitly-specified template arguments for a
29450b57cec5SDimitry Andric         // template parameter pack (that may or may not have been extended
29460b57cec5SDimitry Andric         // via additional deduced arguments).
29470b57cec5SDimitry Andric         if (Param->isParameterPack() && CurrentInstantiationScope &&
29480b57cec5SDimitry Andric             CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
29490b57cec5SDimitry Andric           // Forget the partially-substituted pack; its substitution is now
29500b57cec5SDimitry Andric           // complete.
29510b57cec5SDimitry Andric           CurrentInstantiationScope->ResetPartiallySubstitutedPack();
29520b57cec5SDimitry Andric           // We still need to check the argument in case it was extended by
29530b57cec5SDimitry Andric           // deduction.
29540b57cec5SDimitry Andric         } else {
29550b57cec5SDimitry Andric           // We have already fully type-checked and converted this
29560b57cec5SDimitry Andric           // argument, because it was explicitly-specified. Just record the
29570b57cec5SDimitry Andric           // presence of this argument.
2958bdd1243dSDimitry Andric           SugaredBuilder.push_back(Deduced[I]);
2959bdd1243dSDimitry Andric           CanonicalBuilder.push_back(
2960bdd1243dSDimitry Andric               S.Context.getCanonicalTemplateArgument(Deduced[I]));
29610b57cec5SDimitry Andric           continue;
29620b57cec5SDimitry Andric         }
29630b57cec5SDimitry Andric       }
29640b57cec5SDimitry Andric 
29650b57cec5SDimitry Andric       // We may have deduced this argument, so it still needs to be
29660b57cec5SDimitry Andric       // checked and converted.
29670b57cec5SDimitry Andric       if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2968bdd1243dSDimitry Andric                                          IsDeduced, SugaredBuilder,
2969bdd1243dSDimitry Andric                                          CanonicalBuilder)) {
29700b57cec5SDimitry Andric         Info.Param = makeTemplateParameter(Param);
29710b57cec5SDimitry Andric         // FIXME: These template arguments are temporary. Free them!
2972bdd1243dSDimitry Andric         Info.reset(
2973bdd1243dSDimitry Andric             TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2974bdd1243dSDimitry Andric             TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2975*0fca6ea1SDimitry Andric         return TemplateDeductionResult::SubstitutionFailure;
29760b57cec5SDimitry Andric       }
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric       continue;
29790b57cec5SDimitry Andric     }
29800b57cec5SDimitry Andric 
29810b57cec5SDimitry Andric     // Substitute into the default template argument, if available.
29820b57cec5SDimitry Andric     bool HasDefaultArg = false;
29830b57cec5SDimitry Andric     TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
29840b57cec5SDimitry Andric     if (!TD) {
29850b57cec5SDimitry Andric       assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
29860b57cec5SDimitry Andric              isa<VarTemplatePartialSpecializationDecl>(Template));
2987*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Incomplete;
29880b57cec5SDimitry Andric     }
29890b57cec5SDimitry Andric 
2990349cc55cSDimitry Andric     TemplateArgumentLoc DefArg;
2991349cc55cSDimitry Andric     {
2992349cc55cSDimitry Andric       Qualifiers ThisTypeQuals;
2993349cc55cSDimitry Andric       CXXRecordDecl *ThisContext = nullptr;
2994349cc55cSDimitry Andric       if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
2995349cc55cSDimitry Andric         if (Rec->isLambda())
2996349cc55cSDimitry Andric           if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
2997349cc55cSDimitry Andric             ThisContext = Method->getParent();
2998349cc55cSDimitry Andric             ThisTypeQuals = Method->getMethodQualifiers();
2999349cc55cSDimitry Andric           }
3000349cc55cSDimitry Andric 
3001349cc55cSDimitry Andric       Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
3002349cc55cSDimitry Andric                                        S.getLangOpts().CPlusPlus17);
3003349cc55cSDimitry Andric 
3004349cc55cSDimitry Andric       DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
3005bdd1243dSDimitry Andric           TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
3006bdd1243dSDimitry Andric           SugaredBuilder, CanonicalBuilder, HasDefaultArg);
3007349cc55cSDimitry Andric     }
30080b57cec5SDimitry Andric 
30090b57cec5SDimitry Andric     // If there was no default argument, deduction is incomplete.
30100b57cec5SDimitry Andric     if (DefArg.getArgument().isNull()) {
30110b57cec5SDimitry Andric       Info.Param = makeTemplateParameter(
30120b57cec5SDimitry Andric           const_cast<NamedDecl *>(TemplateParams->getParam(I)));
3013bdd1243dSDimitry Andric       Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3014bdd1243dSDimitry Andric                  TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
30150b57cec5SDimitry Andric       if (PartialOverloading) break;
30160b57cec5SDimitry Andric 
3017*0fca6ea1SDimitry Andric       return HasDefaultArg ? TemplateDeductionResult::SubstitutionFailure
3018*0fca6ea1SDimitry Andric                            : TemplateDeductionResult::Incomplete;
30190b57cec5SDimitry Andric     }
30200b57cec5SDimitry Andric 
30210b57cec5SDimitry Andric     // Check whether we can actually use the default argument.
3022bdd1243dSDimitry Andric     if (S.CheckTemplateArgument(
3023bdd1243dSDimitry Andric             Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
3024bdd1243dSDimitry Andric             0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
30250b57cec5SDimitry Andric       Info.Param = makeTemplateParameter(
30260b57cec5SDimitry Andric                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
30270b57cec5SDimitry Andric       // FIXME: These template arguments are temporary. Free them!
3028bdd1243dSDimitry Andric       Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
3029bdd1243dSDimitry Andric                  TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
3030*0fca6ea1SDimitry Andric       return TemplateDeductionResult::SubstitutionFailure;
30310b57cec5SDimitry Andric     }
30320b57cec5SDimitry Andric 
30330b57cec5SDimitry Andric     // If we get here, we successfully used the default template argument.
30340b57cec5SDimitry Andric   }
30350b57cec5SDimitry Andric 
3036*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
30370b57cec5SDimitry Andric }
30380b57cec5SDimitry Andric 
getAsDeclContextOrEnclosing(Decl * D)30390b57cec5SDimitry Andric static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
30400b57cec5SDimitry Andric   if (auto *DC = dyn_cast<DeclContext>(D))
30410b57cec5SDimitry Andric     return DC;
30420b57cec5SDimitry Andric   return D->getDeclContext();
30430b57cec5SDimitry Andric }
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric template<typename T> struct IsPartialSpecialization {
30460b57cec5SDimitry Andric   static constexpr bool value = false;
30470b57cec5SDimitry Andric };
30480b57cec5SDimitry Andric template<>
30490b57cec5SDimitry Andric struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
30500b57cec5SDimitry Andric   static constexpr bool value = true;
30510b57cec5SDimitry Andric };
30520b57cec5SDimitry Andric template<>
30530b57cec5SDimitry Andric struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
30540b57cec5SDimitry Andric   static constexpr bool value = true;
30550b57cec5SDimitry Andric };
3056bdd1243dSDimitry Andric template <typename TemplateDeclT>
DeducedArgsNeedReplacement(TemplateDeclT * Template)3057bdd1243dSDimitry Andric static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
3058bdd1243dSDimitry Andric   return false;
3059bdd1243dSDimitry Andric }
3060bdd1243dSDimitry Andric template <>
DeducedArgsNeedReplacement(VarTemplatePartialSpecializationDecl * Spec)3061bdd1243dSDimitry Andric bool DeducedArgsNeedReplacement<VarTemplatePartialSpecializationDecl>(
3062bdd1243dSDimitry Andric     VarTemplatePartialSpecializationDecl *Spec) {
3063bdd1243dSDimitry Andric   return !Spec->isClassScopeExplicitSpecialization();
3064bdd1243dSDimitry Andric }
3065bdd1243dSDimitry Andric template <>
DeducedArgsNeedReplacement(ClassTemplatePartialSpecializationDecl * Spec)3066bdd1243dSDimitry Andric bool DeducedArgsNeedReplacement<ClassTemplatePartialSpecializationDecl>(
3067bdd1243dSDimitry Andric     ClassTemplatePartialSpecializationDecl *Spec) {
3068bdd1243dSDimitry Andric   return !Spec->isClassScopeExplicitSpecialization();
3069bdd1243dSDimitry Andric }
30700b57cec5SDimitry Andric 
3071480093f4SDimitry Andric template <typename TemplateDeclT>
3072*0fca6ea1SDimitry Andric static TemplateDeductionResult
CheckDeducedArgumentConstraints(Sema & S,TemplateDeclT * Template,ArrayRef<TemplateArgument> SugaredDeducedArgs,ArrayRef<TemplateArgument> CanonicalDeducedArgs,TemplateDeductionInfo & Info)3073480093f4SDimitry Andric CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
3074bdd1243dSDimitry Andric                                 ArrayRef<TemplateArgument> SugaredDeducedArgs,
3075bdd1243dSDimitry Andric                                 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
3076480093f4SDimitry Andric                                 TemplateDeductionInfo &Info) {
3077480093f4SDimitry Andric   llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
3078480093f4SDimitry Andric   Template->getAssociatedConstraints(AssociatedConstraints);
3079bdd1243dSDimitry Andric 
3080*0fca6ea1SDimitry Andric   std::optional<ArrayRef<TemplateArgument>> Innermost;
3081*0fca6ea1SDimitry Andric   // If we don't need to replace the deduced template arguments,
3082*0fca6ea1SDimitry Andric   // we can add them immediately as the inner-most argument list.
3083*0fca6ea1SDimitry Andric   if (!DeducedArgsNeedReplacement(Template))
3084*0fca6ea1SDimitry Andric     Innermost = CanonicalDeducedArgs;
3085bdd1243dSDimitry Andric 
3086bdd1243dSDimitry Andric   MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
3087*0fca6ea1SDimitry Andric       Template, Template->getDeclContext(), /*Final=*/false, Innermost,
3088bdd1243dSDimitry Andric       /*RelativeToPrimary=*/true, /*Pattern=*/
3089bdd1243dSDimitry Andric       nullptr, /*ForConstraintInstantiation=*/true);
3090bdd1243dSDimitry Andric 
3091bdd1243dSDimitry Andric   // getTemplateInstantiationArgs picks up the non-deduced version of the
3092bdd1243dSDimitry Andric   // template args when this is a variable template partial specialization and
3093bdd1243dSDimitry Andric   // not class-scope explicit specialization, so replace with Deduced Args
3094bdd1243dSDimitry Andric   // instead of adding to inner-most.
3095*0fca6ea1SDimitry Andric   if (!Innermost)
309606c3fb27SDimitry Andric     MLTAL.replaceInnermostTemplateArguments(Template, CanonicalDeducedArgs);
3097bdd1243dSDimitry Andric 
3098bdd1243dSDimitry Andric   if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
3099bdd1243dSDimitry Andric                                     Info.getLocation(),
3100480093f4SDimitry Andric                                     Info.AssociatedConstraintsSatisfaction) ||
3101480093f4SDimitry Andric       !Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
3102bdd1243dSDimitry Andric     Info.reset(
3103bdd1243dSDimitry Andric         TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
3104bdd1243dSDimitry Andric         TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
3105*0fca6ea1SDimitry Andric     return TemplateDeductionResult::ConstraintsNotSatisfied;
3106480093f4SDimitry Andric   }
3107*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
3108480093f4SDimitry Andric }
3109480093f4SDimitry Andric 
31100b57cec5SDimitry Andric /// Complete template argument deduction for a partial specialization.
31110b57cec5SDimitry Andric template <typename T>
31125ffd83dbSDimitry Andric static std::enable_if_t<IsPartialSpecialization<T>::value,
3113*0fca6ea1SDimitry Andric                         TemplateDeductionResult>
FinishTemplateArgumentDeduction(Sema & S,T * Partial,bool IsPartialOrdering,ArrayRef<TemplateArgument> TemplateArgs,SmallVectorImpl<DeducedTemplateArgument> & Deduced,TemplateDeductionInfo & Info)31140b57cec5SDimitry Andric FinishTemplateArgumentDeduction(
31150b57cec5SDimitry Andric     Sema &S, T *Partial, bool IsPartialOrdering,
3116*0fca6ea1SDimitry Andric     ArrayRef<TemplateArgument> TemplateArgs,
31170b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
31180b57cec5SDimitry Andric     TemplateDeductionInfo &Info) {
31190b57cec5SDimitry Andric   // Unevaluated SFINAE context.
31200b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
31210b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::Unevaluated);
31220b57cec5SDimitry Andric   Sema::SFINAETrap Trap(S);
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric   Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
31250b57cec5SDimitry Andric 
31260b57cec5SDimitry Andric   // C++ [temp.deduct.type]p2:
31270b57cec5SDimitry Andric   //   [...] or if any template argument remains neither deduced nor
31280b57cec5SDimitry Andric   //   explicitly specified, template argument deduction fails.
3129bdd1243dSDimitry Andric   SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
31300b57cec5SDimitry Andric   if (auto Result = ConvertDeducedTemplateArguments(
3131bdd1243dSDimitry Andric           S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
3132*0fca6ea1SDimitry Andric           CanonicalBuilder);
3133*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
31340b57cec5SDimitry Andric     return Result;
31350b57cec5SDimitry Andric 
31360b57cec5SDimitry Andric   // Form the template argument list from the deduced template arguments.
3137bdd1243dSDimitry Andric   TemplateArgumentList *SugaredDeducedArgumentList =
3138bdd1243dSDimitry Andric       TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
3139bdd1243dSDimitry Andric   TemplateArgumentList *CanonicalDeducedArgumentList =
3140bdd1243dSDimitry Andric       TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
31410b57cec5SDimitry Andric 
3142bdd1243dSDimitry Andric   Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
31430b57cec5SDimitry Andric 
31440b57cec5SDimitry Andric   // Substitute the deduced template arguments into the template
31450b57cec5SDimitry Andric   // arguments of the class template partial specialization, and
31460b57cec5SDimitry Andric   // verify that the instantiated template arguments are both valid
31470b57cec5SDimitry Andric   // and are equivalent to the template arguments originally provided
31480b57cec5SDimitry Andric   // to the class template.
31490b57cec5SDimitry Andric   LocalInstantiationScope InstScope(S);
31500b57cec5SDimitry Andric   auto *Template = Partial->getSpecializedTemplate();
31510b57cec5SDimitry Andric   const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
31520b57cec5SDimitry Andric       Partial->getTemplateArgsAsWritten();
31530b57cec5SDimitry Andric 
31540b57cec5SDimitry Andric   TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
31550b57cec5SDimitry Andric                                     PartialTemplArgInfo->RAngleLoc);
31560b57cec5SDimitry Andric 
3157bdd1243dSDimitry Andric   if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
3158bdd1243dSDimitry Andric                                MultiLevelTemplateArgumentList(Partial,
3159bdd1243dSDimitry Andric                                                               SugaredBuilder,
3160bdd1243dSDimitry Andric                                                               /*Final=*/true),
3161bdd1243dSDimitry Andric                                InstArgs)) {
31620b57cec5SDimitry Andric     unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
31630b57cec5SDimitry Andric     if (ParamIdx >= Partial->getTemplateParameters()->size())
31640b57cec5SDimitry Andric       ParamIdx = Partial->getTemplateParameters()->size() - 1;
31650b57cec5SDimitry Andric 
31660b57cec5SDimitry Andric     Decl *Param = const_cast<NamedDecl *>(
31670b57cec5SDimitry Andric         Partial->getTemplateParameters()->getParam(ParamIdx));
31680b57cec5SDimitry Andric     Info.Param = makeTemplateParameter(Param);
3169349cc55cSDimitry Andric     Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
3170*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
31710b57cec5SDimitry Andric   }
31720b57cec5SDimitry Andric 
3173480093f4SDimitry Andric   bool ConstraintsNotSatisfied;
3174bdd1243dSDimitry Andric   SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
3175bdd1243dSDimitry Andric       CanonicalConvertedInstArgs;
3176bdd1243dSDimitry Andric   if (S.CheckTemplateArgumentList(
3177bdd1243dSDimitry Andric           Template, Partial->getLocation(), InstArgs, false,
3178bdd1243dSDimitry Andric           SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
3179bdd1243dSDimitry Andric           /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
3180*0fca6ea1SDimitry Andric     return ConstraintsNotSatisfied
3181*0fca6ea1SDimitry Andric                ? TemplateDeductionResult::ConstraintsNotSatisfied
3182*0fca6ea1SDimitry Andric                : TemplateDeductionResult::SubstitutionFailure;
31830b57cec5SDimitry Andric 
31840b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = Template->getTemplateParameters();
31850b57cec5SDimitry Andric   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3186bdd1243dSDimitry Andric     TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
3187bdd1243dSDimitry Andric     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
3188bdd1243dSDimitry Andric                            IsPartialOrdering)) {
31890b57cec5SDimitry Andric       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
31900b57cec5SDimitry Andric       Info.FirstArg = TemplateArgs[I];
31910b57cec5SDimitry Andric       Info.SecondArg = InstArg;
3192*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
31930b57cec5SDimitry Andric     }
31940b57cec5SDimitry Andric   }
31950b57cec5SDimitry Andric 
31960b57cec5SDimitry Andric   if (Trap.hasErrorOccurred())
3197*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
31980b57cec5SDimitry Andric 
3199bdd1243dSDimitry Andric   if (auto Result = CheckDeducedArgumentConstraints(S, Partial, SugaredBuilder,
3200*0fca6ea1SDimitry Andric                                                     CanonicalBuilder, Info);
3201*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
3202480093f4SDimitry Andric     return Result;
3203480093f4SDimitry Andric 
3204*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
32050b57cec5SDimitry Andric }
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric /// Complete template argument deduction for a class or variable template,
32080b57cec5SDimitry Andric /// when partial ordering against a partial specialization.
32090b57cec5SDimitry Andric // FIXME: Factor out duplication with partial specialization version above.
FinishTemplateArgumentDeduction(Sema & S,TemplateDecl * Template,bool PartialOrdering,ArrayRef<TemplateArgument> TemplateArgs,SmallVectorImpl<DeducedTemplateArgument> & Deduced,TemplateDeductionInfo & Info)3210*0fca6ea1SDimitry Andric static TemplateDeductionResult FinishTemplateArgumentDeduction(
32110b57cec5SDimitry Andric     Sema &S, TemplateDecl *Template, bool PartialOrdering,
3212*0fca6ea1SDimitry Andric     ArrayRef<TemplateArgument> TemplateArgs,
32130b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
32140b57cec5SDimitry Andric     TemplateDeductionInfo &Info) {
32150b57cec5SDimitry Andric   // Unevaluated SFINAE context.
32160b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
32170b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::Unevaluated);
32180b57cec5SDimitry Andric   Sema::SFINAETrap Trap(S);
32190b57cec5SDimitry Andric 
32200b57cec5SDimitry Andric   Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
32210b57cec5SDimitry Andric 
32220b57cec5SDimitry Andric   // C++ [temp.deduct.type]p2:
32230b57cec5SDimitry Andric   //   [...] or if any template argument remains neither deduced nor
32240b57cec5SDimitry Andric   //   explicitly specified, template argument deduction fails.
3225bdd1243dSDimitry Andric   SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
32260b57cec5SDimitry Andric   if (auto Result = ConvertDeducedTemplateArguments(
3227bdd1243dSDimitry Andric           S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3228bdd1243dSDimitry Andric           SugaredBuilder, CanonicalBuilder,
3229bdd1243dSDimitry Andric           /*CurrentInstantiationScope=*/nullptr,
3230*0fca6ea1SDimitry Andric           /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false);
3231*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
32320b57cec5SDimitry Andric     return Result;
32330b57cec5SDimitry Andric 
32340b57cec5SDimitry Andric   // Check that we produced the correct argument list.
32350b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = Template->getTemplateParameters();
32360b57cec5SDimitry Andric   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3237bdd1243dSDimitry Andric     TemplateArgument InstArg = CanonicalBuilder[I];
3238bdd1243dSDimitry Andric     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3239bdd1243dSDimitry Andric                            /*PackExpansionMatchesPack=*/true)) {
32400b57cec5SDimitry Andric       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
32410b57cec5SDimitry Andric       Info.FirstArg = TemplateArgs[I];
32420b57cec5SDimitry Andric       Info.SecondArg = InstArg;
3243*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
32440b57cec5SDimitry Andric     }
32450b57cec5SDimitry Andric   }
32460b57cec5SDimitry Andric 
32470b57cec5SDimitry Andric   if (Trap.hasErrorOccurred())
3248*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
32490b57cec5SDimitry Andric 
3250bdd1243dSDimitry Andric   if (auto Result = CheckDeducedArgumentConstraints(S, Template, SugaredBuilder,
3251*0fca6ea1SDimitry Andric                                                     CanonicalBuilder, Info);
3252*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
3253480093f4SDimitry Andric     return Result;
3254480093f4SDimitry Andric 
3255*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
3256*0fca6ea1SDimitry Andric }
3257*0fca6ea1SDimitry Andric /// Complete template argument deduction for DeduceTemplateArgumentsFromType.
3258*0fca6ea1SDimitry Andric /// FIXME: this is mostly duplicated with the above two versions. Deduplicate
3259*0fca6ea1SDimitry Andric /// the three implementations.
FinishTemplateArgumentDeduction(Sema & S,TemplateDecl * TD,SmallVectorImpl<DeducedTemplateArgument> & Deduced,TemplateDeductionInfo & Info)3260*0fca6ea1SDimitry Andric static TemplateDeductionResult FinishTemplateArgumentDeduction(
3261*0fca6ea1SDimitry Andric     Sema &S, TemplateDecl *TD,
3262*0fca6ea1SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3263*0fca6ea1SDimitry Andric     TemplateDeductionInfo &Info) {
3264*0fca6ea1SDimitry Andric   // Unevaluated SFINAE context.
3265*0fca6ea1SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
3266*0fca6ea1SDimitry Andric       S, Sema::ExpressionEvaluationContext::Unevaluated);
3267*0fca6ea1SDimitry Andric   Sema::SFINAETrap Trap(S);
3268*0fca6ea1SDimitry Andric 
3269*0fca6ea1SDimitry Andric   Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(TD));
3270*0fca6ea1SDimitry Andric 
3271*0fca6ea1SDimitry Andric   // C++ [temp.deduct.type]p2:
3272*0fca6ea1SDimitry Andric   //   [...] or if any template argument remains neither deduced nor
3273*0fca6ea1SDimitry Andric   //   explicitly specified, template argument deduction fails.
3274*0fca6ea1SDimitry Andric   SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3275*0fca6ea1SDimitry Andric   if (auto Result = ConvertDeducedTemplateArguments(
3276*0fca6ea1SDimitry Andric           S, TD, /*IsPartialOrdering=*/false, Deduced, Info, SugaredBuilder,
3277*0fca6ea1SDimitry Andric           CanonicalBuilder);
3278*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
3279*0fca6ea1SDimitry Andric     return Result;
3280*0fca6ea1SDimitry Andric 
3281*0fca6ea1SDimitry Andric   if (Trap.hasErrorOccurred())
3282*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
3283*0fca6ea1SDimitry Andric 
3284*0fca6ea1SDimitry Andric   if (auto Result = CheckDeducedArgumentConstraints(S, TD, SugaredBuilder,
3285*0fca6ea1SDimitry Andric                                                     CanonicalBuilder, Info);
3286*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
3287*0fca6ea1SDimitry Andric     return Result;
3288*0fca6ea1SDimitry Andric 
3289*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
32900b57cec5SDimitry Andric }
32910b57cec5SDimitry Andric 
3292*0fca6ea1SDimitry Andric /// Perform template argument deduction to determine whether the given template
3293*0fca6ea1SDimitry Andric /// arguments match the given class or variable template partial specialization
3294*0fca6ea1SDimitry Andric /// per C++ [temp.class.spec.match].
3295*0fca6ea1SDimitry Andric template <typename T>
3296*0fca6ea1SDimitry Andric static std::enable_if_t<IsPartialSpecialization<T>::value,
3297*0fca6ea1SDimitry Andric                         TemplateDeductionResult>
DeduceTemplateArguments(Sema & S,T * Partial,ArrayRef<TemplateArgument> TemplateArgs,TemplateDeductionInfo & Info)3298*0fca6ea1SDimitry Andric DeduceTemplateArguments(Sema &S, T *Partial,
3299*0fca6ea1SDimitry Andric                         ArrayRef<TemplateArgument> TemplateArgs,
33000b57cec5SDimitry Andric                         TemplateDeductionInfo &Info) {
33010b57cec5SDimitry Andric   if (Partial->isInvalidDecl())
3302*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Invalid;
33030b57cec5SDimitry Andric 
33040b57cec5SDimitry Andric   // C++ [temp.class.spec.match]p2:
33050b57cec5SDimitry Andric   //   A partial specialization matches a given actual template
33060b57cec5SDimitry Andric   //   argument list if the template arguments of the partial
33070b57cec5SDimitry Andric   //   specialization can be deduced from the actual template argument
33080b57cec5SDimitry Andric   //   list (14.8.2).
33090b57cec5SDimitry Andric 
33100b57cec5SDimitry Andric   // Unevaluated SFINAE context.
33110b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
3312*0fca6ea1SDimitry Andric       S, Sema::ExpressionEvaluationContext::Unevaluated);
3313*0fca6ea1SDimitry Andric   Sema::SFINAETrap Trap(S);
33140b57cec5SDimitry Andric 
3315fe6060f1SDimitry Andric   // This deduction has no relation to any outer instantiation we might be
3316fe6060f1SDimitry Andric   // performing.
3317*0fca6ea1SDimitry Andric   LocalInstantiationScope InstantiationScope(S);
3318fe6060f1SDimitry Andric 
33190b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
33200b57cec5SDimitry Andric   Deduced.resize(Partial->getTemplateParameters()->size());
3321*0fca6ea1SDimitry Andric   if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
3322*0fca6ea1SDimitry Andric           S, Partial->getTemplateParameters(),
3323*0fca6ea1SDimitry Andric           Partial->getTemplateArgs().asArray(), TemplateArgs, Info, Deduced,
3324*0fca6ea1SDimitry Andric           /*NumberOfArgumentsMustMatch=*/false);
3325*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
33260b57cec5SDimitry Andric     return Result;
33270b57cec5SDimitry Andric 
33280b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3329*0fca6ea1SDimitry Andric   Sema::InstantiatingTemplate Inst(S, Info.getLocation(), Partial, DeducedArgs,
33300b57cec5SDimitry Andric                                    Info);
33310b57cec5SDimitry Andric   if (Inst.isInvalid())
3332*0fca6ea1SDimitry Andric     return TemplateDeductionResult::InstantiationDepth;
33330b57cec5SDimitry Andric 
33340b57cec5SDimitry Andric   if (Trap.hasErrorOccurred())
3335*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
33360b57cec5SDimitry Andric 
33375ffd83dbSDimitry Andric   TemplateDeductionResult Result;
3338*0fca6ea1SDimitry Andric   S.runWithSufficientStackSpace(Info.getLocation(), [&] {
3339*0fca6ea1SDimitry Andric     Result = ::FinishTemplateArgumentDeduction(S, Partial,
33405ffd83dbSDimitry Andric                                                /*IsPartialOrdering=*/false,
33415ffd83dbSDimitry Andric                                                TemplateArgs, Deduced, Info);
33425ffd83dbSDimitry Andric   });
33435ffd83dbSDimitry Andric   return Result;
33440b57cec5SDimitry Andric }
33450b57cec5SDimitry Andric 
3346*0fca6ea1SDimitry Andric TemplateDeductionResult
DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl * Partial,ArrayRef<TemplateArgument> TemplateArgs,TemplateDeductionInfo & Info)3347*0fca6ea1SDimitry Andric Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
3348*0fca6ea1SDimitry Andric                               ArrayRef<TemplateArgument> TemplateArgs,
33490b57cec5SDimitry Andric                               TemplateDeductionInfo &Info) {
3350*0fca6ea1SDimitry Andric   return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3351*0fca6ea1SDimitry Andric }
3352*0fca6ea1SDimitry Andric TemplateDeductionResult
DeduceTemplateArguments(VarTemplatePartialSpecializationDecl * Partial,ArrayRef<TemplateArgument> TemplateArgs,TemplateDeductionInfo & Info)3353*0fca6ea1SDimitry Andric Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
3354*0fca6ea1SDimitry Andric                               ArrayRef<TemplateArgument> TemplateArgs,
3355*0fca6ea1SDimitry Andric                               TemplateDeductionInfo &Info) {
3356*0fca6ea1SDimitry Andric   return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
3357*0fca6ea1SDimitry Andric }
33580b57cec5SDimitry Andric 
3359*0fca6ea1SDimitry Andric TemplateDeductionResult
DeduceTemplateArgumentsFromType(TemplateDecl * TD,QualType FromType,sema::TemplateDeductionInfo & Info)3360*0fca6ea1SDimitry Andric Sema::DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,
3361*0fca6ea1SDimitry Andric                                       sema::TemplateDeductionInfo &Info) {
3362*0fca6ea1SDimitry Andric   if (TD->isInvalidDecl())
3363*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Invalid;
3364*0fca6ea1SDimitry Andric 
3365*0fca6ea1SDimitry Andric   QualType PType;
3366*0fca6ea1SDimitry Andric   if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
3367*0fca6ea1SDimitry Andric     // Use the InjectedClassNameType.
3368*0fca6ea1SDimitry Andric     PType = Context.getTypeDeclType(CTD->getTemplatedDecl());
3369*0fca6ea1SDimitry Andric   } else if (const auto *AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(TD)) {
3370*0fca6ea1SDimitry Andric     PType = AliasTemplate->getTemplatedDecl()
3371*0fca6ea1SDimitry Andric                 ->getUnderlyingType()
3372*0fca6ea1SDimitry Andric                 .getCanonicalType();
3373*0fca6ea1SDimitry Andric   } else {
3374*0fca6ea1SDimitry Andric     assert(false && "Expected a class or alias template");
3375*0fca6ea1SDimitry Andric   }
33760b57cec5SDimitry Andric 
33770b57cec5SDimitry Andric   // Unevaluated SFINAE context.
33780b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
33790b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
33800b57cec5SDimitry Andric   SFINAETrap Trap(*this);
33810b57cec5SDimitry Andric 
3382fe6060f1SDimitry Andric   // This deduction has no relation to any outer instantiation we might be
3383fe6060f1SDimitry Andric   // performing.
3384fe6060f1SDimitry Andric   LocalInstantiationScope InstantiationScope(*this);
3385fe6060f1SDimitry Andric 
3386*0fca6ea1SDimitry Andric   SmallVector<DeducedTemplateArgument> Deduced(
3387*0fca6ea1SDimitry Andric       TD->getTemplateParameters()->size());
3388*0fca6ea1SDimitry Andric   SmallVector<TemplateArgument> PArgs = {TemplateArgument(PType)};
3389*0fca6ea1SDimitry Andric   SmallVector<TemplateArgument> AArgs = {TemplateArgument(FromType)};
3390*0fca6ea1SDimitry Andric   if (auto DeducedResult = DeduceTemplateArguments(
3391*0fca6ea1SDimitry Andric           TD->getTemplateParameters(), PArgs, AArgs, Info, Deduced, false);
3392*0fca6ea1SDimitry Andric       DeducedResult != TemplateDeductionResult::Success) {
3393*0fca6ea1SDimitry Andric     return DeducedResult;
3394*0fca6ea1SDimitry Andric   }
33950b57cec5SDimitry Andric 
33960b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3397*0fca6ea1SDimitry Andric   InstantiatingTemplate Inst(*this, Info.getLocation(), TD, DeducedArgs, Info);
33980b57cec5SDimitry Andric   if (Inst.isInvalid())
3399*0fca6ea1SDimitry Andric     return TemplateDeductionResult::InstantiationDepth;
34000b57cec5SDimitry Andric 
34010b57cec5SDimitry Andric   if (Trap.hasErrorOccurred())
3402*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
34030b57cec5SDimitry Andric 
34045ffd83dbSDimitry Andric   TemplateDeductionResult Result;
34055ffd83dbSDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
3406*0fca6ea1SDimitry Andric     Result = ::FinishTemplateArgumentDeduction(*this, TD, Deduced, Info);
34075ffd83dbSDimitry Andric   });
34085ffd83dbSDimitry Andric   return Result;
34090b57cec5SDimitry Andric }
34100b57cec5SDimitry Andric 
34110b57cec5SDimitry Andric /// Determine whether the given type T is a simple-template-id type.
isSimpleTemplateIdType(QualType T)34120b57cec5SDimitry Andric static bool isSimpleTemplateIdType(QualType T) {
34130b57cec5SDimitry Andric   if (const TemplateSpecializationType *Spec
34140b57cec5SDimitry Andric         = T->getAs<TemplateSpecializationType>())
34150b57cec5SDimitry Andric     return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
34160b57cec5SDimitry Andric 
34170b57cec5SDimitry Andric   // C++17 [temp.local]p2:
34180b57cec5SDimitry Andric   //   the injected-class-name [...] is equivalent to the template-name followed
34190b57cec5SDimitry Andric   //   by the template-arguments of the class template specialization or partial
34200b57cec5SDimitry Andric   //   specialization enclosed in <>
34210b57cec5SDimitry Andric   // ... which means it's equivalent to a simple-template-id.
34220b57cec5SDimitry Andric   //
34230b57cec5SDimitry Andric   // This only arises during class template argument deduction for a copy
34240b57cec5SDimitry Andric   // deduction candidate, where it permits slicing.
34250b57cec5SDimitry Andric   if (T->getAs<InjectedClassNameType>())
34260b57cec5SDimitry Andric     return true;
34270b57cec5SDimitry Andric 
34280b57cec5SDimitry Andric   return false;
34290b57cec5SDimitry Andric }
34300b57cec5SDimitry Andric 
SubstituteExplicitTemplateArguments(FunctionTemplateDecl * FunctionTemplate,TemplateArgumentListInfo & ExplicitTemplateArgs,SmallVectorImpl<DeducedTemplateArgument> & Deduced,SmallVectorImpl<QualType> & ParamTypes,QualType * FunctionType,TemplateDeductionInfo & Info)3431*0fca6ea1SDimitry Andric TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments(
34320b57cec5SDimitry Andric     FunctionTemplateDecl *FunctionTemplate,
34330b57cec5SDimitry Andric     TemplateArgumentListInfo &ExplicitTemplateArgs,
34340b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3435bdd1243dSDimitry Andric     SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
34360b57cec5SDimitry Andric     TemplateDeductionInfo &Info) {
34370b57cec5SDimitry Andric   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
34380b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
34390b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
34400b57cec5SDimitry Andric 
34410b57cec5SDimitry Andric   if (ExplicitTemplateArgs.size() == 0) {
34420b57cec5SDimitry Andric     // No arguments to substitute; just copy over the parameter types and
34430b57cec5SDimitry Andric     // fill in the function type.
3444bdd1243dSDimitry Andric     for (auto *P : Function->parameters())
34450b57cec5SDimitry Andric       ParamTypes.push_back(P->getType());
34460b57cec5SDimitry Andric 
34470b57cec5SDimitry Andric     if (FunctionType)
34480b57cec5SDimitry Andric       *FunctionType = Function->getType();
3449*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
34500b57cec5SDimitry Andric   }
34510b57cec5SDimitry Andric 
34520b57cec5SDimitry Andric   // Unevaluated SFINAE context.
34530b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
34540b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
34550b57cec5SDimitry Andric   SFINAETrap Trap(*this);
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric   // C++ [temp.arg.explicit]p3:
34580b57cec5SDimitry Andric   //   Template arguments that are present shall be specified in the
34590b57cec5SDimitry Andric   //   declaration order of their corresponding template-parameters. The
34600b57cec5SDimitry Andric   //   template argument list shall not specify more template-arguments than
34610b57cec5SDimitry Andric   //   there are corresponding template-parameters.
3462bdd1243dSDimitry Andric   SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
34630b57cec5SDimitry Andric 
34640b57cec5SDimitry Andric   // Enter a new template instantiation context where we check the
34650b57cec5SDimitry Andric   // explicitly-specified template arguments against this function template,
34660b57cec5SDimitry Andric   // and then substitute them into the function parameter types.
34670b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs;
34680b57cec5SDimitry Andric   InstantiatingTemplate Inst(
34690b57cec5SDimitry Andric       *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
34700b57cec5SDimitry Andric       CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
34710b57cec5SDimitry Andric   if (Inst.isInvalid())
3472*0fca6ea1SDimitry Andric     return TemplateDeductionResult::InstantiationDepth;
34730b57cec5SDimitry Andric 
34740b57cec5SDimitry Andric   if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
3475bdd1243dSDimitry Andric                                 ExplicitTemplateArgs, true, SugaredBuilder,
3476bdd1243dSDimitry Andric                                 CanonicalBuilder,
3477bdd1243dSDimitry Andric                                 /*UpdateArgsWithConversions=*/false) ||
34780b57cec5SDimitry Andric       Trap.hasErrorOccurred()) {
3479bdd1243dSDimitry Andric     unsigned Index = SugaredBuilder.size();
34800b57cec5SDimitry Andric     if (Index >= TemplateParams->size())
3481*0fca6ea1SDimitry Andric       return TemplateDeductionResult::SubstitutionFailure;
34820b57cec5SDimitry Andric     Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3483*0fca6ea1SDimitry Andric     return TemplateDeductionResult::InvalidExplicitArguments;
34840b57cec5SDimitry Andric   }
34850b57cec5SDimitry Andric 
34860b57cec5SDimitry Andric   // Form the template argument list from the explicitly-specified
34870b57cec5SDimitry Andric   // template arguments.
3488bdd1243dSDimitry Andric   TemplateArgumentList *SugaredExplicitArgumentList =
3489bdd1243dSDimitry Andric       TemplateArgumentList::CreateCopy(Context, SugaredBuilder);
3490bdd1243dSDimitry Andric   TemplateArgumentList *CanonicalExplicitArgumentList =
3491bdd1243dSDimitry Andric       TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3492bdd1243dSDimitry Andric   Info.setExplicitArgs(SugaredExplicitArgumentList,
3493bdd1243dSDimitry Andric                        CanonicalExplicitArgumentList);
34940b57cec5SDimitry Andric 
34950b57cec5SDimitry Andric   // Template argument deduction and the final substitution should be
34960b57cec5SDimitry Andric   // done in the context of the templated declaration.  Explicit
34970b57cec5SDimitry Andric   // argument substitution, on the other hand, needs to happen in the
34980b57cec5SDimitry Andric   // calling context.
34990b57cec5SDimitry Andric   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric   // If we deduced template arguments for a template parameter pack,
35020b57cec5SDimitry Andric   // note that the template argument pack is partially substituted and record
35030b57cec5SDimitry Andric   // the explicit template arguments. They'll be used as part of deduction
35040b57cec5SDimitry Andric   // for this template parameter pack.
35050b57cec5SDimitry Andric   unsigned PartiallySubstitutedPackIndex = -1u;
3506bdd1243dSDimitry Andric   if (!CanonicalBuilder.empty()) {
3507bdd1243dSDimitry Andric     const TemplateArgument &Arg = CanonicalBuilder.back();
35080b57cec5SDimitry Andric     if (Arg.getKind() == TemplateArgument::Pack) {
3509bdd1243dSDimitry Andric       auto *Param = TemplateParams->getParam(CanonicalBuilder.size() - 1);
35100b57cec5SDimitry Andric       // If this is a fully-saturated fixed-size pack, it should be
35110b57cec5SDimitry Andric       // fully-substituted, not partially-substituted.
3512bdd1243dSDimitry Andric       std::optional<unsigned> Expansions = getExpandedPackSize(Param);
35130b57cec5SDimitry Andric       if (!Expansions || Arg.pack_size() < *Expansions) {
3514bdd1243dSDimitry Andric         PartiallySubstitutedPackIndex = CanonicalBuilder.size() - 1;
35150b57cec5SDimitry Andric         CurrentInstantiationScope->SetPartiallySubstitutedPack(
35160b57cec5SDimitry Andric             Param, Arg.pack_begin(), Arg.pack_size());
35170b57cec5SDimitry Andric       }
35180b57cec5SDimitry Andric     }
35190b57cec5SDimitry Andric   }
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric   const FunctionProtoType *Proto
35220b57cec5SDimitry Andric     = Function->getType()->getAs<FunctionProtoType>();
35230b57cec5SDimitry Andric   assert(Proto && "Function template does not have a prototype?");
35240b57cec5SDimitry Andric 
35250b57cec5SDimitry Andric   // Isolate our substituted parameters from our caller.
35260b57cec5SDimitry Andric   LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
35270b57cec5SDimitry Andric 
35280b57cec5SDimitry Andric   ExtParameterInfoBuilder ExtParamInfos;
35290b57cec5SDimitry Andric 
3530bdd1243dSDimitry Andric   MultiLevelTemplateArgumentList MLTAL(FunctionTemplate,
3531bdd1243dSDimitry Andric                                        SugaredExplicitArgumentList->asArray(),
3532bdd1243dSDimitry Andric                                        /*Final=*/true);
3533bdd1243dSDimitry Andric 
35340b57cec5SDimitry Andric   // Instantiate the types of each of the function parameters given the
35350b57cec5SDimitry Andric   // explicitly-specified template arguments. If the function has a trailing
35360b57cec5SDimitry Andric   // return type, substitute it after the arguments to ensure we substitute
35370b57cec5SDimitry Andric   // in lexical order.
35380b57cec5SDimitry Andric   if (Proto->hasTrailingReturn()) {
35390b57cec5SDimitry Andric     if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3540bdd1243dSDimitry Andric                        Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3541bdd1243dSDimitry Andric                        /*params=*/nullptr, ExtParamInfos))
3542*0fca6ea1SDimitry Andric       return TemplateDeductionResult::SubstitutionFailure;
35430b57cec5SDimitry Andric   }
35440b57cec5SDimitry Andric 
35450b57cec5SDimitry Andric   // Instantiate the return type.
35460b57cec5SDimitry Andric   QualType ResultType;
35470b57cec5SDimitry Andric   {
35480b57cec5SDimitry Andric     // C++11 [expr.prim.general]p3:
35490b57cec5SDimitry Andric     //   If a declaration declares a member function or member function
35500b57cec5SDimitry Andric     //   template of a class X, the expression this is a prvalue of type
35510b57cec5SDimitry Andric     //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
35520b57cec5SDimitry Andric     //   and the end of the function-definition, member-declarator, or
35530b57cec5SDimitry Andric     //   declarator.
35540b57cec5SDimitry Andric     Qualifiers ThisTypeQuals;
35550b57cec5SDimitry Andric     CXXRecordDecl *ThisContext = nullptr;
35560b57cec5SDimitry Andric     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
35570b57cec5SDimitry Andric       ThisContext = Method->getParent();
35580b57cec5SDimitry Andric       ThisTypeQuals = Method->getMethodQualifiers();
35590b57cec5SDimitry Andric     }
35600b57cec5SDimitry Andric 
35610b57cec5SDimitry Andric     CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
35620b57cec5SDimitry Andric                                getLangOpts().CPlusPlus11);
35630b57cec5SDimitry Andric 
35640b57cec5SDimitry Andric     ResultType =
3565bdd1243dSDimitry Andric         SubstType(Proto->getReturnType(), MLTAL,
35660b57cec5SDimitry Andric                   Function->getTypeSpecStartLoc(), Function->getDeclName());
35670b57cec5SDimitry Andric     if (ResultType.isNull() || Trap.hasErrorOccurred())
3568*0fca6ea1SDimitry Andric       return TemplateDeductionResult::SubstitutionFailure;
3569a7dea167SDimitry Andric     // CUDA: Kernel function must have 'void' return type.
3570a7dea167SDimitry Andric     if (getLangOpts().CUDA)
3571a7dea167SDimitry Andric       if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3572a7dea167SDimitry Andric         Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3573a7dea167SDimitry Andric             << Function->getType() << Function->getSourceRange();
3574*0fca6ea1SDimitry Andric         return TemplateDeductionResult::SubstitutionFailure;
3575a7dea167SDimitry Andric       }
35760b57cec5SDimitry Andric   }
35770b57cec5SDimitry Andric 
35780b57cec5SDimitry Andric   // Instantiate the types of each of the function parameters given the
35790b57cec5SDimitry Andric   // explicitly-specified template arguments if we didn't do so earlier.
35800b57cec5SDimitry Andric   if (!Proto->hasTrailingReturn() &&
35810b57cec5SDimitry Andric       SubstParmTypes(Function->getLocation(), Function->parameters(),
3582bdd1243dSDimitry Andric                      Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3583bdd1243dSDimitry Andric                      /*params*/ nullptr, ExtParamInfos))
3584*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
35850b57cec5SDimitry Andric 
35860b57cec5SDimitry Andric   if (FunctionType) {
35870b57cec5SDimitry Andric     auto EPI = Proto->getExtProtoInfo();
35880b57cec5SDimitry Andric     EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
35890b57cec5SDimitry Andric     *FunctionType = BuildFunctionType(ResultType, ParamTypes,
35900b57cec5SDimitry Andric                                       Function->getLocation(),
35910b57cec5SDimitry Andric                                       Function->getDeclName(),
35920b57cec5SDimitry Andric                                       EPI);
35930b57cec5SDimitry Andric     if (FunctionType->isNull() || Trap.hasErrorOccurred())
3594*0fca6ea1SDimitry Andric       return TemplateDeductionResult::SubstitutionFailure;
35950b57cec5SDimitry Andric   }
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric   // C++ [temp.arg.explicit]p2:
35980b57cec5SDimitry Andric   //   Trailing template arguments that can be deduced (14.8.2) may be
35990b57cec5SDimitry Andric   //   omitted from the list of explicit template-arguments. If all of the
36000b57cec5SDimitry Andric   //   template arguments can be deduced, they may all be omitted; in this
36010b57cec5SDimitry Andric   //   case, the empty template argument list <> itself may also be omitted.
36020b57cec5SDimitry Andric   //
36030b57cec5SDimitry Andric   // Take all of the explicitly-specified arguments and put them into
36040b57cec5SDimitry Andric   // the set of deduced template arguments. The partially-substituted
36050b57cec5SDimitry Andric   // parameter pack, however, will be set to NULL since the deduction
36060b57cec5SDimitry Andric   // mechanism handles the partially-substituted argument pack directly.
36070b57cec5SDimitry Andric   Deduced.reserve(TemplateParams->size());
3608bdd1243dSDimitry Andric   for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3609bdd1243dSDimitry Andric     const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
36100b57cec5SDimitry Andric     if (I == PartiallySubstitutedPackIndex)
36110b57cec5SDimitry Andric       Deduced.push_back(DeducedTemplateArgument());
36120b57cec5SDimitry Andric     else
36130b57cec5SDimitry Andric       Deduced.push_back(Arg);
36140b57cec5SDimitry Andric   }
36150b57cec5SDimitry Andric 
3616*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
36170b57cec5SDimitry Andric }
36180b57cec5SDimitry Andric 
36190b57cec5SDimitry Andric /// Check whether the deduced argument type for a call to a function
36200b57cec5SDimitry Andric /// template matches the actual argument type per C++ [temp.deduct.call]p4.
3621*0fca6ea1SDimitry Andric static TemplateDeductionResult
CheckOriginalCallArgDeduction(Sema & S,TemplateDeductionInfo & Info,Sema::OriginalCallArg OriginalArg,QualType DeducedA)36220b57cec5SDimitry Andric CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
36230b57cec5SDimitry Andric                               Sema::OriginalCallArg OriginalArg,
36240b57cec5SDimitry Andric                               QualType DeducedA) {
36250b57cec5SDimitry Andric   ASTContext &Context = S.Context;
36260b57cec5SDimitry Andric 
3627*0fca6ea1SDimitry Andric   auto Failed = [&]() -> TemplateDeductionResult {
36280b57cec5SDimitry Andric     Info.FirstArg = TemplateArgument(DeducedA);
36290b57cec5SDimitry Andric     Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
36300b57cec5SDimitry Andric     Info.CallArgIndex = OriginalArg.ArgIdx;
3631*0fca6ea1SDimitry Andric     return OriginalArg.DecomposedParam
3632*0fca6ea1SDimitry Andric                ? TemplateDeductionResult::DeducedMismatchNested
3633*0fca6ea1SDimitry Andric                : TemplateDeductionResult::DeducedMismatch;
36340b57cec5SDimitry Andric   };
36350b57cec5SDimitry Andric 
36360b57cec5SDimitry Andric   QualType A = OriginalArg.OriginalArgType;
36370b57cec5SDimitry Andric   QualType OriginalParamType = OriginalArg.OriginalParamType;
36380b57cec5SDimitry Andric 
36390b57cec5SDimitry Andric   // Check for type equality (top-level cv-qualifiers are ignored).
36400b57cec5SDimitry Andric   if (Context.hasSameUnqualifiedType(A, DeducedA))
3641*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric   // Strip off references on the argument types; they aren't needed for
36440b57cec5SDimitry Andric   // the following checks.
36450b57cec5SDimitry Andric   if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
36460b57cec5SDimitry Andric     DeducedA = DeducedARef->getPointeeType();
36470b57cec5SDimitry Andric   if (const ReferenceType *ARef = A->getAs<ReferenceType>())
36480b57cec5SDimitry Andric     A = ARef->getPointeeType();
36490b57cec5SDimitry Andric 
36500b57cec5SDimitry Andric   // C++ [temp.deduct.call]p4:
36510b57cec5SDimitry Andric   //   [...] However, there are three cases that allow a difference:
36520b57cec5SDimitry Andric   //     - If the original P is a reference type, the deduced A (i.e., the
36530b57cec5SDimitry Andric   //       type referred to by the reference) can be more cv-qualified than
36540b57cec5SDimitry Andric   //       the transformed A.
36550b57cec5SDimitry Andric   if (const ReferenceType *OriginalParamRef
36560b57cec5SDimitry Andric       = OriginalParamType->getAs<ReferenceType>()) {
36570b57cec5SDimitry Andric     // We don't want to keep the reference around any more.
36580b57cec5SDimitry Andric     OriginalParamType = OriginalParamRef->getPointeeType();
36590b57cec5SDimitry Andric 
36600b57cec5SDimitry Andric     // FIXME: Resolve core issue (no number yet): if the original P is a
36610b57cec5SDimitry Andric     // reference type and the transformed A is function type "noexcept F",
36620b57cec5SDimitry Andric     // the deduced A can be F.
36630b57cec5SDimitry Andric     QualType Tmp;
36640b57cec5SDimitry Andric     if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3665*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
36660b57cec5SDimitry Andric 
36670b57cec5SDimitry Andric     Qualifiers AQuals = A.getQualifiers();
36680b57cec5SDimitry Andric     Qualifiers DeducedAQuals = DeducedA.getQualifiers();
36690b57cec5SDimitry Andric 
36700b57cec5SDimitry Andric     // Under Objective-C++ ARC, the deduced type may have implicitly
36710b57cec5SDimitry Andric     // been given strong or (when dealing with a const reference)
36720b57cec5SDimitry Andric     // unsafe_unretained lifetime. If so, update the original
36730b57cec5SDimitry Andric     // qualifiers to include this lifetime.
36740b57cec5SDimitry Andric     if (S.getLangOpts().ObjCAutoRefCount &&
36750b57cec5SDimitry Andric         ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
36760b57cec5SDimitry Andric           AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
36770b57cec5SDimitry Andric          (DeducedAQuals.hasConst() &&
36780b57cec5SDimitry Andric           DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
36790b57cec5SDimitry Andric       AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
36800b57cec5SDimitry Andric     }
36810b57cec5SDimitry Andric 
36820b57cec5SDimitry Andric     if (AQuals == DeducedAQuals) {
36830b57cec5SDimitry Andric       // Qualifiers match; there's nothing to do.
36840b57cec5SDimitry Andric     } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
36850b57cec5SDimitry Andric       return Failed();
36860b57cec5SDimitry Andric     } else {
36870b57cec5SDimitry Andric       // Qualifiers are compatible, so have the argument type adopt the
36880b57cec5SDimitry Andric       // deduced argument type's qualifiers as if we had performed the
36890b57cec5SDimitry Andric       // qualification conversion.
36900b57cec5SDimitry Andric       A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
36910b57cec5SDimitry Andric     }
36920b57cec5SDimitry Andric   }
36930b57cec5SDimitry Andric 
36940b57cec5SDimitry Andric   //    - The transformed A can be another pointer or pointer to member
36950b57cec5SDimitry Andric   //      type that can be converted to the deduced A via a function pointer
36960b57cec5SDimitry Andric   //      conversion and/or a qualification conversion.
36970b57cec5SDimitry Andric   //
36980b57cec5SDimitry Andric   // Also allow conversions which merely strip __attribute__((noreturn)) from
36990b57cec5SDimitry Andric   // function types (recursively).
37000b57cec5SDimitry Andric   bool ObjCLifetimeConversion = false;
37010b57cec5SDimitry Andric   QualType ResultTy;
37020b57cec5SDimitry Andric   if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
37030b57cec5SDimitry Andric       (S.IsQualificationConversion(A, DeducedA, false,
37040b57cec5SDimitry Andric                                    ObjCLifetimeConversion) ||
37050b57cec5SDimitry Andric        S.IsFunctionConversion(A, DeducedA, ResultTy)))
3706*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
37070b57cec5SDimitry Andric 
37080b57cec5SDimitry Andric   //    - If P is a class and P has the form simple-template-id, then the
37090b57cec5SDimitry Andric   //      transformed A can be a derived class of the deduced A. [...]
37100b57cec5SDimitry Andric   //     [...] Likewise, if P is a pointer to a class of the form
37110b57cec5SDimitry Andric   //      simple-template-id, the transformed A can be a pointer to a
37120b57cec5SDimitry Andric   //      derived class pointed to by the deduced A.
37130b57cec5SDimitry Andric   if (const PointerType *OriginalParamPtr
37140b57cec5SDimitry Andric       = OriginalParamType->getAs<PointerType>()) {
37150b57cec5SDimitry Andric     if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
37160b57cec5SDimitry Andric       if (const PointerType *APtr = A->getAs<PointerType>()) {
37170b57cec5SDimitry Andric         if (A->getPointeeType()->isRecordType()) {
37180b57cec5SDimitry Andric           OriginalParamType = OriginalParamPtr->getPointeeType();
37190b57cec5SDimitry Andric           DeducedA = DeducedAPtr->getPointeeType();
37200b57cec5SDimitry Andric           A = APtr->getPointeeType();
37210b57cec5SDimitry Andric         }
37220b57cec5SDimitry Andric       }
37230b57cec5SDimitry Andric     }
37240b57cec5SDimitry Andric   }
37250b57cec5SDimitry Andric 
37260b57cec5SDimitry Andric   if (Context.hasSameUnqualifiedType(A, DeducedA))
3727*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
37280b57cec5SDimitry Andric 
37290b57cec5SDimitry Andric   if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
37300b57cec5SDimitry Andric       S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3731*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
37320b57cec5SDimitry Andric 
37330b57cec5SDimitry Andric   return Failed();
37340b57cec5SDimitry Andric }
37350b57cec5SDimitry Andric 
37360b57cec5SDimitry Andric /// Find the pack index for a particular parameter index in an instantiation of
37370b57cec5SDimitry Andric /// a function template with specific arguments.
37380b57cec5SDimitry Andric ///
37390b57cec5SDimitry Andric /// \return The pack index for whichever pack produced this parameter, or -1
37400b57cec5SDimitry Andric ///         if this was not produced by a parameter. Intended to be used as the
37410b57cec5SDimitry Andric ///         ArgumentPackSubstitutionIndex for further substitutions.
37420b57cec5SDimitry Andric // FIXME: We should track this in OriginalCallArgs so we don't need to
37430b57cec5SDimitry Andric // reconstruct it here.
getPackIndexForParam(Sema & S,FunctionTemplateDecl * FunctionTemplate,const MultiLevelTemplateArgumentList & Args,unsigned ParamIdx)37440b57cec5SDimitry Andric static unsigned getPackIndexForParam(Sema &S,
37450b57cec5SDimitry Andric                                      FunctionTemplateDecl *FunctionTemplate,
37460b57cec5SDimitry Andric                                      const MultiLevelTemplateArgumentList &Args,
37470b57cec5SDimitry Andric                                      unsigned ParamIdx) {
37480b57cec5SDimitry Andric   unsigned Idx = 0;
37490b57cec5SDimitry Andric   for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
37500b57cec5SDimitry Andric     if (PD->isParameterPack()) {
37510b57cec5SDimitry Andric       unsigned NumExpansions =
375281ad6265SDimitry Andric           S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
37530b57cec5SDimitry Andric       if (Idx + NumExpansions > ParamIdx)
37540b57cec5SDimitry Andric         return ParamIdx - Idx;
37550b57cec5SDimitry Andric       Idx += NumExpansions;
37560b57cec5SDimitry Andric     } else {
37570b57cec5SDimitry Andric       if (Idx == ParamIdx)
37580b57cec5SDimitry Andric         return -1; // Not a pack expansion
37590b57cec5SDimitry Andric       ++Idx;
37600b57cec5SDimitry Andric     }
37610b57cec5SDimitry Andric   }
37620b57cec5SDimitry Andric 
37630b57cec5SDimitry Andric   llvm_unreachable("parameter index would not be produced from template");
37640b57cec5SDimitry Andric }
37650b57cec5SDimitry Andric 
37665f757f3fSDimitry Andric // if `Specialization` is a `CXXConstructorDecl` or `CXXConversionDecl`,
37675f757f3fSDimitry Andric // we'll try to instantiate and update its explicit specifier after constraint
37685f757f3fSDimitry Andric // checking.
instantiateExplicitSpecifierDeferred(Sema & S,FunctionDecl * Specialization,const MultiLevelTemplateArgumentList & SubstArgs,TemplateDeductionInfo & Info,FunctionTemplateDecl * FunctionTemplate,ArrayRef<TemplateArgument> DeducedArgs)3769*0fca6ea1SDimitry Andric static TemplateDeductionResult instantiateExplicitSpecifierDeferred(
37705f757f3fSDimitry Andric     Sema &S, FunctionDecl *Specialization,
37715f757f3fSDimitry Andric     const MultiLevelTemplateArgumentList &SubstArgs,
37725f757f3fSDimitry Andric     TemplateDeductionInfo &Info, FunctionTemplateDecl *FunctionTemplate,
37735f757f3fSDimitry Andric     ArrayRef<TemplateArgument> DeducedArgs) {
37745f757f3fSDimitry Andric   auto GetExplicitSpecifier = [](FunctionDecl *D) {
37755f757f3fSDimitry Andric     return isa<CXXConstructorDecl>(D)
37765f757f3fSDimitry Andric                ? cast<CXXConstructorDecl>(D)->getExplicitSpecifier()
37775f757f3fSDimitry Andric                : cast<CXXConversionDecl>(D)->getExplicitSpecifier();
37785f757f3fSDimitry Andric   };
37795f757f3fSDimitry Andric   auto SetExplicitSpecifier = [](FunctionDecl *D, ExplicitSpecifier ES) {
37805f757f3fSDimitry Andric     isa<CXXConstructorDecl>(D)
37815f757f3fSDimitry Andric         ? cast<CXXConstructorDecl>(D)->setExplicitSpecifier(ES)
37825f757f3fSDimitry Andric         : cast<CXXConversionDecl>(D)->setExplicitSpecifier(ES);
37835f757f3fSDimitry Andric   };
37845f757f3fSDimitry Andric 
37855f757f3fSDimitry Andric   ExplicitSpecifier ES = GetExplicitSpecifier(Specialization);
37865f757f3fSDimitry Andric   Expr *ExplicitExpr = ES.getExpr();
37875f757f3fSDimitry Andric   if (!ExplicitExpr)
3788*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
37895f757f3fSDimitry Andric   if (!ExplicitExpr->isValueDependent())
3790*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
37915f757f3fSDimitry Andric 
37925f757f3fSDimitry Andric   Sema::InstantiatingTemplate Inst(
37935f757f3fSDimitry Andric       S, Info.getLocation(), FunctionTemplate, DeducedArgs,
37945f757f3fSDimitry Andric       Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
37955f757f3fSDimitry Andric   if (Inst.isInvalid())
3796*0fca6ea1SDimitry Andric     return TemplateDeductionResult::InstantiationDepth;
37975f757f3fSDimitry Andric   Sema::SFINAETrap Trap(S);
37985f757f3fSDimitry Andric   const ExplicitSpecifier InstantiatedES =
37995f757f3fSDimitry Andric       S.instantiateExplicitSpecifier(SubstArgs, ES);
38005f757f3fSDimitry Andric   if (InstantiatedES.isInvalid() || Trap.hasErrorOccurred()) {
38015f757f3fSDimitry Andric     Specialization->setInvalidDecl(true);
3802*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
38035f757f3fSDimitry Andric   }
38045f757f3fSDimitry Andric   SetExplicitSpecifier(Specialization, InstantiatedES);
3805*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
38065f757f3fSDimitry Andric }
38075f757f3fSDimitry Andric 
FinishTemplateArgumentDeduction(FunctionTemplateDecl * FunctionTemplate,SmallVectorImpl<DeducedTemplateArgument> & Deduced,unsigned NumExplicitlySpecified,FunctionDecl * & Specialization,TemplateDeductionInfo & Info,SmallVectorImpl<OriginalCallArg> const * OriginalCallArgs,bool PartialOverloading,llvm::function_ref<bool ()> CheckNonDependent)3808*0fca6ea1SDimitry Andric TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
38090b57cec5SDimitry Andric     FunctionTemplateDecl *FunctionTemplate,
38100b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
38110b57cec5SDimitry Andric     unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
38120b57cec5SDimitry Andric     TemplateDeductionInfo &Info,
38130b57cec5SDimitry Andric     SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
38140b57cec5SDimitry Andric     bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
38150b57cec5SDimitry Andric   // Unevaluated SFINAE context.
38160b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
38170b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
38180b57cec5SDimitry Andric   SFINAETrap Trap(*this);
38190b57cec5SDimitry Andric 
38200b57cec5SDimitry Andric   // Enter a new template instantiation context while we instantiate the
38210b57cec5SDimitry Andric   // actual function declaration.
38220b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
38230b57cec5SDimitry Andric   InstantiatingTemplate Inst(
38240b57cec5SDimitry Andric       *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
38250b57cec5SDimitry Andric       CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
38260b57cec5SDimitry Andric   if (Inst.isInvalid())
3827*0fca6ea1SDimitry Andric     return TemplateDeductionResult::InstantiationDepth;
38280b57cec5SDimitry Andric 
38290b57cec5SDimitry Andric   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
38300b57cec5SDimitry Andric 
38310b57cec5SDimitry Andric   // C++ [temp.deduct.type]p2:
38320b57cec5SDimitry Andric   //   [...] or if any template argument remains neither deduced nor
38330b57cec5SDimitry Andric   //   explicitly specified, template argument deduction fails.
3834bdd1243dSDimitry Andric   SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
38350b57cec5SDimitry Andric   if (auto Result = ConvertDeducedTemplateArguments(
3836bdd1243dSDimitry Andric           *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3837bdd1243dSDimitry Andric           SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3838*0fca6ea1SDimitry Andric           NumExplicitlySpecified, PartialOverloading);
3839*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
38400b57cec5SDimitry Andric     return Result;
38410b57cec5SDimitry Andric 
38420b57cec5SDimitry Andric   // C++ [temp.deduct.call]p10: [DR1391]
38430b57cec5SDimitry Andric   //   If deduction succeeds for all parameters that contain
38440b57cec5SDimitry Andric   //   template-parameters that participate in template argument deduction,
38450b57cec5SDimitry Andric   //   and all template arguments are explicitly specified, deduced, or
38460b57cec5SDimitry Andric   //   obtained from default template arguments, remaining parameters are then
38470b57cec5SDimitry Andric   //   compared with the corresponding arguments. For each remaining parameter
38480b57cec5SDimitry Andric   //   P with a type that was non-dependent before substitution of any
38490b57cec5SDimitry Andric   //   explicitly-specified template arguments, if the corresponding argument
38500b57cec5SDimitry Andric   //   A cannot be implicitly converted to P, deduction fails.
38510b57cec5SDimitry Andric   if (CheckNonDependent())
3852*0fca6ea1SDimitry Andric     return TemplateDeductionResult::NonDependentConversionFailure;
38530b57cec5SDimitry Andric 
38540b57cec5SDimitry Andric   // Form the template argument list from the deduced template arguments.
3855bdd1243dSDimitry Andric   TemplateArgumentList *SugaredDeducedArgumentList =
3856bdd1243dSDimitry Andric       TemplateArgumentList::CreateCopy(Context, SugaredBuilder);
3857bdd1243dSDimitry Andric   TemplateArgumentList *CanonicalDeducedArgumentList =
3858bdd1243dSDimitry Andric       TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3859bdd1243dSDimitry Andric   Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
38600b57cec5SDimitry Andric 
38610b57cec5SDimitry Andric   // Substitute the deduced template arguments into the function template
38620b57cec5SDimitry Andric   // declaration to produce the function template specialization.
38630b57cec5SDimitry Andric   DeclContext *Owner = FunctionTemplate->getDeclContext();
38640b57cec5SDimitry Andric   if (FunctionTemplate->getFriendObjectKind())
38650b57cec5SDimitry Andric     Owner = FunctionTemplate->getLexicalDeclContext();
386606c3fb27SDimitry Andric   FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
386706c3fb27SDimitry Andric   // additional check for inline friend,
386806c3fb27SDimitry Andric   // ```
386906c3fb27SDimitry Andric   //   template <class F1> int foo(F1 X);
387006c3fb27SDimitry Andric   //   template <int A1> struct A {
387106c3fb27SDimitry Andric   //     template <class F1> friend int foo(F1 X) { return A1; }
387206c3fb27SDimitry Andric   //   };
387306c3fb27SDimitry Andric   //   template struct A<1>;
387406c3fb27SDimitry Andric   //   int a = foo(1.0);
387506c3fb27SDimitry Andric   // ```
387606c3fb27SDimitry Andric   const FunctionDecl *FDFriend;
387706c3fb27SDimitry Andric   if (FD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None &&
387806c3fb27SDimitry Andric       FD->isDefined(FDFriend, /*CheckForPendingFriendDefinition*/ true) &&
387906c3fb27SDimitry Andric       FDFriend->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None) {
388006c3fb27SDimitry Andric     FD = const_cast<FunctionDecl *>(FDFriend);
388106c3fb27SDimitry Andric     Owner = FD->getLexicalDeclContext();
388206c3fb27SDimitry Andric   }
3883bdd1243dSDimitry Andric   MultiLevelTemplateArgumentList SubstArgs(
3884bdd1243dSDimitry Andric       FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3885bdd1243dSDimitry Andric       /*Final=*/false);
38860b57cec5SDimitry Andric   Specialization = cast_or_null<FunctionDecl>(
388706c3fb27SDimitry Andric       SubstDecl(FD, Owner, SubstArgs));
38880b57cec5SDimitry Andric   if (!Specialization || Specialization->isInvalidDecl())
3889*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
38900b57cec5SDimitry Andric 
38910b57cec5SDimitry Andric   assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
38920b57cec5SDimitry Andric          FunctionTemplate->getCanonicalDecl());
38930b57cec5SDimitry Andric 
38940b57cec5SDimitry Andric   // If the template argument list is owned by the function template
38950b57cec5SDimitry Andric   // specialization, release it.
3896bdd1243dSDimitry Andric   if (Specialization->getTemplateSpecializationArgs() ==
3897bdd1243dSDimitry Andric           CanonicalDeducedArgumentList &&
38980b57cec5SDimitry Andric       !Trap.hasErrorOccurred())
3899bdd1243dSDimitry Andric     Info.takeCanonical();
39000b57cec5SDimitry Andric 
39010b57cec5SDimitry Andric   // There may have been an error that did not prevent us from constructing a
39020b57cec5SDimitry Andric   // declaration. Mark the declaration invalid and return with a substitution
39030b57cec5SDimitry Andric   // failure.
39040b57cec5SDimitry Andric   if (Trap.hasErrorOccurred()) {
39050b57cec5SDimitry Andric     Specialization->setInvalidDecl(true);
3906*0fca6ea1SDimitry Andric     return TemplateDeductionResult::SubstitutionFailure;
39070b57cec5SDimitry Andric   }
39080b57cec5SDimitry Andric 
3909480093f4SDimitry Andric   // C++2a [temp.deduct]p5
3910480093f4SDimitry Andric   //   [...] When all template arguments have been deduced [...] all uses of
3911480093f4SDimitry Andric   //   template parameters [...] are replaced with the corresponding deduced
3912480093f4SDimitry Andric   //   or default argument values.
3913480093f4SDimitry Andric   //   [...] If the function template has associated constraints
3914480093f4SDimitry Andric   //   ([temp.constr.decl]), those constraints are checked for satisfaction
3915480093f4SDimitry Andric   //   ([temp.constr.constr]). If the constraints are not satisfied, type
3916480093f4SDimitry Andric   //   deduction fails.
391713138422SDimitry Andric   if (!PartialOverloading ||
3918bdd1243dSDimitry Andric       (CanonicalBuilder.size() ==
3919bdd1243dSDimitry Andric        FunctionTemplate->getTemplateParameters()->size())) {
3920bdd1243dSDimitry Andric     if (CheckInstantiatedFunctionTemplateConstraints(
3921bdd1243dSDimitry Andric             Info.getLocation(), Specialization, CanonicalBuilder,
3922bdd1243dSDimitry Andric             Info.AssociatedConstraintsSatisfaction))
3923*0fca6ea1SDimitry Andric       return TemplateDeductionResult::MiscellaneousDeductionFailure;
3924480093f4SDimitry Andric 
3925480093f4SDimitry Andric     if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
3926bdd1243dSDimitry Andric       Info.reset(Info.takeSugared(),
3927bdd1243dSDimitry Andric                  TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
3928*0fca6ea1SDimitry Andric       return TemplateDeductionResult::ConstraintsNotSatisfied;
3929480093f4SDimitry Andric     }
393013138422SDimitry Andric   }
3931480093f4SDimitry Andric 
39325f757f3fSDimitry Andric   // We skipped the instantiation of the explicit-specifier during the
39335f757f3fSDimitry Andric   // substitution of `FD` before. So, we try to instantiate it back if
39345f757f3fSDimitry Andric   // `Specialization` is either a constructor or a conversion function.
39355f757f3fSDimitry Andric   if (isa<CXXConstructorDecl, CXXConversionDecl>(Specialization)) {
3936*0fca6ea1SDimitry Andric     if (TemplateDeductionResult::Success !=
3937*0fca6ea1SDimitry Andric         instantiateExplicitSpecifierDeferred(*this, Specialization, SubstArgs,
3938*0fca6ea1SDimitry Andric                                              Info, FunctionTemplate,
3939*0fca6ea1SDimitry Andric                                              DeducedArgs)) {
3940*0fca6ea1SDimitry Andric       return TemplateDeductionResult::SubstitutionFailure;
39415f757f3fSDimitry Andric     }
39425f757f3fSDimitry Andric   }
39435f757f3fSDimitry Andric 
39440b57cec5SDimitry Andric   if (OriginalCallArgs) {
39450b57cec5SDimitry Andric     // C++ [temp.deduct.call]p4:
39460b57cec5SDimitry Andric     //   In general, the deduction process attempts to find template argument
39470b57cec5SDimitry Andric     //   values that will make the deduced A identical to A (after the type A
39480b57cec5SDimitry Andric     //   is transformed as described above). [...]
39490b57cec5SDimitry Andric     llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
39500b57cec5SDimitry Andric     for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
39510b57cec5SDimitry Andric       OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
39520b57cec5SDimitry Andric 
39530b57cec5SDimitry Andric       auto ParamIdx = OriginalArg.ArgIdx;
39545f757f3fSDimitry Andric       unsigned ExplicitOffset =
39555f757f3fSDimitry Andric           Specialization->hasCXXExplicitFunctionObjectParameter() ? 1 : 0;
39565f757f3fSDimitry Andric       if (ParamIdx >= Specialization->getNumParams() - ExplicitOffset)
39570b57cec5SDimitry Andric         // FIXME: This presumably means a pack ended up smaller than we
39580b57cec5SDimitry Andric         // expected while deducing. Should this not result in deduction
39590b57cec5SDimitry Andric         // failure? Can it even happen?
39600b57cec5SDimitry Andric         continue;
39610b57cec5SDimitry Andric 
39620b57cec5SDimitry Andric       QualType DeducedA;
39630b57cec5SDimitry Andric       if (!OriginalArg.DecomposedParam) {
39640b57cec5SDimitry Andric         // P is one of the function parameters, just look up its substituted
39650b57cec5SDimitry Andric         // type.
39665f757f3fSDimitry Andric         DeducedA =
39675f757f3fSDimitry Andric             Specialization->getParamDecl(ParamIdx + ExplicitOffset)->getType();
39680b57cec5SDimitry Andric       } else {
39690b57cec5SDimitry Andric         // P is a decomposed element of a parameter corresponding to a
39700b57cec5SDimitry Andric         // braced-init-list argument. Substitute back into P to find the
39710b57cec5SDimitry Andric         // deduced A.
39720b57cec5SDimitry Andric         QualType &CacheEntry =
39730b57cec5SDimitry Andric             DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
39740b57cec5SDimitry Andric         if (CacheEntry.isNull()) {
39750b57cec5SDimitry Andric           ArgumentPackSubstitutionIndexRAII PackIndex(
39760b57cec5SDimitry Andric               *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
39770b57cec5SDimitry Andric                                           ParamIdx));
39780b57cec5SDimitry Andric           CacheEntry =
39790b57cec5SDimitry Andric               SubstType(OriginalArg.OriginalParamType, SubstArgs,
39800b57cec5SDimitry Andric                         Specialization->getTypeSpecStartLoc(),
39810b57cec5SDimitry Andric                         Specialization->getDeclName());
39820b57cec5SDimitry Andric         }
39830b57cec5SDimitry Andric         DeducedA = CacheEntry;
39840b57cec5SDimitry Andric       }
39850b57cec5SDimitry Andric 
39860b57cec5SDimitry Andric       if (auto TDK =
3987*0fca6ea1SDimitry Andric               CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
3988*0fca6ea1SDimitry Andric           TDK != TemplateDeductionResult::Success)
39890b57cec5SDimitry Andric         return TDK;
39900b57cec5SDimitry Andric     }
39910b57cec5SDimitry Andric   }
39920b57cec5SDimitry Andric 
39930b57cec5SDimitry Andric   // If we suppressed any diagnostics while performing template argument
39940b57cec5SDimitry Andric   // deduction, and if we haven't already instantiated this declaration,
39950b57cec5SDimitry Andric   // keep track of these diagnostics. They'll be emitted if this specialization
39960b57cec5SDimitry Andric   // is actually used.
39970b57cec5SDimitry Andric   if (Info.diag_begin() != Info.diag_end()) {
39980b57cec5SDimitry Andric     SuppressedDiagnosticsMap::iterator
39990b57cec5SDimitry Andric       Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
40000b57cec5SDimitry Andric     if (Pos == SuppressedDiagnostics.end())
40010b57cec5SDimitry Andric         SuppressedDiagnostics[Specialization->getCanonicalDecl()]
40020b57cec5SDimitry Andric           .append(Info.diag_begin(), Info.diag_end());
40030b57cec5SDimitry Andric   }
40040b57cec5SDimitry Andric 
4005*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
40060b57cec5SDimitry Andric }
40070b57cec5SDimitry Andric 
40080b57cec5SDimitry Andric /// Gets the type of a function for template-argument-deducton
40090b57cec5SDimitry Andric /// purposes when it's considered as part of an overload set.
GetTypeOfFunction(Sema & S,const OverloadExpr::FindResult & R,FunctionDecl * Fn)40100b57cec5SDimitry Andric static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
40110b57cec5SDimitry Andric                                   FunctionDecl *Fn) {
40120b57cec5SDimitry Andric   // We may need to deduce the return type of the function now.
40130b57cec5SDimitry Andric   if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
40140b57cec5SDimitry Andric       S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
40150b57cec5SDimitry Andric     return {};
40160b57cec5SDimitry Andric 
40170b57cec5SDimitry Andric   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
40185f757f3fSDimitry Andric     if (Method->isImplicitObjectMemberFunction()) {
40190b57cec5SDimitry Andric       // An instance method that's referenced in a form that doesn't
40200b57cec5SDimitry Andric       // look like a member pointer is just invalid.
40210b57cec5SDimitry Andric       if (!R.HasFormOfMemberPointer)
40220b57cec5SDimitry Andric         return {};
40230b57cec5SDimitry Andric 
40240b57cec5SDimitry Andric       return S.Context.getMemberPointerType(Fn->getType(),
40250b57cec5SDimitry Andric                S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
40260b57cec5SDimitry Andric     }
40270b57cec5SDimitry Andric 
40280b57cec5SDimitry Andric   if (!R.IsAddressOfOperand) return Fn->getType();
40290b57cec5SDimitry Andric   return S.Context.getPointerType(Fn->getType());
40300b57cec5SDimitry Andric }
40310b57cec5SDimitry Andric 
40320b57cec5SDimitry Andric /// Apply the deduction rules for overload sets.
40330b57cec5SDimitry Andric ///
40340b57cec5SDimitry Andric /// \return the null type if this argument should be treated as an
40350b57cec5SDimitry Andric /// undeduced context
40360b57cec5SDimitry Andric static QualType
ResolveOverloadForDeduction(Sema & S,TemplateParameterList * TemplateParams,Expr * Arg,QualType ParamType,bool ParamWasReference,TemplateSpecCandidateSet * FailedTSC=nullptr)40370b57cec5SDimitry Andric ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
40380b57cec5SDimitry Andric                             Expr *Arg, QualType ParamType,
403906c3fb27SDimitry Andric                             bool ParamWasReference,
404006c3fb27SDimitry Andric                             TemplateSpecCandidateSet *FailedTSC = nullptr) {
40410b57cec5SDimitry Andric 
40420b57cec5SDimitry Andric   OverloadExpr::FindResult R = OverloadExpr::find(Arg);
40430b57cec5SDimitry Andric 
40440b57cec5SDimitry Andric   OverloadExpr *Ovl = R.Expression;
40450b57cec5SDimitry Andric 
40460b57cec5SDimitry Andric   // C++0x [temp.deduct.call]p4
40470b57cec5SDimitry Andric   unsigned TDF = 0;
40480b57cec5SDimitry Andric   if (ParamWasReference)
40490b57cec5SDimitry Andric     TDF |= TDF_ParamWithReferenceType;
40500b57cec5SDimitry Andric   if (R.IsAddressOfOperand)
40510b57cec5SDimitry Andric     TDF |= TDF_IgnoreQualifiers;
40520b57cec5SDimitry Andric 
40530b57cec5SDimitry Andric   // C++0x [temp.deduct.call]p6:
40540b57cec5SDimitry Andric   //   When P is a function type, pointer to function type, or pointer
40550b57cec5SDimitry Andric   //   to member function type:
40560b57cec5SDimitry Andric 
40570b57cec5SDimitry Andric   if (!ParamType->isFunctionType() &&
40580b57cec5SDimitry Andric       !ParamType->isFunctionPointerType() &&
40590b57cec5SDimitry Andric       !ParamType->isMemberFunctionPointerType()) {
40600b57cec5SDimitry Andric     if (Ovl->hasExplicitTemplateArgs()) {
40610b57cec5SDimitry Andric       // But we can still look for an explicit specialization.
406206c3fb27SDimitry Andric       if (FunctionDecl *ExplicitSpec =
406306c3fb27SDimitry Andric               S.ResolveSingleFunctionTemplateSpecialization(
406406c3fb27SDimitry Andric                   Ovl, /*Complain=*/false,
406506c3fb27SDimitry Andric                   /*FoundDeclAccessPair=*/nullptr, FailedTSC))
40660b57cec5SDimitry Andric         return GetTypeOfFunction(S, R, ExplicitSpec);
40670b57cec5SDimitry Andric     }
40680b57cec5SDimitry Andric 
40690b57cec5SDimitry Andric     DeclAccessPair DAP;
40700b57cec5SDimitry Andric     if (FunctionDecl *Viable =
4071480093f4SDimitry Andric             S.resolveAddressOfSingleOverloadCandidate(Arg, DAP))
40720b57cec5SDimitry Andric       return GetTypeOfFunction(S, R, Viable);
40730b57cec5SDimitry Andric 
40740b57cec5SDimitry Andric     return {};
40750b57cec5SDimitry Andric   }
40760b57cec5SDimitry Andric 
40770b57cec5SDimitry Andric   // Gather the explicit template arguments, if any.
40780b57cec5SDimitry Andric   TemplateArgumentListInfo ExplicitTemplateArgs;
40790b57cec5SDimitry Andric   if (Ovl->hasExplicitTemplateArgs())
40800b57cec5SDimitry Andric     Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
40810b57cec5SDimitry Andric   QualType Match;
40820b57cec5SDimitry Andric   for (UnresolvedSetIterator I = Ovl->decls_begin(),
40830b57cec5SDimitry Andric          E = Ovl->decls_end(); I != E; ++I) {
40840b57cec5SDimitry Andric     NamedDecl *D = (*I)->getUnderlyingDecl();
40850b57cec5SDimitry Andric 
40860b57cec5SDimitry Andric     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
40870b57cec5SDimitry Andric       //   - If the argument is an overload set containing one or more
40880b57cec5SDimitry Andric       //     function templates, the parameter is treated as a
40890b57cec5SDimitry Andric       //     non-deduced context.
40900b57cec5SDimitry Andric       if (!Ovl->hasExplicitTemplateArgs())
40910b57cec5SDimitry Andric         return {};
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric       // Otherwise, see if we can resolve a function type
40940b57cec5SDimitry Andric       FunctionDecl *Specialization = nullptr;
40950b57cec5SDimitry Andric       TemplateDeductionInfo Info(Ovl->getNameLoc());
40960b57cec5SDimitry Andric       if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
4097*0fca6ea1SDimitry Andric                                     Specialization,
4098*0fca6ea1SDimitry Andric                                     Info) != TemplateDeductionResult::Success)
40990b57cec5SDimitry Andric         continue;
41000b57cec5SDimitry Andric 
41010b57cec5SDimitry Andric       D = Specialization;
41020b57cec5SDimitry Andric     }
41030b57cec5SDimitry Andric 
41040b57cec5SDimitry Andric     FunctionDecl *Fn = cast<FunctionDecl>(D);
41050b57cec5SDimitry Andric     QualType ArgType = GetTypeOfFunction(S, R, Fn);
41060b57cec5SDimitry Andric     if (ArgType.isNull()) continue;
41070b57cec5SDimitry Andric 
41080b57cec5SDimitry Andric     // Function-to-pointer conversion.
41090b57cec5SDimitry Andric     if (!ParamWasReference && ParamType->isPointerType() &&
41100b57cec5SDimitry Andric         ArgType->isFunctionType())
41110b57cec5SDimitry Andric       ArgType = S.Context.getPointerType(ArgType);
41120b57cec5SDimitry Andric 
41130b57cec5SDimitry Andric     //   - If the argument is an overload set (not containing function
41140b57cec5SDimitry Andric     //     templates), trial argument deduction is attempted using each
41150b57cec5SDimitry Andric     //     of the members of the set. If deduction succeeds for only one
41160b57cec5SDimitry Andric     //     of the overload set members, that member is used as the
41170b57cec5SDimitry Andric     //     argument value for the deduction. If deduction succeeds for
41180b57cec5SDimitry Andric     //     more than one member of the overload set the parameter is
41190b57cec5SDimitry Andric     //     treated as a non-deduced context.
41200b57cec5SDimitry Andric 
41210b57cec5SDimitry Andric     // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
41220b57cec5SDimitry Andric     //   Type deduction is done independently for each P/A pair, and
41230b57cec5SDimitry Andric     //   the deduced template argument values are then combined.
41240b57cec5SDimitry Andric     // So we do not reject deductions which were made elsewhere.
41250b57cec5SDimitry Andric     SmallVector<DeducedTemplateArgument, 8>
41260b57cec5SDimitry Andric       Deduced(TemplateParams->size());
41270b57cec5SDimitry Andric     TemplateDeductionInfo Info(Ovl->getNameLoc());
4128*0fca6ea1SDimitry Andric     TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch(
4129*0fca6ea1SDimitry Andric         S, TemplateParams, ParamType, ArgType, Info, Deduced, TDF);
4130*0fca6ea1SDimitry Andric     if (Result != TemplateDeductionResult::Success)
4131*0fca6ea1SDimitry Andric       continue;
41320b57cec5SDimitry Andric     if (!Match.isNull())
41330b57cec5SDimitry Andric       return {};
41340b57cec5SDimitry Andric     Match = ArgType;
41350b57cec5SDimitry Andric   }
41360b57cec5SDimitry Andric 
41370b57cec5SDimitry Andric   return Match;
41380b57cec5SDimitry Andric }
41390b57cec5SDimitry Andric 
41400b57cec5SDimitry Andric /// Perform the adjustments to the parameter and argument types
41410b57cec5SDimitry Andric /// described in C++ [temp.deduct.call].
41420b57cec5SDimitry Andric ///
41430b57cec5SDimitry Andric /// \returns true if the caller should not attempt to perform any template
41440b57cec5SDimitry Andric /// argument deduction based on this P/A pair because the argument is an
41450b57cec5SDimitry Andric /// overloaded function set that could not be resolved.
AdjustFunctionParmAndArgTypesForDeduction(Sema & S,TemplateParameterList * TemplateParams,unsigned FirstInnerIndex,QualType & ParamType,QualType & ArgType,Expr::Classification ArgClassification,Expr * Arg,unsigned & TDF,TemplateSpecCandidateSet * FailedTSC=nullptr)41460b57cec5SDimitry Andric static bool AdjustFunctionParmAndArgTypesForDeduction(
41470b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
41485f757f3fSDimitry Andric     QualType &ParamType, QualType &ArgType,
41495f757f3fSDimitry Andric     Expr::Classification ArgClassification, Expr *Arg, unsigned &TDF,
415006c3fb27SDimitry Andric     TemplateSpecCandidateSet *FailedTSC = nullptr) {
41510b57cec5SDimitry Andric   // C++0x [temp.deduct.call]p3:
41520b57cec5SDimitry Andric   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
41530b57cec5SDimitry Andric   //   are ignored for type deduction.
41540b57cec5SDimitry Andric   if (ParamType.hasQualifiers())
41550b57cec5SDimitry Andric     ParamType = ParamType.getUnqualifiedType();
41560b57cec5SDimitry Andric 
41570b57cec5SDimitry Andric   //   [...] If P is a reference type, the type referred to by P is
41580b57cec5SDimitry Andric   //   used for type deduction.
41590b57cec5SDimitry Andric   const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
41600b57cec5SDimitry Andric   if (ParamRefType)
41610b57cec5SDimitry Andric     ParamType = ParamRefType->getPointeeType();
41620b57cec5SDimitry Andric 
41630b57cec5SDimitry Andric   // Overload sets usually make this parameter an undeduced context,
41640b57cec5SDimitry Andric   // but there are sometimes special circumstances.  Typically
41650b57cec5SDimitry Andric   // involving a template-id-expr.
41660b57cec5SDimitry Andric   if (ArgType == S.Context.OverloadTy) {
41675f757f3fSDimitry Andric     assert(Arg && "expected a non-null arg expression");
416806c3fb27SDimitry Andric     ArgType = ResolveOverloadForDeduction(S, TemplateParams, Arg, ParamType,
416906c3fb27SDimitry Andric                                           ParamRefType != nullptr, FailedTSC);
41700b57cec5SDimitry Andric     if (ArgType.isNull())
41710b57cec5SDimitry Andric       return true;
41720b57cec5SDimitry Andric   }
41730b57cec5SDimitry Andric 
41740b57cec5SDimitry Andric   if (ParamRefType) {
41750b57cec5SDimitry Andric     // If the argument has incomplete array type, try to complete its type.
41765f757f3fSDimitry Andric     if (ArgType->isIncompleteArrayType()) {
41775f757f3fSDimitry Andric       assert(Arg && "expected a non-null arg expression");
4178e8d8bef9SDimitry Andric       ArgType = S.getCompletedType(Arg);
41795f757f3fSDimitry Andric     }
41800b57cec5SDimitry Andric 
41810b57cec5SDimitry Andric     // C++1z [temp.deduct.call]p3:
41820b57cec5SDimitry Andric     //   If P is a forwarding reference and the argument is an lvalue, the type
41830b57cec5SDimitry Andric     //   "lvalue reference to A" is used in place of A for type deduction.
41840b57cec5SDimitry Andric     if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
41855f757f3fSDimitry Andric         ArgClassification.isLValue()) {
4186fe6060f1SDimitry Andric       if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
4187349cc55cSDimitry Andric         ArgType = S.Context.getAddrSpaceQualType(
4188349cc55cSDimitry Andric             ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace());
41890b57cec5SDimitry Andric       ArgType = S.Context.getLValueReferenceType(ArgType);
4190e8d8bef9SDimitry Andric     }
41910b57cec5SDimitry Andric   } else {
41920b57cec5SDimitry Andric     // C++ [temp.deduct.call]p2:
41930b57cec5SDimitry Andric     //   If P is not a reference type:
41940b57cec5SDimitry Andric     //   - If A is an array type, the pointer type produced by the
41950b57cec5SDimitry Andric     //     array-to-pointer standard conversion (4.2) is used in place of
41960b57cec5SDimitry Andric     //     A for type deduction; otherwise,
41970b57cec5SDimitry Andric     //   - If A is a function type, the pointer type produced by the
41980b57cec5SDimitry Andric     //     function-to-pointer standard conversion (4.3) is used in place
41990b57cec5SDimitry Andric     //     of A for type deduction; otherwise,
4200bdd1243dSDimitry Andric     if (ArgType->canDecayToPointerType())
4201bdd1243dSDimitry Andric       ArgType = S.Context.getDecayedType(ArgType);
42020b57cec5SDimitry Andric     else {
42030b57cec5SDimitry Andric       // - If A is a cv-qualified type, the top level cv-qualifiers of A's
42040b57cec5SDimitry Andric       //   type are ignored for type deduction.
42050b57cec5SDimitry Andric       ArgType = ArgType.getUnqualifiedType();
42060b57cec5SDimitry Andric     }
42070b57cec5SDimitry Andric   }
42080b57cec5SDimitry Andric 
42090b57cec5SDimitry Andric   // C++0x [temp.deduct.call]p4:
42100b57cec5SDimitry Andric   //   In general, the deduction process attempts to find template argument
42110b57cec5SDimitry Andric   //   values that will make the deduced A identical to A (after the type A
42120b57cec5SDimitry Andric   //   is transformed as described above). [...]
42130b57cec5SDimitry Andric   TDF = TDF_SkipNonDependent;
42140b57cec5SDimitry Andric 
42150b57cec5SDimitry Andric   //     - If the original P is a reference type, the deduced A (i.e., the
42160b57cec5SDimitry Andric   //       type referred to by the reference) can be more cv-qualified than
42170b57cec5SDimitry Andric   //       the transformed A.
42180b57cec5SDimitry Andric   if (ParamRefType)
42190b57cec5SDimitry Andric     TDF |= TDF_ParamWithReferenceType;
42200b57cec5SDimitry Andric   //     - The transformed A can be another pointer or pointer to member
42210b57cec5SDimitry Andric   //       type that can be converted to the deduced A via a qualification
42220b57cec5SDimitry Andric   //       conversion (4.4).
42230b57cec5SDimitry Andric   if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
42240b57cec5SDimitry Andric       ArgType->isObjCObjectPointerType())
42250b57cec5SDimitry Andric     TDF |= TDF_IgnoreQualifiers;
42260b57cec5SDimitry Andric   //     - If P is a class and P has the form simple-template-id, then the
42270b57cec5SDimitry Andric   //       transformed A can be a derived class of the deduced A. Likewise,
42280b57cec5SDimitry Andric   //       if P is a pointer to a class of the form simple-template-id, the
42290b57cec5SDimitry Andric   //       transformed A can be a pointer to a derived class pointed to by
42300b57cec5SDimitry Andric   //       the deduced A.
42310b57cec5SDimitry Andric   if (isSimpleTemplateIdType(ParamType) ||
42320b57cec5SDimitry Andric       (isa<PointerType>(ParamType) &&
42330b57cec5SDimitry Andric        isSimpleTemplateIdType(
4234fe6060f1SDimitry Andric            ParamType->castAs<PointerType>()->getPointeeType())))
42350b57cec5SDimitry Andric     TDF |= TDF_DerivedClass;
42360b57cec5SDimitry Andric 
42370b57cec5SDimitry Andric   return false;
42380b57cec5SDimitry Andric }
42390b57cec5SDimitry Andric 
42400b57cec5SDimitry Andric static bool
42410b57cec5SDimitry Andric hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
42420b57cec5SDimitry Andric                                QualType T);
42430b57cec5SDimitry Andric 
4244*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
42450b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
42465f757f3fSDimitry Andric     QualType ParamType, QualType ArgType,
42475f757f3fSDimitry Andric     Expr::Classification ArgClassification, Expr *Arg,
42485f757f3fSDimitry Andric     TemplateDeductionInfo &Info,
42490b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
42500b57cec5SDimitry Andric     SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
425106c3fb27SDimitry Andric     bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
425206c3fb27SDimitry Andric     TemplateSpecCandidateSet *FailedTSC = nullptr);
42530b57cec5SDimitry Andric 
42540b57cec5SDimitry Andric /// Attempt template argument deduction from an initializer list
42550b57cec5SDimitry Andric ///        deemed to be an argument in a function call.
DeduceFromInitializerList(Sema & S,TemplateParameterList * TemplateParams,QualType AdjustedParamType,InitListExpr * ILE,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced,SmallVectorImpl<Sema::OriginalCallArg> & OriginalCallArgs,unsigned ArgIdx,unsigned TDF)4256*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceFromInitializerList(
42570b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
42580b57cec5SDimitry Andric     InitListExpr *ILE, TemplateDeductionInfo &Info,
42590b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
42600b57cec5SDimitry Andric     SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
42610b57cec5SDimitry Andric     unsigned TDF) {
42620b57cec5SDimitry Andric   // C++ [temp.deduct.call]p1: (CWG 1591)
42630b57cec5SDimitry Andric   //   If removing references and cv-qualifiers from P gives
42640b57cec5SDimitry Andric   //   std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
42650b57cec5SDimitry Andric   //   a non-empty initializer list, then deduction is performed instead for
42660b57cec5SDimitry Andric   //   each element of the initializer list, taking P0 as a function template
42670b57cec5SDimitry Andric   //   parameter type and the initializer element as its argument
42680b57cec5SDimitry Andric   //
42690b57cec5SDimitry Andric   // We've already removed references and cv-qualifiers here.
42700b57cec5SDimitry Andric   if (!ILE->getNumInits())
4271*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
42720b57cec5SDimitry Andric 
42730b57cec5SDimitry Andric   QualType ElTy;
42740b57cec5SDimitry Andric   auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
42750b57cec5SDimitry Andric   if (ArrTy)
42760b57cec5SDimitry Andric     ElTy = ArrTy->getElementType();
42770b57cec5SDimitry Andric   else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
42780b57cec5SDimitry Andric     //   Otherwise, an initializer list argument causes the parameter to be
42790b57cec5SDimitry Andric     //   considered a non-deduced context
4280*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
42810b57cec5SDimitry Andric   }
42820b57cec5SDimitry Andric 
4283a7dea167SDimitry Andric   // Resolving a core issue: a braced-init-list containing any designators is
4284a7dea167SDimitry Andric   // a non-deduced context.
4285a7dea167SDimitry Andric   for (Expr *E : ILE->inits())
4286a7dea167SDimitry Andric     if (isa<DesignatedInitExpr>(E))
4287*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
4288a7dea167SDimitry Andric 
42890b57cec5SDimitry Andric   // Deduction only needs to be done for dependent types.
42900b57cec5SDimitry Andric   if (ElTy->isDependentType()) {
42910b57cec5SDimitry Andric     for (Expr *E : ILE->inits()) {
42920b57cec5SDimitry Andric       if (auto Result = DeduceTemplateArgumentsFromCallArgument(
42935f757f3fSDimitry Andric               S, TemplateParams, 0, ElTy, E->getType(),
42945f757f3fSDimitry Andric               E->Classify(S.getASTContext()), E, Info, Deduced,
4295*0fca6ea1SDimitry Andric               OriginalCallArgs, true, ArgIdx, TDF);
4296*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
42970b57cec5SDimitry Andric         return Result;
42980b57cec5SDimitry Andric     }
42990b57cec5SDimitry Andric   }
43000b57cec5SDimitry Andric 
43010b57cec5SDimitry Andric   //   in the P0[N] case, if N is a non-type template parameter, N is deduced
43020b57cec5SDimitry Andric   //   from the length of the initializer list.
43030b57cec5SDimitry Andric   if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
43040b57cec5SDimitry Andric     // Determine the array bound is something we can deduce.
4305e8d8bef9SDimitry Andric     if (const NonTypeTemplateParmDecl *NTTP =
43060b57cec5SDimitry Andric             getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
43070b57cec5SDimitry Andric       // We can perform template argument deduction for the given non-type
43080b57cec5SDimitry Andric       // template parameter.
43090b57cec5SDimitry Andric       // C++ [temp.deduct.type]p13:
43100b57cec5SDimitry Andric       //   The type of N in the type T[N] is std::size_t.
43110b57cec5SDimitry Andric       QualType T = S.Context.getSizeType();
43120b57cec5SDimitry Andric       llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
43130b57cec5SDimitry Andric       if (auto Result = DeduceNonTypeTemplateArgument(
43140b57cec5SDimitry Andric               S, TemplateParams, NTTP, llvm::APSInt(Size), T,
4315*0fca6ea1SDimitry Andric               /*ArrayBound=*/true, Info, Deduced);
4316*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
43170b57cec5SDimitry Andric         return Result;
43180b57cec5SDimitry Andric     }
43190b57cec5SDimitry Andric   }
43200b57cec5SDimitry Andric 
4321*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
43220b57cec5SDimitry Andric }
43230b57cec5SDimitry Andric 
43240b57cec5SDimitry Andric /// Perform template argument deduction per [temp.deduct.call] for a
43250b57cec5SDimitry Andric ///        single parameter / argument pair.
DeduceTemplateArgumentsFromCallArgument(Sema & S,TemplateParameterList * TemplateParams,unsigned FirstInnerIndex,QualType ParamType,QualType ArgType,Expr::Classification ArgClassification,Expr * Arg,TemplateDeductionInfo & Info,SmallVectorImpl<DeducedTemplateArgument> & Deduced,SmallVectorImpl<Sema::OriginalCallArg> & OriginalCallArgs,bool DecomposedParam,unsigned ArgIdx,unsigned TDF,TemplateSpecCandidateSet * FailedTSC)4326*0fca6ea1SDimitry Andric static TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
43270b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
43285f757f3fSDimitry Andric     QualType ParamType, QualType ArgType,
43295f757f3fSDimitry Andric     Expr::Classification ArgClassification, Expr *Arg,
43305f757f3fSDimitry Andric     TemplateDeductionInfo &Info,
43310b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
43320b57cec5SDimitry Andric     SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
433306c3fb27SDimitry Andric     bool DecomposedParam, unsigned ArgIdx, unsigned TDF,
433406c3fb27SDimitry Andric     TemplateSpecCandidateSet *FailedTSC) {
43355f757f3fSDimitry Andric 
43360b57cec5SDimitry Andric   QualType OrigParamType = ParamType;
43370b57cec5SDimitry Andric 
43380b57cec5SDimitry Andric   //   If P is a reference type [...]
43390b57cec5SDimitry Andric   //   If P is a cv-qualified type [...]
43405f757f3fSDimitry Andric   if (AdjustFunctionParmAndArgTypesForDeduction(
43415f757f3fSDimitry Andric           S, TemplateParams, FirstInnerIndex, ParamType, ArgType,
43425f757f3fSDimitry Andric           ArgClassification, Arg, TDF, FailedTSC))
4343*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
43440b57cec5SDimitry Andric 
43450b57cec5SDimitry Andric   //   If [...] the argument is a non-empty initializer list [...]
43465f757f3fSDimitry Andric   if (InitListExpr *ILE = dyn_cast_if_present<InitListExpr>(Arg))
43470b57cec5SDimitry Andric     return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
43480b57cec5SDimitry Andric                                      Deduced, OriginalCallArgs, ArgIdx, TDF);
43490b57cec5SDimitry Andric 
43500b57cec5SDimitry Andric   //   [...] the deduction process attempts to find template argument values
43510b57cec5SDimitry Andric   //   that will make the deduced A identical to A
43520b57cec5SDimitry Andric   //
43530b57cec5SDimitry Andric   // Keep track of the argument type and corresponding parameter index,
43540b57cec5SDimitry Andric   // so we can check for compatibility between the deduced A and A.
43555f757f3fSDimitry Andric   if (Arg)
43560b57cec5SDimitry Andric     OriginalCallArgs.push_back(
43570b57cec5SDimitry Andric         Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
43580b57cec5SDimitry Andric   return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
43590b57cec5SDimitry Andric                                             ArgType, Info, Deduced, TDF);
43600b57cec5SDimitry Andric }
43610b57cec5SDimitry Andric 
DeduceTemplateArguments(FunctionTemplateDecl * FunctionTemplate,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,FunctionDecl * & Specialization,TemplateDeductionInfo & Info,bool PartialOverloading,bool AggregateDeductionCandidate,QualType ObjectType,Expr::Classification ObjectClassification,llvm::function_ref<bool (ArrayRef<QualType>)> CheckNonDependent)4362*0fca6ea1SDimitry Andric TemplateDeductionResult Sema::DeduceTemplateArguments(
43630b57cec5SDimitry Andric     FunctionTemplateDecl *FunctionTemplate,
43640b57cec5SDimitry Andric     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
43650b57cec5SDimitry Andric     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
436606c3fb27SDimitry Andric     bool PartialOverloading, bool AggregateDeductionCandidate,
43675f757f3fSDimitry Andric     QualType ObjectType, Expr::Classification ObjectClassification,
43680b57cec5SDimitry Andric     llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
43690b57cec5SDimitry Andric   if (FunctionTemplate->isInvalidDecl())
4370*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Invalid;
43710b57cec5SDimitry Andric 
43720b57cec5SDimitry Andric   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
43730b57cec5SDimitry Andric   unsigned NumParams = Function->getNumParams();
43745f757f3fSDimitry Andric   bool HasExplicitObject = false;
43755f757f3fSDimitry Andric   int ExplicitObjectOffset = 0;
43765f757f3fSDimitry Andric   if (Function->hasCXXExplicitFunctionObjectParameter()) {
43775f757f3fSDimitry Andric     HasExplicitObject = true;
43785f757f3fSDimitry Andric     ExplicitObjectOffset = 1;
43795f757f3fSDimitry Andric   }
43800b57cec5SDimitry Andric 
43810b57cec5SDimitry Andric   unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
43820b57cec5SDimitry Andric 
43830b57cec5SDimitry Andric   // C++ [temp.deduct.call]p1:
43840b57cec5SDimitry Andric   //   Template argument deduction is done by comparing each function template
43850b57cec5SDimitry Andric   //   parameter type (call it P) with the type of the corresponding argument
43860b57cec5SDimitry Andric   //   of the call (call it A) as described below.
43875f757f3fSDimitry Andric   if (Args.size() < Function->getMinRequiredExplicitArguments() &&
43885f757f3fSDimitry Andric       !PartialOverloading)
4389*0fca6ea1SDimitry Andric     return TemplateDeductionResult::TooFewArguments;
43905f757f3fSDimitry Andric   else if (TooManyArguments(NumParams, Args.size() + ExplicitObjectOffset,
43915f757f3fSDimitry Andric                             PartialOverloading)) {
4392a7dea167SDimitry Andric     const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
43930b57cec5SDimitry Andric     if (Proto->isTemplateVariadic())
43940b57cec5SDimitry Andric       /* Do nothing */;
43950b57cec5SDimitry Andric     else if (!Proto->isVariadic())
4396*0fca6ea1SDimitry Andric       return TemplateDeductionResult::TooManyArguments;
43970b57cec5SDimitry Andric   }
43980b57cec5SDimitry Andric 
43990b57cec5SDimitry Andric   // The types of the parameters from which we will perform template argument
44000b57cec5SDimitry Andric   // deduction.
44010b57cec5SDimitry Andric   LocalInstantiationScope InstScope(*this);
44020b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
44030b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
44040b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
44050b57cec5SDimitry Andric   SmallVector<QualType, 8> ParamTypes;
44060b57cec5SDimitry Andric   unsigned NumExplicitlySpecified = 0;
44070b57cec5SDimitry Andric   if (ExplicitTemplateArgs) {
44085ffd83dbSDimitry Andric     TemplateDeductionResult Result;
44095ffd83dbSDimitry Andric     runWithSufficientStackSpace(Info.getLocation(), [&] {
44105ffd83dbSDimitry Andric       Result = SubstituteExplicitTemplateArguments(
44115ffd83dbSDimitry Andric           FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
44120b57cec5SDimitry Andric           Info);
44135ffd83dbSDimitry Andric     });
4414*0fca6ea1SDimitry Andric     if (Result != TemplateDeductionResult::Success)
44150b57cec5SDimitry Andric       return Result;
44160b57cec5SDimitry Andric 
44170b57cec5SDimitry Andric     NumExplicitlySpecified = Deduced.size();
44180b57cec5SDimitry Andric   } else {
44190b57cec5SDimitry Andric     // Just fill in the parameter types from the function declaration.
44200b57cec5SDimitry Andric     for (unsigned I = 0; I != NumParams; ++I)
44210b57cec5SDimitry Andric       ParamTypes.push_back(Function->getParamDecl(I)->getType());
44220b57cec5SDimitry Andric   }
44230b57cec5SDimitry Andric 
44240b57cec5SDimitry Andric   SmallVector<OriginalCallArg, 8> OriginalCallArgs;
44250b57cec5SDimitry Andric 
44260b57cec5SDimitry Andric   // Deduce an argument of type ParamType from an expression with index ArgIdx.
44275f757f3fSDimitry Andric   auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx,
4428*0fca6ea1SDimitry Andric                                 bool ExplicitObjectArgument) {
44290b57cec5SDimitry Andric     // C++ [demp.deduct.call]p1: (DR1391)
44300b57cec5SDimitry Andric     //   Template argument deduction is done by comparing each function template
44310b57cec5SDimitry Andric     //   parameter that contains template-parameters that participate in
44320b57cec5SDimitry Andric     //   template argument deduction ...
44330b57cec5SDimitry Andric     if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4434*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
44350b57cec5SDimitry Andric 
4436*0fca6ea1SDimitry Andric     if (ExplicitObjectArgument) {
44370b57cec5SDimitry Andric       //   ... with the type of the corresponding argument
44380b57cec5SDimitry Andric       return DeduceTemplateArgumentsFromCallArgument(
44395f757f3fSDimitry Andric           *this, TemplateParams, FirstInnerIndex, ParamType, ObjectType,
44405f757f3fSDimitry Andric           ObjectClassification,
44415f757f3fSDimitry Andric           /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
44425f757f3fSDimitry Andric           /*Decomposed*/ false, ArgIdx, /*TDF*/ 0);
44435f757f3fSDimitry Andric     }
44445f757f3fSDimitry Andric 
44455f757f3fSDimitry Andric     //   ... with the type of the corresponding argument
44465f757f3fSDimitry Andric     return DeduceTemplateArgumentsFromCallArgument(
44475f757f3fSDimitry Andric         *this, TemplateParams, FirstInnerIndex, ParamType,
44485f757f3fSDimitry Andric         Args[ArgIdx]->getType(), Args[ArgIdx]->Classify(getASTContext()),
44495f757f3fSDimitry Andric         Args[ArgIdx], Info, Deduced, OriginalCallArgs, /*Decomposed*/ false,
44505f757f3fSDimitry Andric         ArgIdx, /*TDF*/ 0);
44510b57cec5SDimitry Andric   };
44520b57cec5SDimitry Andric 
44530b57cec5SDimitry Andric   // Deduce template arguments from the function parameters.
44540b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
44550b57cec5SDimitry Andric   SmallVector<QualType, 8> ParamTypesForArgChecking;
44560b57cec5SDimitry Andric   for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
44570b57cec5SDimitry Andric        ParamIdx != NumParamTypes; ++ParamIdx) {
44580b57cec5SDimitry Andric     QualType ParamType = ParamTypes[ParamIdx];
44590b57cec5SDimitry Andric 
44600b57cec5SDimitry Andric     const PackExpansionType *ParamExpansion =
44610b57cec5SDimitry Andric         dyn_cast<PackExpansionType>(ParamType);
44620b57cec5SDimitry Andric     if (!ParamExpansion) {
44630b57cec5SDimitry Andric       // Simple case: matching a function parameter to a function argument.
44645f757f3fSDimitry Andric       if (ArgIdx >= Args.size() && !(HasExplicitObject && ParamIdx == 0))
44650b57cec5SDimitry Andric         break;
44660b57cec5SDimitry Andric 
44670b57cec5SDimitry Andric       ParamTypesForArgChecking.push_back(ParamType);
44685f757f3fSDimitry Andric 
44695f757f3fSDimitry Andric       if (ParamIdx == 0 && HasExplicitObject) {
44705f757f3fSDimitry Andric         if (auto Result = DeduceCallArgument(ParamType, 0,
4471*0fca6ea1SDimitry Andric                                              /*ExplicitObjectArgument=*/true);
4472*0fca6ea1SDimitry Andric             Result != TemplateDeductionResult::Success)
44735f757f3fSDimitry Andric           return Result;
44745f757f3fSDimitry Andric         continue;
44755f757f3fSDimitry Andric       }
44765f757f3fSDimitry Andric 
44775f757f3fSDimitry Andric       if (auto Result = DeduceCallArgument(ParamType, ArgIdx++,
4478*0fca6ea1SDimitry Andric                                            /*ExplicitObjectArgument=*/false);
4479*0fca6ea1SDimitry Andric           Result != TemplateDeductionResult::Success)
44800b57cec5SDimitry Andric         return Result;
44810b57cec5SDimitry Andric 
44820b57cec5SDimitry Andric       continue;
44830b57cec5SDimitry Andric     }
44840b57cec5SDimitry Andric 
448506c3fb27SDimitry Andric     bool IsTrailingPack = ParamIdx + 1 == NumParamTypes;
448606c3fb27SDimitry Andric 
44870b57cec5SDimitry Andric     QualType ParamPattern = ParamExpansion->getPattern();
44880b57cec5SDimitry Andric     PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
448906c3fb27SDimitry Andric                                  ParamPattern,
449006c3fb27SDimitry Andric                                  AggregateDeductionCandidate && IsTrailingPack);
44910b57cec5SDimitry Andric 
44920b57cec5SDimitry Andric     // C++0x [temp.deduct.call]p1:
44930b57cec5SDimitry Andric     //   For a function parameter pack that occurs at the end of the
44940b57cec5SDimitry Andric     //   parameter-declaration-list, the type A of each remaining argument of
44950b57cec5SDimitry Andric     //   the call is compared with the type P of the declarator-id of the
44960b57cec5SDimitry Andric     //   function parameter pack. Each comparison deduces template arguments
44970b57cec5SDimitry Andric     //   for subsequent positions in the template parameter packs expanded by
44980b57cec5SDimitry Andric     //   the function parameter pack. When a function parameter pack appears
44990b57cec5SDimitry Andric     //   in a non-deduced context [not at the end of the list], the type of
45000b57cec5SDimitry Andric     //   that parameter pack is never deduced.
45010b57cec5SDimitry Andric     //
45020b57cec5SDimitry Andric     // FIXME: The above rule allows the size of the parameter pack to change
45030b57cec5SDimitry Andric     // after we skip it (in the non-deduced case). That makes no sense, so
45040b57cec5SDimitry Andric     // we instead notionally deduce the pack against N arguments, where N is
45050b57cec5SDimitry Andric     // the length of the explicitly-specified pack if it's expanded by the
45060b57cec5SDimitry Andric     // parameter pack and 0 otherwise, and we treat each deduction as a
45070b57cec5SDimitry Andric     // non-deduced context.
450806c3fb27SDimitry Andric     if (IsTrailingPack || PackScope.hasFixedArity()) {
45090b57cec5SDimitry Andric       for (; ArgIdx < Args.size() && PackScope.hasNextElement();
45100b57cec5SDimitry Andric            PackScope.nextPackElement(), ++ArgIdx) {
45110b57cec5SDimitry Andric         ParamTypesForArgChecking.push_back(ParamPattern);
45125f757f3fSDimitry Andric         if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx,
4513*0fca6ea1SDimitry Andric                                              /*ExplicitObjectArgument=*/false);
4514*0fca6ea1SDimitry Andric             Result != TemplateDeductionResult::Success)
45150b57cec5SDimitry Andric           return Result;
45160b57cec5SDimitry Andric       }
45170b57cec5SDimitry Andric     } else {
45180b57cec5SDimitry Andric       // If the parameter type contains an explicitly-specified pack that we
45190b57cec5SDimitry Andric       // could not expand, skip the number of parameters notionally created
45200b57cec5SDimitry Andric       // by the expansion.
4521bdd1243dSDimitry Andric       std::optional<unsigned> NumExpansions =
4522bdd1243dSDimitry Andric           ParamExpansion->getNumExpansions();
45230b57cec5SDimitry Andric       if (NumExpansions && !PackScope.isPartiallyExpanded()) {
45240b57cec5SDimitry Andric         for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
45250b57cec5SDimitry Andric              ++I, ++ArgIdx) {
45260b57cec5SDimitry Andric           ParamTypesForArgChecking.push_back(ParamPattern);
45270b57cec5SDimitry Andric           // FIXME: Should we add OriginalCallArgs for these? What if the
45280b57cec5SDimitry Andric           // corresponding argument is a list?
45290b57cec5SDimitry Andric           PackScope.nextPackElement();
45300b57cec5SDimitry Andric         }
4531*0fca6ea1SDimitry Andric       } else if (!IsTrailingPack && !PackScope.isPartiallyExpanded() &&
4532*0fca6ea1SDimitry Andric                  PackScope.isDeducedFromEarlierParameter()) {
4533*0fca6ea1SDimitry Andric         // [temp.deduct.general#3]
4534*0fca6ea1SDimitry Andric         // When all template arguments have been deduced
4535*0fca6ea1SDimitry Andric         // or obtained from default template arguments, all uses of template
4536*0fca6ea1SDimitry Andric         // parameters in the template parameter list of the template are
4537*0fca6ea1SDimitry Andric         // replaced with the corresponding deduced or default argument values
4538*0fca6ea1SDimitry Andric         //
4539*0fca6ea1SDimitry Andric         // If we have a trailing parameter pack, that has been deduced
4540*0fca6ea1SDimitry Andric         // previously we substitute the pack here in a similar fashion as
4541*0fca6ea1SDimitry Andric         // above with the trailing parameter packs. The main difference here is
4542*0fca6ea1SDimitry Andric         // that, in this case we are not processing all of the remaining
4543*0fca6ea1SDimitry Andric         // arguments. We are only process as many arguments as we have in
4544*0fca6ea1SDimitry Andric         // the already deduced parameter.
4545*0fca6ea1SDimitry Andric         std::optional<unsigned> ArgPosAfterSubstitution =
4546*0fca6ea1SDimitry Andric             PackScope.getSavedPackSizeIfAllEqual();
4547*0fca6ea1SDimitry Andric         if (!ArgPosAfterSubstitution)
4548*0fca6ea1SDimitry Andric           continue;
4549*0fca6ea1SDimitry Andric 
4550*0fca6ea1SDimitry Andric         unsigned PackArgEnd = ArgIdx + *ArgPosAfterSubstitution;
4551*0fca6ea1SDimitry Andric         for (; ArgIdx < PackArgEnd && ArgIdx < Args.size(); ArgIdx++) {
4552*0fca6ea1SDimitry Andric           ParamTypesForArgChecking.push_back(ParamPattern);
4553*0fca6ea1SDimitry Andric           if (auto Result =
4554*0fca6ea1SDimitry Andric                   DeduceCallArgument(ParamPattern, ArgIdx,
4555*0fca6ea1SDimitry Andric                                      /*ExplicitObjectArgument=*/false);
4556*0fca6ea1SDimitry Andric               Result != TemplateDeductionResult::Success)
4557*0fca6ea1SDimitry Andric             return Result;
4558*0fca6ea1SDimitry Andric 
4559*0fca6ea1SDimitry Andric           PackScope.nextPackElement();
4560*0fca6ea1SDimitry Andric         }
45610b57cec5SDimitry Andric       }
45620b57cec5SDimitry Andric     }
45630b57cec5SDimitry Andric 
45640b57cec5SDimitry Andric     // Build argument packs for each of the parameter packs expanded by this
45650b57cec5SDimitry Andric     // pack expansion.
4566*0fca6ea1SDimitry Andric     if (auto Result = PackScope.finish();
4567*0fca6ea1SDimitry Andric         Result != TemplateDeductionResult::Success)
45680b57cec5SDimitry Andric       return Result;
45690b57cec5SDimitry Andric   }
45700b57cec5SDimitry Andric 
45710b57cec5SDimitry Andric   // Capture the context in which the function call is made. This is the context
45720b57cec5SDimitry Andric   // that is needed when the accessibility of template arguments is checked.
45730b57cec5SDimitry Andric   DeclContext *CallingCtx = CurContext;
45740b57cec5SDimitry Andric 
45755ffd83dbSDimitry Andric   TemplateDeductionResult Result;
45765ffd83dbSDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
45775ffd83dbSDimitry Andric     Result = FinishTemplateArgumentDeduction(
45780b57cec5SDimitry Andric         FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
45790b57cec5SDimitry Andric         &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
45800b57cec5SDimitry Andric           ContextRAII SavedContext(*this, CallingCtx);
45810b57cec5SDimitry Andric           return CheckNonDependent(ParamTypesForArgChecking);
45820b57cec5SDimitry Andric         });
45835ffd83dbSDimitry Andric   });
45845ffd83dbSDimitry Andric   return Result;
45850b57cec5SDimitry Andric }
45860b57cec5SDimitry Andric 
adjustCCAndNoReturn(QualType ArgFunctionType,QualType FunctionType,bool AdjustExceptionSpec)45870b57cec5SDimitry Andric QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
45880b57cec5SDimitry Andric                                    QualType FunctionType,
45890b57cec5SDimitry Andric                                    bool AdjustExceptionSpec) {
45900b57cec5SDimitry Andric   if (ArgFunctionType.isNull())
45910b57cec5SDimitry Andric     return ArgFunctionType;
45920b57cec5SDimitry Andric 
4593a7dea167SDimitry Andric   const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4594a7dea167SDimitry Andric   const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
45950b57cec5SDimitry Andric   FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
45960b57cec5SDimitry Andric   bool Rebuild = false;
45970b57cec5SDimitry Andric 
45980b57cec5SDimitry Andric   CallingConv CC = FunctionTypeP->getCallConv();
45990b57cec5SDimitry Andric   if (EPI.ExtInfo.getCC() != CC) {
46000b57cec5SDimitry Andric     EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
46010b57cec5SDimitry Andric     Rebuild = true;
46020b57cec5SDimitry Andric   }
46030b57cec5SDimitry Andric 
46040b57cec5SDimitry Andric   bool NoReturn = FunctionTypeP->getNoReturnAttr();
46050b57cec5SDimitry Andric   if (EPI.ExtInfo.getNoReturn() != NoReturn) {
46060b57cec5SDimitry Andric     EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
46070b57cec5SDimitry Andric     Rebuild = true;
46080b57cec5SDimitry Andric   }
46090b57cec5SDimitry Andric 
46100b57cec5SDimitry Andric   if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
46110b57cec5SDimitry Andric                               ArgFunctionTypeP->hasExceptionSpec())) {
46120b57cec5SDimitry Andric     EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
46130b57cec5SDimitry Andric     Rebuild = true;
46140b57cec5SDimitry Andric   }
46150b57cec5SDimitry Andric 
46160b57cec5SDimitry Andric   if (!Rebuild)
46170b57cec5SDimitry Andric     return ArgFunctionType;
46180b57cec5SDimitry Andric 
46190b57cec5SDimitry Andric   return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
46200b57cec5SDimitry Andric                                  ArgFunctionTypeP->getParamTypes(), EPI);
46210b57cec5SDimitry Andric }
46220b57cec5SDimitry Andric 
DeduceTemplateArguments(FunctionTemplateDecl * FunctionTemplate,TemplateArgumentListInfo * ExplicitTemplateArgs,QualType ArgFunctionType,FunctionDecl * & Specialization,TemplateDeductionInfo & Info,bool IsAddressOfFunction)4623*0fca6ea1SDimitry Andric TemplateDeductionResult Sema::DeduceTemplateArguments(
46240b57cec5SDimitry Andric     FunctionTemplateDecl *FunctionTemplate,
46250b57cec5SDimitry Andric     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
46260b57cec5SDimitry Andric     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
46270b57cec5SDimitry Andric     bool IsAddressOfFunction) {
46280b57cec5SDimitry Andric   if (FunctionTemplate->isInvalidDecl())
4629*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Invalid;
46300b57cec5SDimitry Andric 
46310b57cec5SDimitry Andric   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
46320b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
46330b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
46340b57cec5SDimitry Andric   QualType FunctionType = Function->getType();
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric   // Substitute any explicit template arguments.
46370b57cec5SDimitry Andric   LocalInstantiationScope InstScope(*this);
46380b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
46390b57cec5SDimitry Andric   unsigned NumExplicitlySpecified = 0;
46400b57cec5SDimitry Andric   SmallVector<QualType, 4> ParamTypes;
46410b57cec5SDimitry Andric   if (ExplicitTemplateArgs) {
46425ffd83dbSDimitry Andric     TemplateDeductionResult Result;
46435ffd83dbSDimitry Andric     runWithSufficientStackSpace(Info.getLocation(), [&] {
46445ffd83dbSDimitry Andric       Result = SubstituteExplicitTemplateArguments(
46455ffd83dbSDimitry Andric           FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
46465ffd83dbSDimitry Andric           &FunctionType, Info);
46475ffd83dbSDimitry Andric     });
4648*0fca6ea1SDimitry Andric     if (Result != TemplateDeductionResult::Success)
46490b57cec5SDimitry Andric       return Result;
46500b57cec5SDimitry Andric 
46510b57cec5SDimitry Andric     NumExplicitlySpecified = Deduced.size();
46520b57cec5SDimitry Andric   }
46530b57cec5SDimitry Andric 
46540b57cec5SDimitry Andric   // When taking the address of a function, we require convertibility of
46550b57cec5SDimitry Andric   // the resulting function type. Otherwise, we allow arbitrary mismatches
46560b57cec5SDimitry Andric   // of calling convention and noreturn.
46570b57cec5SDimitry Andric   if (!IsAddressOfFunction)
46580b57cec5SDimitry Andric     ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
46590b57cec5SDimitry Andric                                           /*AdjustExceptionSpec*/false);
46600b57cec5SDimitry Andric 
46610b57cec5SDimitry Andric   // Unevaluated SFINAE context.
46620b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
46630b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
46640b57cec5SDimitry Andric   SFINAETrap Trap(*this);
46650b57cec5SDimitry Andric 
46660b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
46670b57cec5SDimitry Andric 
46680b57cec5SDimitry Andric   // If the function has a deduced return type, substitute it for a dependent
466906c3fb27SDimitry Andric   // type so that we treat it as a non-deduced context in what follows.
46700b57cec5SDimitry Andric   bool HasDeducedReturnType = false;
467106c3fb27SDimitry Andric   if (getLangOpts().CPlusPlus14 &&
46720b57cec5SDimitry Andric       Function->getReturnType()->getContainedAutoType()) {
4673349cc55cSDimitry Andric     FunctionType = SubstAutoTypeDependent(FunctionType);
46740b57cec5SDimitry Andric     HasDeducedReturnType = true;
46750b57cec5SDimitry Andric   }
46760b57cec5SDimitry Andric 
4677349cc55cSDimitry Andric   if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
46780b57cec5SDimitry Andric     unsigned TDF =
46790b57cec5SDimitry Andric         TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
46800b57cec5SDimitry Andric     // Deduce template arguments from the function type.
4681*0fca6ea1SDimitry Andric     if (TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch(
4682*0fca6ea1SDimitry Andric             *this, TemplateParams, FunctionType, ArgFunctionType, Info, Deduced,
4683*0fca6ea1SDimitry Andric             TDF);
4684*0fca6ea1SDimitry Andric         Result != TemplateDeductionResult::Success)
46850b57cec5SDimitry Andric       return Result;
46860b57cec5SDimitry Andric   }
46870b57cec5SDimitry Andric 
46885ffd83dbSDimitry Andric   TemplateDeductionResult Result;
46895ffd83dbSDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
46905ffd83dbSDimitry Andric     Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
46910b57cec5SDimitry Andric                                              NumExplicitlySpecified,
46925ffd83dbSDimitry Andric                                              Specialization, Info);
46935ffd83dbSDimitry Andric   });
4694*0fca6ea1SDimitry Andric   if (Result != TemplateDeductionResult::Success)
46950b57cec5SDimitry Andric     return Result;
46960b57cec5SDimitry Andric 
46970b57cec5SDimitry Andric   // If the function has a deduced return type, deduce it now, so we can check
46980b57cec5SDimitry Andric   // that the deduced function type matches the requested type.
469906c3fb27SDimitry Andric   if (HasDeducedReturnType && IsAddressOfFunction &&
47000b57cec5SDimitry Andric       Specialization->getReturnType()->isUndeducedType() &&
47010b57cec5SDimitry Andric       DeduceReturnType(Specialization, Info.getLocation(), false))
4702*0fca6ea1SDimitry Andric     return TemplateDeductionResult::MiscellaneousDeductionFailure;
47030b57cec5SDimitry Andric 
4704*0fca6ea1SDimitry Andric   // [C++26][expr.const]/p17
4705*0fca6ea1SDimitry Andric   // An expression or conversion is immediate-escalating if it is not initially
4706*0fca6ea1SDimitry Andric   // in an immediate function context and it is [...]
4707*0fca6ea1SDimitry Andric   // a potentially-evaluated id-expression that denotes an immediate function.
470806c3fb27SDimitry Andric   if (IsAddressOfFunction && getLangOpts().CPlusPlus20 &&
470906c3fb27SDimitry Andric       Specialization->isImmediateEscalating() &&
4710*0fca6ea1SDimitry Andric       parentEvaluationContext().isPotentiallyEvaluated() &&
471106c3fb27SDimitry Andric       CheckIfFunctionSpecializationIsImmediate(Specialization,
471206c3fb27SDimitry Andric                                                Info.getLocation()))
4713*0fca6ea1SDimitry Andric     return TemplateDeductionResult::MiscellaneousDeductionFailure;
47140b57cec5SDimitry Andric 
47150b57cec5SDimitry Andric   // Adjust the exception specification of the argument to match the
47160b57cec5SDimitry Andric   // substituted and resolved type we just formed. (Calling convention and
47170b57cec5SDimitry Andric   // noreturn can't be dependent, so we don't actually need this for them
47180b57cec5SDimitry Andric   // right now.)
47190b57cec5SDimitry Andric   QualType SpecializationType = Specialization->getType();
472006c3fb27SDimitry Andric   if (!IsAddressOfFunction) {
47210b57cec5SDimitry Andric     ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
47220b57cec5SDimitry Andric                                           /*AdjustExceptionSpec*/true);
47230b57cec5SDimitry Andric 
472406c3fb27SDimitry Andric     // Revert placeholder types in the return type back to undeduced types so
472506c3fb27SDimitry Andric     // that the comparison below compares the declared return types.
472606c3fb27SDimitry Andric     if (HasDeducedReturnType) {
472706c3fb27SDimitry Andric       SpecializationType = SubstAutoType(SpecializationType, QualType());
472806c3fb27SDimitry Andric       ArgFunctionType = SubstAutoType(ArgFunctionType, QualType());
472906c3fb27SDimitry Andric     }
473006c3fb27SDimitry Andric   }
473106c3fb27SDimitry Andric 
47320b57cec5SDimitry Andric   // If the requested function type does not match the actual type of the
47330b57cec5SDimitry Andric   // specialization with respect to arguments of compatible pointer to function
47340b57cec5SDimitry Andric   // types, template argument deduction fails.
47350b57cec5SDimitry Andric   if (!ArgFunctionType.isNull()) {
4736*0fca6ea1SDimitry Andric     if (IsAddressOfFunction ? !isSameOrCompatibleFunctionType(
47370b57cec5SDimitry Andric                                   Context.getCanonicalType(SpecializationType),
473806c3fb27SDimitry Andric                                   Context.getCanonicalType(ArgFunctionType))
4739*0fca6ea1SDimitry Andric                             : !Context.hasSameFunctionTypeIgnoringExceptionSpec(
4740*0fca6ea1SDimitry Andric                                   SpecializationType, ArgFunctionType)) {
474106c3fb27SDimitry Andric       Info.FirstArg = TemplateArgument(SpecializationType);
474206c3fb27SDimitry Andric       Info.SecondArg = TemplateArgument(ArgFunctionType);
4743*0fca6ea1SDimitry Andric       return TemplateDeductionResult::NonDeducedMismatch;
474406c3fb27SDimitry Andric     }
47450b57cec5SDimitry Andric   }
47460b57cec5SDimitry Andric 
4747*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
47480b57cec5SDimitry Andric }
47490b57cec5SDimitry Andric 
DeduceTemplateArguments(FunctionTemplateDecl * ConversionTemplate,QualType ObjectType,Expr::Classification ObjectClassification,QualType ToType,CXXConversionDecl * & Specialization,TemplateDeductionInfo & Info)4750*0fca6ea1SDimitry Andric TemplateDeductionResult Sema::DeduceTemplateArguments(
47515f757f3fSDimitry Andric     FunctionTemplateDecl *ConversionTemplate, QualType ObjectType,
47525f757f3fSDimitry Andric     Expr::Classification ObjectClassification, QualType ToType,
47535f757f3fSDimitry Andric     CXXConversionDecl *&Specialization, TemplateDeductionInfo &Info) {
47540b57cec5SDimitry Andric   if (ConversionTemplate->isInvalidDecl())
4755*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Invalid;
47560b57cec5SDimitry Andric 
47570b57cec5SDimitry Andric   CXXConversionDecl *ConversionGeneric
47580b57cec5SDimitry Andric     = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
47590b57cec5SDimitry Andric 
47600b57cec5SDimitry Andric   QualType FromType = ConversionGeneric->getConversionType();
47610b57cec5SDimitry Andric 
47620b57cec5SDimitry Andric   // Canonicalize the types for deduction.
47630b57cec5SDimitry Andric   QualType P = Context.getCanonicalType(FromType);
47640b57cec5SDimitry Andric   QualType A = Context.getCanonicalType(ToType);
47650b57cec5SDimitry Andric 
47660b57cec5SDimitry Andric   // C++0x [temp.deduct.conv]p2:
47670b57cec5SDimitry Andric   //   If P is a reference type, the type referred to by P is used for
47680b57cec5SDimitry Andric   //   type deduction.
47690b57cec5SDimitry Andric   if (const ReferenceType *PRef = P->getAs<ReferenceType>())
47700b57cec5SDimitry Andric     P = PRef->getPointeeType();
47710b57cec5SDimitry Andric 
47720b57cec5SDimitry Andric   // C++0x [temp.deduct.conv]p4:
47730b57cec5SDimitry Andric   //   [...] If A is a reference type, the type referred to by A is used
47740b57cec5SDimitry Andric   //   for type deduction.
47750b57cec5SDimitry Andric   if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
47760b57cec5SDimitry Andric     A = ARef->getPointeeType();
47770b57cec5SDimitry Andric     // We work around a defect in the standard here: cv-qualifiers are also
47780b57cec5SDimitry Andric     // removed from P and A in this case, unless P was a reference type. This
47790b57cec5SDimitry Andric     // seems to mostly match what other compilers are doing.
47800b57cec5SDimitry Andric     if (!FromType->getAs<ReferenceType>()) {
47810b57cec5SDimitry Andric       A = A.getUnqualifiedType();
47820b57cec5SDimitry Andric       P = P.getUnqualifiedType();
47830b57cec5SDimitry Andric     }
47840b57cec5SDimitry Andric 
47850b57cec5SDimitry Andric   // C++ [temp.deduct.conv]p3:
47860b57cec5SDimitry Andric   //
47870b57cec5SDimitry Andric   //   If A is not a reference type:
47880b57cec5SDimitry Andric   } else {
47890b57cec5SDimitry Andric     assert(!A->isReferenceType() && "Reference types were handled above");
47900b57cec5SDimitry Andric 
47910b57cec5SDimitry Andric     //   - If P is an array type, the pointer type produced by the
47920b57cec5SDimitry Andric     //     array-to-pointer standard conversion (4.2) is used in place
47930b57cec5SDimitry Andric     //     of P for type deduction; otherwise,
47940b57cec5SDimitry Andric     if (P->isArrayType())
47950b57cec5SDimitry Andric       P = Context.getArrayDecayedType(P);
47960b57cec5SDimitry Andric     //   - If P is a function type, the pointer type produced by the
47970b57cec5SDimitry Andric     //     function-to-pointer standard conversion (4.3) is used in
47980b57cec5SDimitry Andric     //     place of P for type deduction; otherwise,
47990b57cec5SDimitry Andric     else if (P->isFunctionType())
48000b57cec5SDimitry Andric       P = Context.getPointerType(P);
48010b57cec5SDimitry Andric     //   - If P is a cv-qualified type, the top level cv-qualifiers of
48020b57cec5SDimitry Andric     //     P's type are ignored for type deduction.
48030b57cec5SDimitry Andric     else
48040b57cec5SDimitry Andric       P = P.getUnqualifiedType();
48050b57cec5SDimitry Andric 
48060b57cec5SDimitry Andric     // C++0x [temp.deduct.conv]p4:
48070b57cec5SDimitry Andric     //   If A is a cv-qualified type, the top level cv-qualifiers of A's
48080b57cec5SDimitry Andric     //   type are ignored for type deduction. If A is a reference type, the type
48090b57cec5SDimitry Andric     //   referred to by A is used for type deduction.
48100b57cec5SDimitry Andric     A = A.getUnqualifiedType();
48110b57cec5SDimitry Andric   }
48120b57cec5SDimitry Andric 
48130b57cec5SDimitry Andric   // Unevaluated SFINAE context.
48140b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
48150b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
48160b57cec5SDimitry Andric   SFINAETrap Trap(*this);
48170b57cec5SDimitry Andric 
48180b57cec5SDimitry Andric   // C++ [temp.deduct.conv]p1:
48190b57cec5SDimitry Andric   //   Template argument deduction is done by comparing the return
48200b57cec5SDimitry Andric   //   type of the template conversion function (call it P) with the
48210b57cec5SDimitry Andric   //   type that is required as the result of the conversion (call it
48220b57cec5SDimitry Andric   //   A) as described in 14.8.2.4.
48230b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
48240b57cec5SDimitry Andric     = ConversionTemplate->getTemplateParameters();
48250b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
48260b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
48270b57cec5SDimitry Andric 
48280b57cec5SDimitry Andric   // C++0x [temp.deduct.conv]p4:
48290b57cec5SDimitry Andric   //   In general, the deduction process attempts to find template
48300b57cec5SDimitry Andric   //   argument values that will make the deduced A identical to
48310b57cec5SDimitry Andric   //   A. However, there are two cases that allow a difference:
48320b57cec5SDimitry Andric   unsigned TDF = 0;
48330b57cec5SDimitry Andric   //     - If the original A is a reference type, A can be more
48340b57cec5SDimitry Andric   //       cv-qualified than the deduced A (i.e., the type referred to
48350b57cec5SDimitry Andric   //       by the reference)
48360b57cec5SDimitry Andric   if (ToType->isReferenceType())
48370b57cec5SDimitry Andric     TDF |= TDF_ArgWithReferenceType;
48380b57cec5SDimitry Andric   //     - The deduced A can be another pointer or pointer to member
48390b57cec5SDimitry Andric   //       type that can be converted to A via a qualification
48400b57cec5SDimitry Andric   //       conversion.
48410b57cec5SDimitry Andric   //
48420b57cec5SDimitry Andric   // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
48430b57cec5SDimitry Andric   // both P and A are pointers or member pointers. In this case, we
48440b57cec5SDimitry Andric   // just ignore cv-qualifiers completely).
48450b57cec5SDimitry Andric   if ((P->isPointerType() && A->isPointerType()) ||
48460b57cec5SDimitry Andric       (P->isMemberPointerType() && A->isMemberPointerType()))
48470b57cec5SDimitry Andric     TDF |= TDF_IgnoreQualifiers;
48485f757f3fSDimitry Andric 
48495f757f3fSDimitry Andric   SmallVector<Sema::OriginalCallArg, 1> OriginalCallArgs;
48505f757f3fSDimitry Andric   if (ConversionGeneric->isExplicitObjectMemberFunction()) {
48515f757f3fSDimitry Andric     QualType ParamType = ConversionGeneric->getParamDecl(0)->getType();
48525f757f3fSDimitry Andric     if (TemplateDeductionResult Result =
48535f757f3fSDimitry Andric             DeduceTemplateArgumentsFromCallArgument(
48545f757f3fSDimitry Andric                 *this, TemplateParams, getFirstInnerIndex(ConversionTemplate),
48555f757f3fSDimitry Andric                 ParamType, ObjectType, ObjectClassification,
48565f757f3fSDimitry Andric                 /*Arg=*/nullptr, Info, Deduced, OriginalCallArgs,
4857*0fca6ea1SDimitry Andric                 /*Decomposed*/ false, 0, /*TDF*/ 0);
4858*0fca6ea1SDimitry Andric         Result != TemplateDeductionResult::Success)
48595f757f3fSDimitry Andric       return Result;
48605f757f3fSDimitry Andric   }
48615f757f3fSDimitry Andric 
4862*0fca6ea1SDimitry Andric   if (TemplateDeductionResult Result = DeduceTemplateArgumentsByTypeMatch(
4863*0fca6ea1SDimitry Andric           *this, TemplateParams, P, A, Info, Deduced, TDF);
4864*0fca6ea1SDimitry Andric       Result != TemplateDeductionResult::Success)
48650b57cec5SDimitry Andric     return Result;
48660b57cec5SDimitry Andric 
48670b57cec5SDimitry Andric   // Create an Instantiation Scope for finalizing the operator.
48680b57cec5SDimitry Andric   LocalInstantiationScope InstScope(*this);
48690b57cec5SDimitry Andric   // Finish template argument deduction.
48700b57cec5SDimitry Andric   FunctionDecl *ConversionSpecialized = nullptr;
48715ffd83dbSDimitry Andric   TemplateDeductionResult Result;
48725ffd83dbSDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
48735ffd83dbSDimitry Andric     Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
48745f757f3fSDimitry Andric                                              ConversionSpecialized, Info,
48755f757f3fSDimitry Andric                                              &OriginalCallArgs);
48765ffd83dbSDimitry Andric   });
48770b57cec5SDimitry Andric   Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
48780b57cec5SDimitry Andric   return Result;
48790b57cec5SDimitry Andric }
48800b57cec5SDimitry Andric 
4881*0fca6ea1SDimitry Andric TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl * FunctionTemplate,TemplateArgumentListInfo * ExplicitTemplateArgs,FunctionDecl * & Specialization,TemplateDeductionInfo & Info,bool IsAddressOfFunction)4882*0fca6ea1SDimitry Andric Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
48830b57cec5SDimitry Andric                               TemplateArgumentListInfo *ExplicitTemplateArgs,
4884*0fca6ea1SDimitry Andric                               FunctionDecl *&Specialization,
4885*0fca6ea1SDimitry Andric                               TemplateDeductionInfo &Info,
48860b57cec5SDimitry Andric                               bool IsAddressOfFunction) {
48870b57cec5SDimitry Andric   return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
48880b57cec5SDimitry Andric                                  QualType(), Specialization, Info,
48890b57cec5SDimitry Andric                                  IsAddressOfFunction);
48900b57cec5SDimitry Andric }
48910b57cec5SDimitry Andric 
48920b57cec5SDimitry Andric namespace {
48930b57cec5SDimitry Andric   struct DependentAuto { bool IsPack; };
48940b57cec5SDimitry Andric 
48950b57cec5SDimitry Andric   /// Substitute the 'auto' specifier or deduced template specialization type
48960b57cec5SDimitry Andric   /// specifier within a type for a given replacement type.
48970b57cec5SDimitry Andric   class SubstituteDeducedTypeTransform :
48980b57cec5SDimitry Andric       public TreeTransform<SubstituteDeducedTypeTransform> {
48990b57cec5SDimitry Andric     QualType Replacement;
49000b57cec5SDimitry Andric     bool ReplacementIsPack;
49010b57cec5SDimitry Andric     bool UseTypeSugar;
49021db9f3b2SDimitry Andric     using inherited = TreeTransform<SubstituteDeducedTypeTransform>;
49030b57cec5SDimitry Andric 
49040b57cec5SDimitry Andric   public:
SubstituteDeducedTypeTransform(Sema & SemaRef,DependentAuto DA)49050b57cec5SDimitry Andric     SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
490604eeddc0SDimitry Andric         : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
49070b57cec5SDimitry Andric           ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
49080b57cec5SDimitry Andric 
SubstituteDeducedTypeTransform(Sema & SemaRef,QualType Replacement,bool UseTypeSugar=true)49090b57cec5SDimitry Andric     SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
49100b57cec5SDimitry Andric                                    bool UseTypeSugar = true)
49110b57cec5SDimitry Andric         : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
49120b57cec5SDimitry Andric           Replacement(Replacement), ReplacementIsPack(false),
49130b57cec5SDimitry Andric           UseTypeSugar(UseTypeSugar) {}
49140b57cec5SDimitry Andric 
TransformDesugared(TypeLocBuilder & TLB,DeducedTypeLoc TL)49150b57cec5SDimitry Andric     QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
49160b57cec5SDimitry Andric       assert(isa<TemplateTypeParmType>(Replacement) &&
49170b57cec5SDimitry Andric              "unexpected unsugared replacement kind");
49180b57cec5SDimitry Andric       QualType Result = Replacement;
49190b57cec5SDimitry Andric       TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
49200b57cec5SDimitry Andric       NewTL.setNameLoc(TL.getNameLoc());
49210b57cec5SDimitry Andric       return Result;
49220b57cec5SDimitry Andric     }
49230b57cec5SDimitry Andric 
TransformAutoType(TypeLocBuilder & TLB,AutoTypeLoc TL)49240b57cec5SDimitry Andric     QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
49250b57cec5SDimitry Andric       // If we're building the type pattern to deduce against, don't wrap the
49260b57cec5SDimitry Andric       // substituted type in an AutoType. Certain template deduction rules
49270b57cec5SDimitry Andric       // apply only when a template type parameter appears directly (and not if
49280b57cec5SDimitry Andric       // the parameter is found through desugaring). For instance:
49290b57cec5SDimitry Andric       //   auto &&lref = lvalue;
49300b57cec5SDimitry Andric       // must transform into "rvalue reference to T" not "rvalue reference to
49310b57cec5SDimitry Andric       // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
49320b57cec5SDimitry Andric       //
49330b57cec5SDimitry Andric       // FIXME: Is this still necessary?
49340b57cec5SDimitry Andric       if (!UseTypeSugar)
49350b57cec5SDimitry Andric         return TransformDesugared(TLB, TL);
49360b57cec5SDimitry Andric 
49370b57cec5SDimitry Andric       QualType Result = SemaRef.Context.getAutoType(
49380b57cec5SDimitry Andric           Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
493955e4f9d5SDimitry Andric           ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
494055e4f9d5SDimitry Andric           TL.getTypePtr()->getTypeConstraintArguments());
49410b57cec5SDimitry Andric       auto NewTL = TLB.push<AutoTypeLoc>(Result);
494255e4f9d5SDimitry Andric       NewTL.copy(TL);
49430b57cec5SDimitry Andric       return Result;
49440b57cec5SDimitry Andric     }
49450b57cec5SDimitry Andric 
TransformDeducedTemplateSpecializationType(TypeLocBuilder & TLB,DeducedTemplateSpecializationTypeLoc TL)49460b57cec5SDimitry Andric     QualType TransformDeducedTemplateSpecializationType(
49470b57cec5SDimitry Andric         TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
49480b57cec5SDimitry Andric       if (!UseTypeSugar)
49490b57cec5SDimitry Andric         return TransformDesugared(TLB, TL);
49500b57cec5SDimitry Andric 
49510b57cec5SDimitry Andric       QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
49520b57cec5SDimitry Andric           TL.getTypePtr()->getTemplateName(),
49530b57cec5SDimitry Andric           Replacement, Replacement.isNull());
49540b57cec5SDimitry Andric       auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
49550b57cec5SDimitry Andric       NewTL.setNameLoc(TL.getNameLoc());
49560b57cec5SDimitry Andric       return Result;
49570b57cec5SDimitry Andric     }
49580b57cec5SDimitry Andric 
TransformLambdaExpr(LambdaExpr * E)49590b57cec5SDimitry Andric     ExprResult TransformLambdaExpr(LambdaExpr *E) {
49600b57cec5SDimitry Andric       // Lambdas never need to be transformed.
49610b57cec5SDimitry Andric       return E;
49620b57cec5SDimitry Andric     }
TransformExceptionSpec(SourceLocation Loc,FunctionProtoType::ExceptionSpecInfo & ESI,SmallVectorImpl<QualType> & Exceptions,bool & Changed)49631db9f3b2SDimitry Andric     bool TransformExceptionSpec(SourceLocation Loc,
49641db9f3b2SDimitry Andric                                 FunctionProtoType::ExceptionSpecInfo &ESI,
49651db9f3b2SDimitry Andric                                 SmallVectorImpl<QualType> &Exceptions,
49661db9f3b2SDimitry Andric                                 bool &Changed) {
49671db9f3b2SDimitry Andric       if (ESI.Type == EST_Uninstantiated) {
49681db9f3b2SDimitry Andric         ESI.instantiate();
49691db9f3b2SDimitry Andric         Changed = true;
49701db9f3b2SDimitry Andric       }
49711db9f3b2SDimitry Andric       return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
49721db9f3b2SDimitry Andric     }
49730b57cec5SDimitry Andric 
Apply(TypeLoc TL)49740b57cec5SDimitry Andric     QualType Apply(TypeLoc TL) {
49750b57cec5SDimitry Andric       // Create some scratch storage for the transformed type locations.
49760b57cec5SDimitry Andric       // FIXME: We're just going to throw this information away. Don't build it.
49770b57cec5SDimitry Andric       TypeLocBuilder TLB;
49780b57cec5SDimitry Andric       TLB.reserve(TL.getFullDataSize());
49790b57cec5SDimitry Andric       return TransformType(TLB, TL);
49800b57cec5SDimitry Andric     }
49810b57cec5SDimitry Andric   };
49820b57cec5SDimitry Andric 
49830b57cec5SDimitry Andric } // namespace
49840b57cec5SDimitry Andric 
CheckDeducedPlaceholderConstraints(Sema & S,const AutoType & Type,AutoTypeLoc TypeLoc,QualType Deduced)4985bdd1243dSDimitry Andric static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
4986bdd1243dSDimitry Andric                                                AutoTypeLoc TypeLoc,
4987bdd1243dSDimitry Andric                                                QualType Deduced) {
498855e4f9d5SDimitry Andric   ConstraintSatisfaction Satisfaction;
498955e4f9d5SDimitry Andric   ConceptDecl *Concept = Type.getTypeConstraintConcept();
499055e4f9d5SDimitry Andric   TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
499155e4f9d5SDimitry Andric                                         TypeLoc.getRAngleLoc());
499255e4f9d5SDimitry Andric   TemplateArgs.addArgument(
499355e4f9d5SDimitry Andric       TemplateArgumentLoc(TemplateArgument(Deduced),
499455e4f9d5SDimitry Andric                           S.Context.getTrivialTypeSourceInfo(
499555e4f9d5SDimitry Andric                               Deduced, TypeLoc.getNameLoc())));
499655e4f9d5SDimitry Andric   for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
499755e4f9d5SDimitry Andric     TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
499855e4f9d5SDimitry Andric 
4999bdd1243dSDimitry Andric   llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
500055e4f9d5SDimitry Andric   if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
5001bdd1243dSDimitry Andric                                   /*PartialTemplateArgs=*/false,
5002bdd1243dSDimitry Andric                                   SugaredConverted, CanonicalConverted))
5003bdd1243dSDimitry Andric     return true;
5004bdd1243dSDimitry Andric   MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
5005bdd1243dSDimitry Andric                                        /*Final=*/false);
5006*0fca6ea1SDimitry Andric   // Build up an EvaluationContext with an ImplicitConceptSpecializationDecl so
5007*0fca6ea1SDimitry Andric   // that the template arguments of the constraint can be preserved. For
5008*0fca6ea1SDimitry Andric   // example:
5009*0fca6ea1SDimitry Andric   //
5010*0fca6ea1SDimitry Andric   //  template <class T>
5011*0fca6ea1SDimitry Andric   //  concept C = []<D U = void>() { return true; }();
5012*0fca6ea1SDimitry Andric   //
5013*0fca6ea1SDimitry Andric   // We need the argument for T while evaluating type constraint D in
5014*0fca6ea1SDimitry Andric   // building the CallExpr to the lambda.
5015*0fca6ea1SDimitry Andric   EnterExpressionEvaluationContext EECtx(
5016*0fca6ea1SDimitry Andric       S, Sema::ExpressionEvaluationContext::Unevaluated,
5017*0fca6ea1SDimitry Andric       ImplicitConceptSpecializationDecl::Create(
5018*0fca6ea1SDimitry Andric           S.getASTContext(), Concept->getDeclContext(), Concept->getLocation(),
5019*0fca6ea1SDimitry Andric           CanonicalConverted));
502055e4f9d5SDimitry Andric   if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
5021bdd1243dSDimitry Andric                                     MLTAL, TypeLoc.getLocalSourceRange(),
502255e4f9d5SDimitry Andric                                     Satisfaction))
5023bdd1243dSDimitry Andric     return true;
502455e4f9d5SDimitry Andric   if (!Satisfaction.IsSatisfied) {
502555e4f9d5SDimitry Andric     std::string Buf;
502655e4f9d5SDimitry Andric     llvm::raw_string_ostream OS(Buf);
502755e4f9d5SDimitry Andric     OS << "'" << Concept->getName();
502855e4f9d5SDimitry Andric     if (TypeLoc.hasExplicitTemplateArgs()) {
5029fe6060f1SDimitry Andric       printTemplateArgumentList(
5030fe6060f1SDimitry Andric           OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
5031fe6060f1SDimitry Andric           Type.getTypeConstraintConcept()->getTemplateParameters());
503255e4f9d5SDimitry Andric     }
503355e4f9d5SDimitry Andric     OS << "'";
503455e4f9d5SDimitry Andric     OS.flush();
503555e4f9d5SDimitry Andric     S.Diag(TypeLoc.getConceptNameLoc(),
503655e4f9d5SDimitry Andric            diag::err_placeholder_constraints_not_satisfied)
503755e4f9d5SDimitry Andric         << Deduced << Buf << TypeLoc.getLocalSourceRange();
503855e4f9d5SDimitry Andric     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
5039bdd1243dSDimitry Andric     return true;
504055e4f9d5SDimitry Andric   }
5041bdd1243dSDimitry Andric   return false;
504255e4f9d5SDimitry Andric }
504355e4f9d5SDimitry Andric 
5044*0fca6ea1SDimitry Andric TemplateDeductionResult
DeduceAutoType(TypeLoc Type,Expr * Init,QualType & Result,TemplateDeductionInfo & Info,bool DependentDeduction,bool IgnoreConstraints,TemplateSpecCandidateSet * FailedTSC)504506c3fb27SDimitry Andric Sema::DeduceAutoType(TypeLoc Type, Expr *Init, QualType &Result,
504606c3fb27SDimitry Andric                      TemplateDeductionInfo &Info, bool DependentDeduction,
504706c3fb27SDimitry Andric                      bool IgnoreConstraints,
504806c3fb27SDimitry Andric                      TemplateSpecCandidateSet *FailedTSC) {
5049bdd1243dSDimitry Andric   assert(DependentDeduction || Info.getDeducedDepth() == 0);
50505ffd83dbSDimitry Andric   if (Init->containsErrors())
5051*0fca6ea1SDimitry Andric     return TemplateDeductionResult::AlreadyDiagnosed;
5052bdd1243dSDimitry Andric 
5053bdd1243dSDimitry Andric   const AutoType *AT = Type.getType()->getContainedAutoType();
5054bdd1243dSDimitry Andric   assert(AT);
5055bdd1243dSDimitry Andric 
5056bdd1243dSDimitry Andric   if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
50570b57cec5SDimitry Andric     ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
50580b57cec5SDimitry Andric     if (NonPlaceholder.isInvalid())
5059*0fca6ea1SDimitry Andric       return TemplateDeductionResult::AlreadyDiagnosed;
50600b57cec5SDimitry Andric     Init = NonPlaceholder.get();
50610b57cec5SDimitry Andric   }
50620b57cec5SDimitry Andric 
50630b57cec5SDimitry Andric   DependentAuto DependentResult = {
50640b57cec5SDimitry Andric       /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
50650b57cec5SDimitry Andric 
5066bdd1243dSDimitry Andric   if (!DependentDeduction &&
5067480093f4SDimitry Andric       (Type.getType()->isDependentType() || Init->isTypeDependent() ||
5068480093f4SDimitry Andric        Init->containsUnexpandedParameterPack())) {
50690b57cec5SDimitry Andric     Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
50700b57cec5SDimitry Andric     assert(!Result.isNull() && "substituting DependentTy can't fail");
5071*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
50720b57cec5SDimitry Andric   }
50730b57cec5SDimitry Andric 
50745f757f3fSDimitry Andric   // Make sure that we treat 'char[]' equaly as 'char*' in C23 mode.
50755f757f3fSDimitry Andric   auto *String = dyn_cast<StringLiteral>(Init);
50765f757f3fSDimitry Andric   if (getLangOpts().C23 && String && Type.getType()->isArrayType()) {
50775f757f3fSDimitry Andric     Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
50785f757f3fSDimitry Andric     TypeLoc TL = TypeLoc(Init->getType(), Type.getOpaqueData());
50795f757f3fSDimitry Andric     Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(TL);
50805f757f3fSDimitry Andric     assert(!Result.isNull() && "substituting DependentTy can't fail");
5081*0fca6ea1SDimitry Andric     return TemplateDeductionResult::Success;
50825f757f3fSDimitry Andric   }
50835f757f3fSDimitry Andric 
50845f757f3fSDimitry Andric   // Emit a warning if 'auto*' is used in pedantic and in C23 mode.
50855f757f3fSDimitry Andric   if (getLangOpts().C23 && Type.getType()->isPointerType()) {
50865f757f3fSDimitry Andric     Diag(Type.getBeginLoc(), diag::ext_c23_auto_non_plain_identifier);
50875f757f3fSDimitry Andric   }
50885f757f3fSDimitry Andric 
5089bdd1243dSDimitry Andric   auto *InitList = dyn_cast<InitListExpr>(Init);
5090bdd1243dSDimitry Andric   if (!getLangOpts().CPlusPlus && InitList) {
50915f757f3fSDimitry Andric     Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c)
50925f757f3fSDimitry Andric         << (int)AT->getKeyword() << getLangOpts().C23;
5093*0fca6ea1SDimitry Andric     return TemplateDeductionResult::AlreadyDiagnosed;
50940b57cec5SDimitry Andric   }
50950b57cec5SDimitry Andric 
50960b57cec5SDimitry Andric   // Deduce type of TemplParam in Func(Init)
50970b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 1> Deduced;
50980b57cec5SDimitry Andric   Deduced.resize(1);
50990b57cec5SDimitry Andric 
51000b57cec5SDimitry Andric   // If deduction failed, don't diagnose if the initializer is dependent; it
51010b57cec5SDimitry Andric   // might acquire a matching type in the instantiation.
5102bdd1243dSDimitry Andric   auto DeductionFailed = [&](TemplateDeductionResult TDK) {
51030b57cec5SDimitry Andric     if (Init->isTypeDependent()) {
51040b57cec5SDimitry Andric       Result =
51050b57cec5SDimitry Andric           SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
51060b57cec5SDimitry Andric       assert(!Result.isNull() && "substituting DependentTy can't fail");
5107*0fca6ea1SDimitry Andric       return TemplateDeductionResult::Success;
51080b57cec5SDimitry Andric     }
5109bdd1243dSDimitry Andric     return TDK;
51100b57cec5SDimitry Andric   };
51110b57cec5SDimitry Andric 
51120b57cec5SDimitry Andric   SmallVector<OriginalCallArg, 4> OriginalCallArgs;
51130b57cec5SDimitry Andric 
5114bdd1243dSDimitry Andric   QualType DeducedType;
5115bdd1243dSDimitry Andric   // If this is a 'decltype(auto)' specifier, do the decltype dance.
5116bdd1243dSDimitry Andric   if (AT->isDecltypeAuto()) {
51170b57cec5SDimitry Andric     if (InitList) {
5118bdd1243dSDimitry Andric       Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
5119*0fca6ea1SDimitry Andric       return TemplateDeductionResult::AlreadyDiagnosed;
5120bdd1243dSDimitry Andric     }
51210b57cec5SDimitry Andric 
5122bdd1243dSDimitry Andric     DeducedType = getDecltypeForExpr(Init);
5123bdd1243dSDimitry Andric     assert(!DeducedType.isNull());
5124bdd1243dSDimitry Andric   } else {
5125bdd1243dSDimitry Andric     LocalInstantiationScope InstScope(*this);
5126bdd1243dSDimitry Andric 
5127bdd1243dSDimitry Andric     // Build template<class TemplParam> void Func(FuncParam);
5128bdd1243dSDimitry Andric     SourceLocation Loc = Init->getExprLoc();
5129bdd1243dSDimitry Andric     TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
5130bdd1243dSDimitry Andric         Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
5131bdd1243dSDimitry Andric         nullptr, false, false, false);
5132bdd1243dSDimitry Andric     QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
5133bdd1243dSDimitry Andric     NamedDecl *TemplParamPtr = TemplParam;
5134bdd1243dSDimitry Andric     FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
5135bdd1243dSDimitry Andric         Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
5136bdd1243dSDimitry Andric 
5137bdd1243dSDimitry Andric     if (InitList) {
5138bdd1243dSDimitry Andric       // Notionally, we substitute std::initializer_list<T> for 'auto' and
5139bdd1243dSDimitry Andric       // deduce against that. Such deduction only succeeds if removing
5140bdd1243dSDimitry Andric       // cv-qualifiers and references results in std::initializer_list<T>.
5141bdd1243dSDimitry Andric       if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
5142*0fca6ea1SDimitry Andric         return TemplateDeductionResult::Invalid;
5143a7dea167SDimitry Andric 
51440b57cec5SDimitry Andric       SourceRange DeducedFromInitRange;
5145bdd1243dSDimitry Andric       for (Expr *Init : InitList->inits()) {
5146bdd1243dSDimitry Andric         // Resolving a core issue: a braced-init-list containing any designators
5147bdd1243dSDimitry Andric         // is a non-deduced context.
5148bdd1243dSDimitry Andric         if (isa<DesignatedInitExpr>(Init))
5149*0fca6ea1SDimitry Andric           return TemplateDeductionResult::Invalid;
51500b57cec5SDimitry Andric         if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
51515f757f3fSDimitry Andric                 *this, TemplateParamsSt.get(), 0, TemplArg, Init->getType(),
51525f757f3fSDimitry Andric                 Init->Classify(getASTContext()), Init, Info, Deduced,
5153bdd1243dSDimitry Andric                 OriginalCallArgs, /*Decomposed=*/true,
5154*0fca6ea1SDimitry Andric                 /*ArgIdx=*/0, /*TDF=*/0);
5155*0fca6ea1SDimitry Andric             TDK != TemplateDeductionResult::Success) {
5156*0fca6ea1SDimitry Andric           if (TDK == TemplateDeductionResult::Inconsistent) {
5157bdd1243dSDimitry Andric             Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
5158bdd1243dSDimitry Andric                 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
5159bdd1243dSDimitry Andric                 << Init->getSourceRange();
5160*0fca6ea1SDimitry Andric             return DeductionFailed(TemplateDeductionResult::AlreadyDiagnosed);
5161bdd1243dSDimitry Andric           }
5162bdd1243dSDimitry Andric           return DeductionFailed(TDK);
5163bdd1243dSDimitry Andric         }
51640b57cec5SDimitry Andric 
51650b57cec5SDimitry Andric         if (DeducedFromInitRange.isInvalid() &&
51660b57cec5SDimitry Andric             Deduced[0].getKind() != TemplateArgument::Null)
51670b57cec5SDimitry Andric           DeducedFromInitRange = Init->getSourceRange();
51680b57cec5SDimitry Andric       }
51690b57cec5SDimitry Andric     } else {
51700b57cec5SDimitry Andric       if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
51710b57cec5SDimitry Andric         Diag(Loc, diag::err_auto_bitfield);
5172*0fca6ea1SDimitry Andric         return TemplateDeductionResult::AlreadyDiagnosed;
51730b57cec5SDimitry Andric       }
5174bdd1243dSDimitry Andric       QualType FuncParam =
5175bdd1243dSDimitry Andric           SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
5176bdd1243dSDimitry Andric       assert(!FuncParam.isNull() &&
5177bdd1243dSDimitry Andric              "substituting template parameter for 'auto' failed");
51780b57cec5SDimitry Andric       if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
51795f757f3fSDimitry Andric               *this, TemplateParamsSt.get(), 0, FuncParam, Init->getType(),
51805f757f3fSDimitry Andric               Init->Classify(getASTContext()), Init, Info, Deduced,
518106c3fb27SDimitry Andric               OriginalCallArgs, /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0,
5182*0fca6ea1SDimitry Andric               FailedTSC);
5183*0fca6ea1SDimitry Andric           TDK != TemplateDeductionResult::Success)
5184bdd1243dSDimitry Andric         return DeductionFailed(TDK);
51850b57cec5SDimitry Andric     }
51860b57cec5SDimitry Andric 
51870b57cec5SDimitry Andric     // Could be null if somehow 'auto' appears in a non-deduced context.
51880b57cec5SDimitry Andric     if (Deduced[0].getKind() != TemplateArgument::Type)
5189*0fca6ea1SDimitry Andric       return DeductionFailed(TemplateDeductionResult::Incomplete);
5190bdd1243dSDimitry Andric     DeducedType = Deduced[0].getAsType();
51910b57cec5SDimitry Andric 
51920b57cec5SDimitry Andric     if (InitList) {
51930b57cec5SDimitry Andric       DeducedType = BuildStdInitializerList(DeducedType, Loc);
51940b57cec5SDimitry Andric       if (DeducedType.isNull())
5195*0fca6ea1SDimitry Andric         return TemplateDeductionResult::AlreadyDiagnosed;
5196bdd1243dSDimitry Andric     }
51970b57cec5SDimitry Andric   }
51980b57cec5SDimitry Andric 
5199bdd1243dSDimitry Andric   if (!Result.isNull()) {
5200bdd1243dSDimitry Andric     if (!Context.hasSameType(DeducedType, Result)) {
5201bdd1243dSDimitry Andric       Info.FirstArg = Result;
5202bdd1243dSDimitry Andric       Info.SecondArg = DeducedType;
5203*0fca6ea1SDimitry Andric       return DeductionFailed(TemplateDeductionResult::Inconsistent);
520455e4f9d5SDimitry Andric     }
5205bdd1243dSDimitry Andric     DeducedType = Context.getCommonSugaredType(Result, DeducedType);
520655e4f9d5SDimitry Andric   }
520755e4f9d5SDimitry Andric 
5208bdd1243dSDimitry Andric   if (AT->isConstrained() && !IgnoreConstraints &&
5209bdd1243dSDimitry Andric       CheckDeducedPlaceholderConstraints(
5210bdd1243dSDimitry Andric           *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
5211*0fca6ea1SDimitry Andric     return TemplateDeductionResult::AlreadyDiagnosed;
5212bdd1243dSDimitry Andric 
52130b57cec5SDimitry Andric   Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
52140b57cec5SDimitry Andric   if (Result.isNull())
5215*0fca6ea1SDimitry Andric     return TemplateDeductionResult::AlreadyDiagnosed;
52160b57cec5SDimitry Andric 
52170b57cec5SDimitry Andric   // Check that the deduced argument type is compatible with the original
52180b57cec5SDimitry Andric   // argument type per C++ [temp.deduct.call]p4.
52190b57cec5SDimitry Andric   QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
52200b57cec5SDimitry Andric   for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
52210b57cec5SDimitry Andric     assert((bool)InitList == OriginalArg.DecomposedParam &&
52220b57cec5SDimitry Andric            "decomposed non-init-list in auto deduction?");
52230b57cec5SDimitry Andric     if (auto TDK =
5224*0fca6ea1SDimitry Andric             CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA);
5225*0fca6ea1SDimitry Andric         TDK != TemplateDeductionResult::Success) {
52260b57cec5SDimitry Andric       Result = QualType();
5227bdd1243dSDimitry Andric       return DeductionFailed(TDK);
52280b57cec5SDimitry Andric     }
52290b57cec5SDimitry Andric   }
52300b57cec5SDimitry Andric 
5231*0fca6ea1SDimitry Andric   return TemplateDeductionResult::Success;
52320b57cec5SDimitry Andric }
52330b57cec5SDimitry Andric 
SubstAutoType(QualType TypeWithAuto,QualType TypeToReplaceAuto)52340b57cec5SDimitry Andric QualType Sema::SubstAutoType(QualType TypeWithAuto,
52350b57cec5SDimitry Andric                              QualType TypeToReplaceAuto) {
5236349cc55cSDimitry Andric   assert(TypeToReplaceAuto != Context.DependentTy);
52370b57cec5SDimitry Andric   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
52380b57cec5SDimitry Andric       .TransformType(TypeWithAuto);
52390b57cec5SDimitry Andric }
52400b57cec5SDimitry Andric 
SubstAutoTypeSourceInfo(TypeSourceInfo * TypeWithAuto,QualType TypeToReplaceAuto)52410b57cec5SDimitry Andric TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
52420b57cec5SDimitry Andric                                               QualType TypeToReplaceAuto) {
5243349cc55cSDimitry Andric   assert(TypeToReplaceAuto != Context.DependentTy);
52440b57cec5SDimitry Andric   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
52450b57cec5SDimitry Andric       .TransformType(TypeWithAuto);
52460b57cec5SDimitry Andric }
52470b57cec5SDimitry Andric 
SubstAutoTypeDependent(QualType TypeWithAuto)5248349cc55cSDimitry Andric QualType Sema::SubstAutoTypeDependent(QualType TypeWithAuto) {
5249349cc55cSDimitry Andric   return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5250349cc55cSDimitry Andric       .TransformType(TypeWithAuto);
5251349cc55cSDimitry Andric }
5252349cc55cSDimitry Andric 
5253349cc55cSDimitry Andric TypeSourceInfo *
SubstAutoTypeSourceInfoDependent(TypeSourceInfo * TypeWithAuto)5254349cc55cSDimitry Andric Sema::SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto) {
5255349cc55cSDimitry Andric   return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
5256349cc55cSDimitry Andric       .TransformType(TypeWithAuto);
5257349cc55cSDimitry Andric }
5258349cc55cSDimitry Andric 
ReplaceAutoType(QualType TypeWithAuto,QualType TypeToReplaceAuto)52590b57cec5SDimitry Andric QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
52600b57cec5SDimitry Andric                                QualType TypeToReplaceAuto) {
52610b57cec5SDimitry Andric   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
52620b57cec5SDimitry Andric                                         /*UseTypeSugar*/ false)
52630b57cec5SDimitry Andric       .TransformType(TypeWithAuto);
52640b57cec5SDimitry Andric }
52650b57cec5SDimitry Andric 
ReplaceAutoTypeSourceInfo(TypeSourceInfo * TypeWithAuto,QualType TypeToReplaceAuto)5266e63539f3SDimitry Andric TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
5267e63539f3SDimitry Andric                                                 QualType TypeToReplaceAuto) {
5268e63539f3SDimitry Andric   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
5269e63539f3SDimitry Andric                                         /*UseTypeSugar*/ false)
5270e63539f3SDimitry Andric       .TransformType(TypeWithAuto);
5271e63539f3SDimitry Andric }
5272e63539f3SDimitry Andric 
DiagnoseAutoDeductionFailure(const VarDecl * VDecl,const Expr * Init)5273*0fca6ea1SDimitry Andric void Sema::DiagnoseAutoDeductionFailure(const VarDecl *VDecl,
5274*0fca6ea1SDimitry Andric                                         const Expr *Init) {
52750b57cec5SDimitry Andric   if (isa<InitListExpr>(Init))
52760b57cec5SDimitry Andric     Diag(VDecl->getLocation(),
52770b57cec5SDimitry Andric          VDecl->isInitCapture()
52780b57cec5SDimitry Andric              ? diag::err_init_capture_deduction_failure_from_init_list
52790b57cec5SDimitry Andric              : diag::err_auto_var_deduction_failure_from_init_list)
52800b57cec5SDimitry Andric       << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
52810b57cec5SDimitry Andric   else
52820b57cec5SDimitry Andric     Diag(VDecl->getLocation(),
52830b57cec5SDimitry Andric          VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
52840b57cec5SDimitry Andric                                 : diag::err_auto_var_deduction_failure)
52850b57cec5SDimitry Andric       << VDecl->getDeclName() << VDecl->getType() << Init->getType()
52860b57cec5SDimitry Andric       << Init->getSourceRange();
52870b57cec5SDimitry Andric }
52880b57cec5SDimitry Andric 
DeduceReturnType(FunctionDecl * FD,SourceLocation Loc,bool Diagnose)52890b57cec5SDimitry Andric bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
52900b57cec5SDimitry Andric                             bool Diagnose) {
52910b57cec5SDimitry Andric   assert(FD->getReturnType()->isUndeducedType());
52920b57cec5SDimitry Andric 
52930b57cec5SDimitry Andric   // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
52940b57cec5SDimitry Andric   // within the return type from the call operator's type.
52950b57cec5SDimitry Andric   if (isLambdaConversionOperator(FD)) {
52960b57cec5SDimitry Andric     CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
52970b57cec5SDimitry Andric     FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
52980b57cec5SDimitry Andric 
52990b57cec5SDimitry Andric     // For a generic lambda, instantiate the call operator if needed.
53000b57cec5SDimitry Andric     if (auto *Args = FD->getTemplateSpecializationArgs()) {
53010b57cec5SDimitry Andric       CallOp = InstantiateFunctionDeclaration(
53020b57cec5SDimitry Andric           CallOp->getDescribedFunctionTemplate(), Args, Loc);
53030b57cec5SDimitry Andric       if (!CallOp || CallOp->isInvalidDecl())
53040b57cec5SDimitry Andric         return true;
53050b57cec5SDimitry Andric 
53060b57cec5SDimitry Andric       // We might need to deduce the return type by instantiating the definition
53070b57cec5SDimitry Andric       // of the operator() function.
5308a7dea167SDimitry Andric       if (CallOp->getReturnType()->isUndeducedType()) {
5309a7dea167SDimitry Andric         runWithSufficientStackSpace(Loc, [&] {
53100b57cec5SDimitry Andric           InstantiateFunctionDefinition(Loc, CallOp);
5311a7dea167SDimitry Andric         });
5312a7dea167SDimitry Andric       }
53130b57cec5SDimitry Andric     }
53140b57cec5SDimitry Andric 
53150b57cec5SDimitry Andric     if (CallOp->isInvalidDecl())
53160b57cec5SDimitry Andric       return true;
53170b57cec5SDimitry Andric     assert(!CallOp->getReturnType()->isUndeducedType() &&
53180b57cec5SDimitry Andric            "failed to deduce lambda return type");
53190b57cec5SDimitry Andric 
53200b57cec5SDimitry Andric     // Build the new return type from scratch.
5321e8d8bef9SDimitry Andric     CallingConv RetTyCC = FD->getReturnType()
5322e8d8bef9SDimitry Andric                               ->getPointeeType()
5323e8d8bef9SDimitry Andric                               ->castAs<FunctionType>()
5324e8d8bef9SDimitry Andric                               ->getCallConv();
53250b57cec5SDimitry Andric     QualType RetType = getLambdaConversionFunctionResultType(
5326e8d8bef9SDimitry Andric         CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
53270b57cec5SDimitry Andric     if (FD->getReturnType()->getAs<PointerType>())
53280b57cec5SDimitry Andric       RetType = Context.getPointerType(RetType);
53290b57cec5SDimitry Andric     else {
53300b57cec5SDimitry Andric       assert(FD->getReturnType()->getAs<BlockPointerType>());
53310b57cec5SDimitry Andric       RetType = Context.getBlockPointerType(RetType);
53320b57cec5SDimitry Andric     }
53330b57cec5SDimitry Andric     Context.adjustDeducedFunctionResultType(FD, RetType);
53340b57cec5SDimitry Andric     return false;
53350b57cec5SDimitry Andric   }
53360b57cec5SDimitry Andric 
5337a7dea167SDimitry Andric   if (FD->getTemplateInstantiationPattern()) {
5338a7dea167SDimitry Andric     runWithSufficientStackSpace(Loc, [&] {
53390b57cec5SDimitry Andric       InstantiateFunctionDefinition(Loc, FD);
5340a7dea167SDimitry Andric     });
5341a7dea167SDimitry Andric   }
53420b57cec5SDimitry Andric 
53430b57cec5SDimitry Andric   bool StillUndeduced = FD->getReturnType()->isUndeducedType();
53440b57cec5SDimitry Andric   if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
53450b57cec5SDimitry Andric     Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
53460b57cec5SDimitry Andric     Diag(FD->getLocation(), diag::note_callee_decl) << FD;
53470b57cec5SDimitry Andric   }
53480b57cec5SDimitry Andric 
53490b57cec5SDimitry Andric   return StillUndeduced;
53500b57cec5SDimitry Andric }
53510b57cec5SDimitry Andric 
CheckIfFunctionSpecializationIsImmediate(FunctionDecl * FD,SourceLocation Loc)535206c3fb27SDimitry Andric bool Sema::CheckIfFunctionSpecializationIsImmediate(FunctionDecl *FD,
535306c3fb27SDimitry Andric                                                     SourceLocation Loc) {
535406c3fb27SDimitry Andric   assert(FD->isImmediateEscalating());
535506c3fb27SDimitry Andric 
535606c3fb27SDimitry Andric   if (isLambdaConversionOperator(FD)) {
535706c3fb27SDimitry Andric     CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
535806c3fb27SDimitry Andric     FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
535906c3fb27SDimitry Andric 
536006c3fb27SDimitry Andric     // For a generic lambda, instantiate the call operator if needed.
536106c3fb27SDimitry Andric     if (auto *Args = FD->getTemplateSpecializationArgs()) {
536206c3fb27SDimitry Andric       CallOp = InstantiateFunctionDeclaration(
536306c3fb27SDimitry Andric           CallOp->getDescribedFunctionTemplate(), Args, Loc);
536406c3fb27SDimitry Andric       if (!CallOp || CallOp->isInvalidDecl())
536506c3fb27SDimitry Andric         return true;
536606c3fb27SDimitry Andric       runWithSufficientStackSpace(
536706c3fb27SDimitry Andric           Loc, [&] { InstantiateFunctionDefinition(Loc, CallOp); });
536806c3fb27SDimitry Andric     }
536906c3fb27SDimitry Andric     return CallOp->isInvalidDecl();
537006c3fb27SDimitry Andric   }
537106c3fb27SDimitry Andric 
537206c3fb27SDimitry Andric   if (FD->getTemplateInstantiationPattern()) {
537306c3fb27SDimitry Andric     runWithSufficientStackSpace(
537406c3fb27SDimitry Andric         Loc, [&] { InstantiateFunctionDefinition(Loc, FD); });
537506c3fb27SDimitry Andric   }
537606c3fb27SDimitry Andric   return false;
537706c3fb27SDimitry Andric }
537806c3fb27SDimitry Andric 
GetImplicitObjectParameterType(ASTContext & Context,const CXXMethodDecl * Method,QualType RawType,bool IsOtherRvr)5379*0fca6ea1SDimitry Andric static QualType GetImplicitObjectParameterType(ASTContext &Context,
5380*0fca6ea1SDimitry Andric                                                const CXXMethodDecl *Method,
5381*0fca6ea1SDimitry Andric                                                QualType RawType,
5382*0fca6ea1SDimitry Andric                                                bool IsOtherRvr) {
5383*0fca6ea1SDimitry Andric   // C++20 [temp.func.order]p3.1, p3.2:
5384*0fca6ea1SDimitry Andric   //  - The type X(M) is "rvalue reference to cv A" if the optional
5385*0fca6ea1SDimitry Andric   //    ref-qualifier of M is && or if M has no ref-qualifier and the
5386*0fca6ea1SDimitry Andric   //    positionally-corresponding parameter of the other transformed template
5387*0fca6ea1SDimitry Andric   //    has rvalue reference type; if this determination depends recursively
5388*0fca6ea1SDimitry Andric   //    upon whether X(M) is an rvalue reference type, it is not considered to
5389*0fca6ea1SDimitry Andric   //    have rvalue reference type.
53900b57cec5SDimitry Andric   //
5391*0fca6ea1SDimitry Andric   //  - Otherwise, X(M) is "lvalue reference to cv A".
5392*0fca6ea1SDimitry Andric   assert(Method && !Method->isExplicitObjectMemberFunction() &&
5393*0fca6ea1SDimitry Andric          "expected a member function with no explicit object parameter");
5394*0fca6ea1SDimitry Andric 
5395*0fca6ea1SDimitry Andric   RawType = Context.getQualifiedType(RawType, Method->getMethodQualifiers());
5396*0fca6ea1SDimitry Andric   if (Method->getRefQualifier() == RQ_RValue ||
5397*0fca6ea1SDimitry Andric       (IsOtherRvr && Method->getRefQualifier() == RQ_None))
5398*0fca6ea1SDimitry Andric     return Context.getRValueReferenceType(RawType);
5399*0fca6ea1SDimitry Andric   return Context.getLValueReferenceType(RawType);
54000b57cec5SDimitry Andric }
54010b57cec5SDimitry Andric 
54020b57cec5SDimitry Andric /// Determine whether the function template \p FT1 is at least as
54030b57cec5SDimitry Andric /// specialized as \p FT2.
isAtLeastAsSpecializedAs(Sema & S,SourceLocation Loc,const FunctionTemplateDecl * FT1,const FunctionTemplateDecl * FT2,TemplatePartialOrderingContext TPOC,bool Reversed,const SmallVector<QualType> & Args1,const SmallVector<QualType> & Args2)5404*0fca6ea1SDimitry Andric static bool isAtLeastAsSpecializedAs(Sema &S, SourceLocation Loc,
5405*0fca6ea1SDimitry Andric                                      const FunctionTemplateDecl *FT1,
5406*0fca6ea1SDimitry Andric                                      const FunctionTemplateDecl *FT2,
54070b57cec5SDimitry Andric                                      TemplatePartialOrderingContext TPOC,
5408*0fca6ea1SDimitry Andric                                      bool Reversed,
5409*0fca6ea1SDimitry Andric                                      const SmallVector<QualType> &Args1,
5410*0fca6ea1SDimitry Andric                                      const SmallVector<QualType> &Args2) {
54115ffd83dbSDimitry Andric   assert(!Reversed || TPOC == TPOC_Call);
54125ffd83dbSDimitry Andric 
54130b57cec5SDimitry Andric   FunctionDecl *FD1 = FT1->getTemplatedDecl();
54140b57cec5SDimitry Andric   FunctionDecl *FD2 = FT2->getTemplatedDecl();
54150b57cec5SDimitry Andric   const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
54160b57cec5SDimitry Andric   const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
54170b57cec5SDimitry Andric 
54180b57cec5SDimitry Andric   assert(Proto1 && Proto2 && "Function templates must have prototypes");
54190b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
54200b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
54210b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
54220b57cec5SDimitry Andric 
54230b57cec5SDimitry Andric   // C++0x [temp.deduct.partial]p3:
54240b57cec5SDimitry Andric   //   The types used to determine the ordering depend on the context in which
54250b57cec5SDimitry Andric   //   the partial ordering is done:
54260b57cec5SDimitry Andric   TemplateDeductionInfo Info(Loc);
54270b57cec5SDimitry Andric   switch (TPOC) {
5428*0fca6ea1SDimitry Andric   case TPOC_Call:
54290b57cec5SDimitry Andric     if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
54300b57cec5SDimitry Andric                                 Args1.data(), Args1.size(), Info, Deduced,
5431*0fca6ea1SDimitry Andric                                 TDF_None, /*PartialOrdering=*/true) !=
5432*0fca6ea1SDimitry Andric         TemplateDeductionResult::Success)
54330b57cec5SDimitry Andric       return false;
54340b57cec5SDimitry Andric 
54350b57cec5SDimitry Andric     break;
54360b57cec5SDimitry Andric 
54370b57cec5SDimitry Andric   case TPOC_Conversion:
54380b57cec5SDimitry Andric     //   - In the context of a call to a conversion operator, the return types
54390b57cec5SDimitry Andric     //     of the conversion function templates are used.
54400b57cec5SDimitry Andric     if (DeduceTemplateArgumentsByTypeMatch(
54410b57cec5SDimitry Andric             S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
54420b57cec5SDimitry Andric             Info, Deduced, TDF_None,
5443*0fca6ea1SDimitry Andric             /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
54440b57cec5SDimitry Andric       return false;
54450b57cec5SDimitry Andric     break;
54460b57cec5SDimitry Andric 
54470b57cec5SDimitry Andric   case TPOC_Other:
54480b57cec5SDimitry Andric     //   - In other contexts (14.6.6.2) the function template's function type
54490b57cec5SDimitry Andric     //     is used.
5450*0fca6ea1SDimitry Andric     if (DeduceTemplateArgumentsByTypeMatch(
5451*0fca6ea1SDimitry Andric             S, TemplateParams, FD2->getType(), FD1->getType(), Info, Deduced,
5452*0fca6ea1SDimitry Andric             TDF_AllowCompatibleFunctionType,
5453*0fca6ea1SDimitry Andric             /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
54540b57cec5SDimitry Andric       return false;
54550b57cec5SDimitry Andric     break;
54560b57cec5SDimitry Andric   }
54570b57cec5SDimitry Andric 
54580b57cec5SDimitry Andric   // C++0x [temp.deduct.partial]p11:
54590b57cec5SDimitry Andric   //   In most cases, all template parameters must have values in order for
54600b57cec5SDimitry Andric   //   deduction to succeed, but for partial ordering purposes a template
54610b57cec5SDimitry Andric   //   parameter may remain without a value provided it is not used in the
54620b57cec5SDimitry Andric   //   types being used for partial ordering. [ Note: a template parameter used
54630b57cec5SDimitry Andric   //   in a non-deduced context is considered used. -end note]
54640b57cec5SDimitry Andric   unsigned ArgIdx = 0, NumArgs = Deduced.size();
54650b57cec5SDimitry Andric   for (; ArgIdx != NumArgs; ++ArgIdx)
54660b57cec5SDimitry Andric     if (Deduced[ArgIdx].isNull())
54670b57cec5SDimitry Andric       break;
54680b57cec5SDimitry Andric 
54690b57cec5SDimitry Andric   // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
54700b57cec5SDimitry Andric   // to substitute the deduced arguments back into the template and check that
54710b57cec5SDimitry Andric   // we get the right type.
54720b57cec5SDimitry Andric 
54730b57cec5SDimitry Andric   if (ArgIdx == NumArgs) {
54740b57cec5SDimitry Andric     // All template arguments were deduced. FT1 is at least as specialized
54750b57cec5SDimitry Andric     // as FT2.
54760b57cec5SDimitry Andric     return true;
54770b57cec5SDimitry Andric   }
54780b57cec5SDimitry Andric 
54790b57cec5SDimitry Andric   // Figure out which template parameters were used.
54800b57cec5SDimitry Andric   llvm::SmallBitVector UsedParameters(TemplateParams->size());
54810b57cec5SDimitry Andric   switch (TPOC) {
54820b57cec5SDimitry Andric   case TPOC_Call:
54830b57cec5SDimitry Andric     for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5484*0fca6ea1SDimitry Andric       ::MarkUsedTemplateParameters(S.Context, Args2[I], /*OnlyDeduced=*/false,
5485*0fca6ea1SDimitry Andric                                    TemplateParams->getDepth(), UsedParameters);
54860b57cec5SDimitry Andric     break;
54870b57cec5SDimitry Andric 
54880b57cec5SDimitry Andric   case TPOC_Conversion:
5489*0fca6ea1SDimitry Andric     ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(),
5490*0fca6ea1SDimitry Andric                                  /*OnlyDeduced=*/false,
54910b57cec5SDimitry Andric                                  TemplateParams->getDepth(), UsedParameters);
54920b57cec5SDimitry Andric     break;
54930b57cec5SDimitry Andric 
54940b57cec5SDimitry Andric   case TPOC_Other:
5495*0fca6ea1SDimitry Andric     // We do not deduce template arguments from the exception specification
5496*0fca6ea1SDimitry Andric     // when determining the primary template of a function template
5497*0fca6ea1SDimitry Andric     // specialization or when taking the address of a function template.
5498*0fca6ea1SDimitry Andric     // Therefore, we do not mark template parameters in the exception
5499*0fca6ea1SDimitry Andric     // specification as used during partial ordering to prevent the following
5500*0fca6ea1SDimitry Andric     // from being ambiguous:
5501*0fca6ea1SDimitry Andric     //
5502*0fca6ea1SDimitry Andric     //   template<typename T, typename U>
5503*0fca6ea1SDimitry Andric     //   void f(U) noexcept(noexcept(T())); // #1
5504*0fca6ea1SDimitry Andric     //
5505*0fca6ea1SDimitry Andric     //   template<typename T>
5506*0fca6ea1SDimitry Andric     //   void f(T*) noexcept; // #2
5507*0fca6ea1SDimitry Andric     //
5508*0fca6ea1SDimitry Andric     //   template<>
5509*0fca6ea1SDimitry Andric     //   void f<int>(int*) noexcept; // explicit specialization of #2
5510*0fca6ea1SDimitry Andric     //
5511*0fca6ea1SDimitry Andric     // Although there is no corresponding wording in the standard, this seems
5512*0fca6ea1SDimitry Andric     // to be the intended behavior given the definition of
5513*0fca6ea1SDimitry Andric     // 'deduction substitution loci' in [temp.deduct].
5514*0fca6ea1SDimitry Andric     ::MarkUsedTemplateParameters(
5515*0fca6ea1SDimitry Andric         S.Context,
5516*0fca6ea1SDimitry Andric         S.Context.getFunctionTypeWithExceptionSpec(FD2->getType(), EST_None),
5517*0fca6ea1SDimitry Andric         /*OnlyDeduced=*/false, TemplateParams->getDepth(), UsedParameters);
55180b57cec5SDimitry Andric     break;
55190b57cec5SDimitry Andric   }
55200b57cec5SDimitry Andric 
55210b57cec5SDimitry Andric   for (; ArgIdx != NumArgs; ++ArgIdx)
55220b57cec5SDimitry Andric     // If this argument had no value deduced but was used in one of the types
55230b57cec5SDimitry Andric     // used for partial ordering, then deduction fails.
55240b57cec5SDimitry Andric     if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
55250b57cec5SDimitry Andric       return false;
55260b57cec5SDimitry Andric 
55270b57cec5SDimitry Andric   return true;
55280b57cec5SDimitry Andric }
55290b57cec5SDimitry Andric 
getMoreSpecializedTemplate(FunctionTemplateDecl * FT1,FunctionTemplateDecl * FT2,SourceLocation Loc,TemplatePartialOrderingContext TPOC,unsigned NumCallArguments1,QualType RawObj1Ty,QualType RawObj2Ty,bool Reversed)553081ad6265SDimitry Andric FunctionTemplateDecl *Sema::getMoreSpecializedTemplate(
553181ad6265SDimitry Andric     FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
553281ad6265SDimitry Andric     TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5533*0fca6ea1SDimitry Andric     QualType RawObj1Ty, QualType RawObj2Ty, bool Reversed) {
5534*0fca6ea1SDimitry Andric   SmallVector<QualType> Args1;
5535*0fca6ea1SDimitry Andric   SmallVector<QualType> Args2;
5536*0fca6ea1SDimitry Andric   const FunctionDecl *FD1 = FT1->getTemplatedDecl();
5537*0fca6ea1SDimitry Andric   const FunctionDecl *FD2 = FT2->getTemplatedDecl();
5538*0fca6ea1SDimitry Andric   bool ShouldConvert1 = false;
5539*0fca6ea1SDimitry Andric   bool ShouldConvert2 = false;
5540*0fca6ea1SDimitry Andric   QualType Obj1Ty;
5541*0fca6ea1SDimitry Andric   QualType Obj2Ty;
5542*0fca6ea1SDimitry Andric   if (TPOC == TPOC_Call) {
5543*0fca6ea1SDimitry Andric     const FunctionProtoType *Proto1 =
5544*0fca6ea1SDimitry Andric         FD1->getType()->castAs<FunctionProtoType>();
5545*0fca6ea1SDimitry Andric     const FunctionProtoType *Proto2 =
5546*0fca6ea1SDimitry Andric         FD2->getType()->castAs<FunctionProtoType>();
5547480093f4SDimitry Andric 
5548*0fca6ea1SDimitry Andric     //   - In the context of a function call, the function parameter types are
5549*0fca6ea1SDimitry Andric     //     used.
5550*0fca6ea1SDimitry Andric     const CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5551*0fca6ea1SDimitry Andric     const CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5552*0fca6ea1SDimitry Andric     // C++20 [temp.func.order]p3
5553*0fca6ea1SDimitry Andric     //   [...] Each function template M that is a member function is
5554*0fca6ea1SDimitry Andric     //   considered to have a new first parameter of type
5555*0fca6ea1SDimitry Andric     //   X(M), described below, inserted in its function parameter list.
5556*0fca6ea1SDimitry Andric     //
5557*0fca6ea1SDimitry Andric     // Note that we interpret "that is a member function" as
5558*0fca6ea1SDimitry Andric     // "that is a member function with no expicit object argument".
5559*0fca6ea1SDimitry Andric     // Otherwise the ordering rules for methods with expicit objet arguments
5560*0fca6ea1SDimitry Andric     // against anything else make no sense.
5561*0fca6ea1SDimitry Andric     ShouldConvert1 = Method1 && !Method1->isExplicitObjectMemberFunction();
5562*0fca6ea1SDimitry Andric     ShouldConvert2 = Method2 && !Method2->isExplicitObjectMemberFunction();
5563*0fca6ea1SDimitry Andric     if (ShouldConvert1) {
5564*0fca6ea1SDimitry Andric       bool IsRValRef2 =
5565*0fca6ea1SDimitry Andric           ShouldConvert2
5566*0fca6ea1SDimitry Andric               ? Method2->getRefQualifier() == RQ_RValue
5567*0fca6ea1SDimitry Andric               : Proto2->param_type_begin()[0]->isRValueReferenceType();
5568*0fca6ea1SDimitry Andric       // Compare 'this' from Method1 against first parameter from Method2.
5569*0fca6ea1SDimitry Andric       Obj1Ty = GetImplicitObjectParameterType(this->Context, Method1, RawObj1Ty,
5570*0fca6ea1SDimitry Andric                                               IsRValRef2);
5571*0fca6ea1SDimitry Andric       Args1.push_back(Obj1Ty);
5572*0fca6ea1SDimitry Andric     }
5573*0fca6ea1SDimitry Andric     if (ShouldConvert2) {
5574*0fca6ea1SDimitry Andric       bool IsRValRef1 =
5575*0fca6ea1SDimitry Andric           ShouldConvert1
5576*0fca6ea1SDimitry Andric               ? Method1->getRefQualifier() == RQ_RValue
5577*0fca6ea1SDimitry Andric               : Proto1->param_type_begin()[0]->isRValueReferenceType();
5578*0fca6ea1SDimitry Andric       // Compare 'this' from Method2 against first parameter from Method1.
5579*0fca6ea1SDimitry Andric       Obj2Ty = GetImplicitObjectParameterType(this->Context, Method2, RawObj2Ty,
5580*0fca6ea1SDimitry Andric                                               IsRValRef1);
5581*0fca6ea1SDimitry Andric       Args2.push_back(Obj2Ty);
5582*0fca6ea1SDimitry Andric     }
5583*0fca6ea1SDimitry Andric     size_t NumComparedArguments = NumCallArguments1;
5584*0fca6ea1SDimitry Andric     // Either added an argument above or the prototype includes an explicit
5585*0fca6ea1SDimitry Andric     // object argument we need to count
5586*0fca6ea1SDimitry Andric     if (Method1)
5587*0fca6ea1SDimitry Andric       ++NumComparedArguments;
5588bdd1243dSDimitry Andric 
5589*0fca6ea1SDimitry Andric     Args1.insert(Args1.end(), Proto1->param_type_begin(),
5590*0fca6ea1SDimitry Andric                  Proto1->param_type_end());
5591*0fca6ea1SDimitry Andric     Args2.insert(Args2.end(), Proto2->param_type_begin(),
5592*0fca6ea1SDimitry Andric                  Proto2->param_type_end());
5593*0fca6ea1SDimitry Andric 
5594*0fca6ea1SDimitry Andric     // C++ [temp.func.order]p5:
5595*0fca6ea1SDimitry Andric     //   The presence of unused ellipsis and default arguments has no effect on
5596*0fca6ea1SDimitry Andric     //   the partial ordering of function templates.
5597*0fca6ea1SDimitry Andric     Args1.resize(std::min(Args1.size(), NumComparedArguments));
5598*0fca6ea1SDimitry Andric     Args2.resize(std::min(Args2.size(), NumComparedArguments));
5599*0fca6ea1SDimitry Andric 
5600*0fca6ea1SDimitry Andric     if (Reversed)
5601*0fca6ea1SDimitry Andric       std::reverse(Args2.begin(), Args2.end());
5602*0fca6ea1SDimitry Andric   }
5603*0fca6ea1SDimitry Andric   bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, Reversed,
5604*0fca6ea1SDimitry Andric                                           Args1, Args2);
5605*0fca6ea1SDimitry Andric   bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC, Reversed,
5606*0fca6ea1SDimitry Andric                                           Args2, Args1);
5607bdd1243dSDimitry Andric   // C++ [temp.deduct.partial]p10:
5608bdd1243dSDimitry Andric   //   F is more specialized than G if F is at least as specialized as G and G
5609bdd1243dSDimitry Andric   //   is not at least as specialized as F.
5610bdd1243dSDimitry Andric   if (Better1 != Better2) // We have a clear winner
5611bdd1243dSDimitry Andric     return Better1 ? FT1 : FT2;
5612bdd1243dSDimitry Andric 
5613bdd1243dSDimitry Andric   if (!Better1 && !Better2) // Neither is better than the other
561481ad6265SDimitry Andric     return nullptr;
5615bdd1243dSDimitry Andric 
5616bdd1243dSDimitry Andric   // C++ [temp.deduct.partial]p11:
5617bdd1243dSDimitry Andric   //   ... and if G has a trailing function parameter pack for which F does not
5618bdd1243dSDimitry Andric   //   have a corresponding parameter, and if F does not have a trailing
5619bdd1243dSDimitry Andric   //   function parameter pack, then F is more specialized than G.
5620*0fca6ea1SDimitry Andric 
5621*0fca6ea1SDimitry Andric   SmallVector<QualType> Param1;
5622*0fca6ea1SDimitry Andric   Param1.reserve(FD1->param_size() + ShouldConvert1);
5623*0fca6ea1SDimitry Andric   if (ShouldConvert1)
5624*0fca6ea1SDimitry Andric     Param1.push_back(Obj1Ty);
5625*0fca6ea1SDimitry Andric   for (const auto &P : FD1->parameters())
5626*0fca6ea1SDimitry Andric     Param1.push_back(P->getType());
5627*0fca6ea1SDimitry Andric 
5628*0fca6ea1SDimitry Andric   SmallVector<QualType> Param2;
5629*0fca6ea1SDimitry Andric   Param2.reserve(FD2->param_size() + ShouldConvert2);
5630*0fca6ea1SDimitry Andric   if (ShouldConvert2)
5631*0fca6ea1SDimitry Andric     Param2.push_back(Obj2Ty);
5632*0fca6ea1SDimitry Andric   for (const auto &P : FD2->parameters())
5633*0fca6ea1SDimitry Andric     Param2.push_back(P->getType());
5634*0fca6ea1SDimitry Andric 
5635*0fca6ea1SDimitry Andric   unsigned NumParams1 = Param1.size();
5636*0fca6ea1SDimitry Andric   unsigned NumParams2 = Param2.size();
5637*0fca6ea1SDimitry Andric 
5638*0fca6ea1SDimitry Andric   bool Variadic1 =
5639*0fca6ea1SDimitry Andric       FD1->param_size() && FD1->parameters().back()->isParameterPack();
5640*0fca6ea1SDimitry Andric   bool Variadic2 =
5641*0fca6ea1SDimitry Andric       FD2->param_size() && FD2->parameters().back()->isParameterPack();
5642bdd1243dSDimitry Andric   if (Variadic1 != Variadic2) {
5643bdd1243dSDimitry Andric     if (Variadic1 && NumParams1 > NumParams2)
5644bdd1243dSDimitry Andric       return FT2;
5645bdd1243dSDimitry Andric     if (Variadic2 && NumParams2 > NumParams1)
5646bdd1243dSDimitry Andric       return FT1;
5647bdd1243dSDimitry Andric   }
5648bdd1243dSDimitry Andric 
5649bdd1243dSDimitry Andric   // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5650bdd1243dSDimitry Andric   // there is no wording or even resolution for this issue.
5651bdd1243dSDimitry Andric   for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
5652*0fca6ea1SDimitry Andric     QualType T1 = Param1[i].getCanonicalType();
5653*0fca6ea1SDimitry Andric     QualType T2 = Param2[i].getCanonicalType();
5654bdd1243dSDimitry Andric     auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5655bdd1243dSDimitry Andric     auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5656bdd1243dSDimitry Andric     if (!TST1 || !TST2)
5657bdd1243dSDimitry Andric       continue;
5658bdd1243dSDimitry Andric     const TemplateArgument &TA1 = TST1->template_arguments().back();
5659bdd1243dSDimitry Andric     if (TA1.getKind() == TemplateArgument::Pack) {
5660bdd1243dSDimitry Andric       assert(TST1->template_arguments().size() ==
5661bdd1243dSDimitry Andric              TST2->template_arguments().size());
5662bdd1243dSDimitry Andric       const TemplateArgument &TA2 = TST2->template_arguments().back();
5663bdd1243dSDimitry Andric       assert(TA2.getKind() == TemplateArgument::Pack);
5664bdd1243dSDimitry Andric       unsigned PackSize1 = TA1.pack_size();
5665bdd1243dSDimitry Andric       unsigned PackSize2 = TA2.pack_size();
5666bdd1243dSDimitry Andric       bool IsPackExpansion1 =
5667bdd1243dSDimitry Andric           PackSize1 && TA1.pack_elements().back().isPackExpansion();
5668bdd1243dSDimitry Andric       bool IsPackExpansion2 =
5669bdd1243dSDimitry Andric           PackSize2 && TA2.pack_elements().back().isPackExpansion();
5670bdd1243dSDimitry Andric       if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5671bdd1243dSDimitry Andric         if (PackSize1 > PackSize2 && IsPackExpansion1)
5672bdd1243dSDimitry Andric           return FT2;
5673bdd1243dSDimitry Andric         if (PackSize1 < PackSize2 && IsPackExpansion2)
5674bdd1243dSDimitry Andric           return FT1;
5675bdd1243dSDimitry Andric       }
5676bdd1243dSDimitry Andric     }
5677bdd1243dSDimitry Andric   }
5678bdd1243dSDimitry Andric 
5679bdd1243dSDimitry Andric   if (!Context.getLangOpts().CPlusPlus20)
5680bdd1243dSDimitry Andric     return nullptr;
5681bdd1243dSDimitry Andric 
5682bdd1243dSDimitry Andric   // Match GCC on not implementing [temp.func.order]p6.2.1.
5683bdd1243dSDimitry Andric 
5684bdd1243dSDimitry Andric   // C++20 [temp.func.order]p6:
5685bdd1243dSDimitry Andric   //   If deduction against the other template succeeds for both transformed
5686bdd1243dSDimitry Andric   //   templates, constraints can be considered as follows:
5687bdd1243dSDimitry Andric 
5688bdd1243dSDimitry Andric   // C++20 [temp.func.order]p6.1:
5689bdd1243dSDimitry Andric   //   If their template-parameter-lists (possibly including template-parameters
5690bdd1243dSDimitry Andric   //   invented for an abbreviated function template ([dcl.fct])) or function
5691bdd1243dSDimitry Andric   //   parameter lists differ in length, neither template is more specialized
5692bdd1243dSDimitry Andric   //   than the other.
5693bdd1243dSDimitry Andric   TemplateParameterList *TPL1 = FT1->getTemplateParameters();
5694bdd1243dSDimitry Andric   TemplateParameterList *TPL2 = FT2->getTemplateParameters();
5695bdd1243dSDimitry Andric   if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
5696bdd1243dSDimitry Andric     return nullptr;
5697bdd1243dSDimitry Andric 
5698bdd1243dSDimitry Andric   // C++20 [temp.func.order]p6.2.2:
5699bdd1243dSDimitry Andric   //   Otherwise, if the corresponding template-parameters of the
5700bdd1243dSDimitry Andric   //   template-parameter-lists are not equivalent ([temp.over.link]) or if the
5701bdd1243dSDimitry Andric   //   function parameters that positionally correspond between the two
5702bdd1243dSDimitry Andric   //   templates are not of the same type, neither template is more specialized
5703bdd1243dSDimitry Andric   //   than the other.
570406c3fb27SDimitry Andric   if (!TemplateParameterListsAreEqual(TPL1, TPL2, false,
570506c3fb27SDimitry Andric                                       Sema::TPL_TemplateParamsEquivalent))
5706bdd1243dSDimitry Andric     return nullptr;
5707bdd1243dSDimitry Andric 
5708*0fca6ea1SDimitry Andric   // [dcl.fct]p5:
5709*0fca6ea1SDimitry Andric   // Any top-level cv-qualifiers modifying a parameter type are deleted when
5710*0fca6ea1SDimitry Andric   // forming the function type.
5711bdd1243dSDimitry Andric   for (unsigned i = 0; i < NumParams1; ++i)
5712*0fca6ea1SDimitry Andric     if (!Context.hasSameUnqualifiedType(Param1[i], Param2[i]))
5713bdd1243dSDimitry Andric       return nullptr;
5714bdd1243dSDimitry Andric 
5715bdd1243dSDimitry Andric   // C++20 [temp.func.order]p6.3:
5716bdd1243dSDimitry Andric   //   Otherwise, if the context in which the partial ordering is done is
5717bdd1243dSDimitry Andric   //   that of a call to a conversion function and the return types of the
5718bdd1243dSDimitry Andric   //   templates are not the same, then neither template is more specialized
5719bdd1243dSDimitry Andric   //   than the other.
5720bdd1243dSDimitry Andric   if (TPOC == TPOC_Conversion &&
5721bdd1243dSDimitry Andric       !Context.hasSameType(FD1->getReturnType(), FD2->getReturnType()))
5722bdd1243dSDimitry Andric     return nullptr;
5723bdd1243dSDimitry Andric 
5724480093f4SDimitry Andric   llvm::SmallVector<const Expr *, 3> AC1, AC2;
5725480093f4SDimitry Andric   FT1->getAssociatedConstraints(AC1);
5726480093f4SDimitry Andric   FT2->getAssociatedConstraints(AC2);
5727480093f4SDimitry Andric   bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5728480093f4SDimitry Andric   if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5729480093f4SDimitry Andric     return nullptr;
5730480093f4SDimitry Andric   if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5731480093f4SDimitry Andric     return nullptr;
5732480093f4SDimitry Andric   if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5733480093f4SDimitry Andric     return nullptr;
5734480093f4SDimitry Andric   return AtLeastAsConstrained1 ? FT1 : FT2;
57350b57cec5SDimitry Andric }
57360b57cec5SDimitry Andric 
57370b57cec5SDimitry Andric /// Determine if the two templates are equivalent.
isSameTemplate(TemplateDecl * T1,TemplateDecl * T2)57380b57cec5SDimitry Andric static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
57390b57cec5SDimitry Andric   if (T1 == T2)
57400b57cec5SDimitry Andric     return true;
57410b57cec5SDimitry Andric 
57420b57cec5SDimitry Andric   if (!T1 || !T2)
57430b57cec5SDimitry Andric     return false;
57440b57cec5SDimitry Andric 
57450b57cec5SDimitry Andric   return T1->getCanonicalDecl() == T2->getCanonicalDecl();
57460b57cec5SDimitry Andric }
57470b57cec5SDimitry Andric 
getMostSpecialized(UnresolvedSetIterator SpecBegin,UnresolvedSetIterator SpecEnd,TemplateSpecCandidateSet & FailedCandidates,SourceLocation Loc,const PartialDiagnostic & NoneDiag,const PartialDiagnostic & AmbigDiag,const PartialDiagnostic & CandidateDiag,bool Complain,QualType TargetType)57480b57cec5SDimitry Andric UnresolvedSetIterator Sema::getMostSpecialized(
57490b57cec5SDimitry Andric     UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
57500b57cec5SDimitry Andric     TemplateSpecCandidateSet &FailedCandidates,
57510b57cec5SDimitry Andric     SourceLocation Loc, const PartialDiagnostic &NoneDiag,
57520b57cec5SDimitry Andric     const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
57530b57cec5SDimitry Andric     bool Complain, QualType TargetType) {
57540b57cec5SDimitry Andric   if (SpecBegin == SpecEnd) {
57550b57cec5SDimitry Andric     if (Complain) {
57560b57cec5SDimitry Andric       Diag(Loc, NoneDiag);
57570b57cec5SDimitry Andric       FailedCandidates.NoteCandidates(*this, Loc);
57580b57cec5SDimitry Andric     }
57590b57cec5SDimitry Andric     return SpecEnd;
57600b57cec5SDimitry Andric   }
57610b57cec5SDimitry Andric 
57620b57cec5SDimitry Andric   if (SpecBegin + 1 == SpecEnd)
57630b57cec5SDimitry Andric     return SpecBegin;
57640b57cec5SDimitry Andric 
57650b57cec5SDimitry Andric   // Find the function template that is better than all of the templates it
57660b57cec5SDimitry Andric   // has been compared to.
57670b57cec5SDimitry Andric   UnresolvedSetIterator Best = SpecBegin;
57680b57cec5SDimitry Andric   FunctionTemplateDecl *BestTemplate
57690b57cec5SDimitry Andric     = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
57700b57cec5SDimitry Andric   assert(BestTemplate && "Not a function template specialization?");
57710b57cec5SDimitry Andric   for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
57720b57cec5SDimitry Andric     FunctionTemplateDecl *Challenger
57730b57cec5SDimitry Andric       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
57740b57cec5SDimitry Andric     assert(Challenger && "Not a function template specialization?");
5775*0fca6ea1SDimitry Andric     if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger, Loc,
5776*0fca6ea1SDimitry Andric                                                   TPOC_Other, 0),
57770b57cec5SDimitry Andric                        Challenger)) {
57780b57cec5SDimitry Andric       Best = I;
57790b57cec5SDimitry Andric       BestTemplate = Challenger;
57800b57cec5SDimitry Andric     }
57810b57cec5SDimitry Andric   }
57820b57cec5SDimitry Andric 
57830b57cec5SDimitry Andric   // Make sure that the "best" function template is more specialized than all
57840b57cec5SDimitry Andric   // of the others.
57850b57cec5SDimitry Andric   bool Ambiguous = false;
57860b57cec5SDimitry Andric   for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
57870b57cec5SDimitry Andric     FunctionTemplateDecl *Challenger
57880b57cec5SDimitry Andric       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
57890b57cec5SDimitry Andric     if (I != Best &&
57900b57cec5SDimitry Andric         !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5791*0fca6ea1SDimitry Andric                                                    Loc, TPOC_Other, 0),
57920b57cec5SDimitry Andric                         BestTemplate)) {
57930b57cec5SDimitry Andric       Ambiguous = true;
57940b57cec5SDimitry Andric       break;
57950b57cec5SDimitry Andric     }
57960b57cec5SDimitry Andric   }
57970b57cec5SDimitry Andric 
57980b57cec5SDimitry Andric   if (!Ambiguous) {
57990b57cec5SDimitry Andric     // We found an answer. Return it.
58000b57cec5SDimitry Andric     return Best;
58010b57cec5SDimitry Andric   }
58020b57cec5SDimitry Andric 
58030b57cec5SDimitry Andric   // Diagnose the ambiguity.
58040b57cec5SDimitry Andric   if (Complain) {
58050b57cec5SDimitry Andric     Diag(Loc, AmbigDiag);
58060b57cec5SDimitry Andric 
58070b57cec5SDimitry Andric     // FIXME: Can we order the candidates in some sane way?
58080b57cec5SDimitry Andric     for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
58090b57cec5SDimitry Andric       PartialDiagnostic PD = CandidateDiag;
58100b57cec5SDimitry Andric       const auto *FD = cast<FunctionDecl>(*I);
58110b57cec5SDimitry Andric       PD << FD << getTemplateArgumentBindingsText(
58120b57cec5SDimitry Andric                       FD->getPrimaryTemplate()->getTemplateParameters(),
58130b57cec5SDimitry Andric                       *FD->getTemplateSpecializationArgs());
58140b57cec5SDimitry Andric       if (!TargetType.isNull())
58150b57cec5SDimitry Andric         HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
58160b57cec5SDimitry Andric       Diag((*I)->getLocation(), PD);
58170b57cec5SDimitry Andric     }
58180b57cec5SDimitry Andric   }
58190b57cec5SDimitry Andric 
58200b57cec5SDimitry Andric   return SpecEnd;
58210b57cec5SDimitry Andric }
58220b57cec5SDimitry Andric 
getMoreConstrainedFunction(FunctionDecl * FD1,FunctionDecl * FD2)5823*0fca6ea1SDimitry Andric FunctionDecl *Sema::getMoreConstrainedFunction(FunctionDecl *FD1,
5824*0fca6ea1SDimitry Andric                                                FunctionDecl *FD2) {
5825*0fca6ea1SDimitry Andric   assert(!FD1->getDescribedTemplate() && !FD2->getDescribedTemplate() &&
5826*0fca6ea1SDimitry Andric          "not for function templates");
5827*0fca6ea1SDimitry Andric   FunctionDecl *F1 = FD1;
5828*0fca6ea1SDimitry Andric   if (FunctionDecl *MF = FD1->getInstantiatedFromMemberFunction())
5829*0fca6ea1SDimitry Andric     F1 = MF;
5830*0fca6ea1SDimitry Andric   FunctionDecl *F2 = FD2;
5831*0fca6ea1SDimitry Andric   if (FunctionDecl *MF = FD2->getInstantiatedFromMemberFunction())
5832*0fca6ea1SDimitry Andric     F2 = MF;
5833*0fca6ea1SDimitry Andric   llvm::SmallVector<const Expr *, 1> AC1, AC2;
5834*0fca6ea1SDimitry Andric   F1->getAssociatedConstraints(AC1);
5835*0fca6ea1SDimitry Andric   F2->getAssociatedConstraints(AC2);
5836*0fca6ea1SDimitry Andric   bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5837*0fca6ea1SDimitry Andric   if (IsAtLeastAsConstrained(F1, AC1, F2, AC2, AtLeastAsConstrained1))
5838*0fca6ea1SDimitry Andric     return nullptr;
5839*0fca6ea1SDimitry Andric   if (IsAtLeastAsConstrained(F2, AC2, F1, AC1, AtLeastAsConstrained2))
5840*0fca6ea1SDimitry Andric     return nullptr;
5841*0fca6ea1SDimitry Andric   if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5842*0fca6ea1SDimitry Andric     return nullptr;
5843*0fca6ea1SDimitry Andric   return AtLeastAsConstrained1 ? FD1 : FD2;
5844*0fca6ea1SDimitry Andric }
5845*0fca6ea1SDimitry Andric 
58460b57cec5SDimitry Andric /// Determine whether one partial specialization, P1, is at least as
58470b57cec5SDimitry Andric /// specialized than another, P2.
58480b57cec5SDimitry Andric ///
58490b57cec5SDimitry Andric /// \tparam TemplateLikeDecl The kind of P2, which must be a
58500b57cec5SDimitry Andric /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
58510b57cec5SDimitry Andric /// \param T1 The injected-class-name of P1 (faked for a variable template).
58520b57cec5SDimitry Andric /// \param T2 The injected-class-name of P2 (faked for a variable template).
58530b57cec5SDimitry Andric template<typename TemplateLikeDecl>
isAtLeastAsSpecializedAs(Sema & S,QualType T1,QualType T2,TemplateLikeDecl * P2,TemplateDeductionInfo & Info)58540b57cec5SDimitry Andric static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
58550b57cec5SDimitry Andric                                      TemplateLikeDecl *P2,
58560b57cec5SDimitry Andric                                      TemplateDeductionInfo &Info) {
58570b57cec5SDimitry Andric   // C++ [temp.class.order]p1:
58580b57cec5SDimitry Andric   //   For two class template partial specializations, the first is at least as
58590b57cec5SDimitry Andric   //   specialized as the second if, given the following rewrite to two
58600b57cec5SDimitry Andric   //   function templates, the first function template is at least as
58610b57cec5SDimitry Andric   //   specialized as the second according to the ordering rules for function
58620b57cec5SDimitry Andric   //   templates (14.6.6.2):
58630b57cec5SDimitry Andric   //     - the first function template has the same template parameters as the
58640b57cec5SDimitry Andric   //       first partial specialization and has a single function parameter
58650b57cec5SDimitry Andric   //       whose type is a class template specialization with the template
58660b57cec5SDimitry Andric   //       arguments of the first partial specialization, and
58670b57cec5SDimitry Andric   //     - the second function template has the same template parameters as the
58680b57cec5SDimitry Andric   //       second partial specialization and has a single function parameter
58690b57cec5SDimitry Andric   //       whose type is a class template specialization with the template
58700b57cec5SDimitry Andric   //       arguments of the second partial specialization.
58710b57cec5SDimitry Andric   //
58720b57cec5SDimitry Andric   // Rather than synthesize function templates, we merely perform the
58730b57cec5SDimitry Andric   // equivalent partial ordering by performing deduction directly on
58740b57cec5SDimitry Andric   // the template arguments of the class template partial
58750b57cec5SDimitry Andric   // specializations. This computation is slightly simpler than the
58760b57cec5SDimitry Andric   // general problem of function template partial ordering, because
58770b57cec5SDimitry Andric   // class template partial specializations are more constrained. We
58780b57cec5SDimitry Andric   // know that every template parameter is deducible from the class
58790b57cec5SDimitry Andric   // template partial specialization's template arguments, for
58800b57cec5SDimitry Andric   // example.
58810b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
58820b57cec5SDimitry Andric 
58830b57cec5SDimitry Andric   // Determine whether P1 is at least as specialized as P2.
58840b57cec5SDimitry Andric   Deduced.resize(P2->getTemplateParameters()->size());
5885*0fca6ea1SDimitry Andric   if (DeduceTemplateArgumentsByTypeMatch(
5886*0fca6ea1SDimitry Andric           S, P2->getTemplateParameters(), T2, T1, Info, Deduced, TDF_None,
5887*0fca6ea1SDimitry Andric           /*PartialOrdering=*/true) != TemplateDeductionResult::Success)
58880b57cec5SDimitry Andric     return false;
58890b57cec5SDimitry Andric 
58900b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
58910b57cec5SDimitry Andric                                                Deduced.end());
58920b57cec5SDimitry Andric   Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
58930b57cec5SDimitry Andric                                    Info);
5894fe6060f1SDimitry Andric   if (Inst.isInvalid())
5895fe6060f1SDimitry Andric     return false;
5896fe6060f1SDimitry Andric 
5897bdd1243dSDimitry Andric   const auto *TST1 = cast<TemplateSpecializationType>(T1);
58985ffd83dbSDimitry Andric   bool AtLeastAsSpecialized;
58995ffd83dbSDimitry Andric   S.runWithSufficientStackSpace(Info.getLocation(), [&] {
5900*0fca6ea1SDimitry Andric     AtLeastAsSpecialized =
5901*0fca6ea1SDimitry Andric         FinishTemplateArgumentDeduction(
5902*0fca6ea1SDimitry Andric             S, P2, /*IsPartialOrdering=*/true, TST1->template_arguments(),
5903*0fca6ea1SDimitry Andric             Deduced, Info) == TemplateDeductionResult::Success;
59045ffd83dbSDimitry Andric   });
59055ffd83dbSDimitry Andric   return AtLeastAsSpecialized;
59060b57cec5SDimitry Andric }
59070b57cec5SDimitry Andric 
5908bdd1243dSDimitry Andric namespace {
5909bdd1243dSDimitry Andric // A dummy class to return nullptr instead of P2 when performing "more
5910bdd1243dSDimitry Andric // specialized than primary" check.
5911bdd1243dSDimitry Andric struct GetP2 {
5912bdd1243dSDimitry Andric   template <typename T1, typename T2,
5913bdd1243dSDimitry Andric             std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
operator ()__anonc4c693d01b11::GetP25914bdd1243dSDimitry Andric   T2 *operator()(T1 *, T2 *P2) {
5915bdd1243dSDimitry Andric     return P2;
5916bdd1243dSDimitry Andric   }
5917bdd1243dSDimitry Andric   template <typename T1, typename T2,
5918bdd1243dSDimitry Andric             std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
operator ()__anonc4c693d01b11::GetP25919bdd1243dSDimitry Andric   T1 *operator()(T1 *, T2 *) {
5920bdd1243dSDimitry Andric     return nullptr;
5921bdd1243dSDimitry Andric   }
5922bdd1243dSDimitry Andric };
5923bdd1243dSDimitry Andric 
5924bdd1243dSDimitry Andric // The assumption is that two template argument lists have the same size.
5925bdd1243dSDimitry Andric struct TemplateArgumentListAreEqual {
5926bdd1243dSDimitry Andric   ASTContext &Ctx;
TemplateArgumentListAreEqual__anonc4c693d01b11::TemplateArgumentListAreEqual5927bdd1243dSDimitry Andric   TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
5928bdd1243dSDimitry Andric 
5929bdd1243dSDimitry Andric   template <typename T1, typename T2,
5930bdd1243dSDimitry Andric             std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
operator ()__anonc4c693d01b11::TemplateArgumentListAreEqual5931bdd1243dSDimitry Andric   bool operator()(T1 *PS1, T2 *PS2) {
5932bdd1243dSDimitry Andric     ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
5933bdd1243dSDimitry Andric                                Args2 = PS2->getTemplateArgs().asArray();
5934bdd1243dSDimitry Andric 
5935bdd1243dSDimitry Andric     for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5936bdd1243dSDimitry Andric       // We use profile, instead of structural comparison of the arguments,
5937bdd1243dSDimitry Andric       // because canonicalization can't do the right thing for dependent
5938bdd1243dSDimitry Andric       // expressions.
5939bdd1243dSDimitry Andric       llvm::FoldingSetNodeID IDA, IDB;
5940bdd1243dSDimitry Andric       Args1[I].Profile(IDA, Ctx);
5941bdd1243dSDimitry Andric       Args2[I].Profile(IDB, Ctx);
5942bdd1243dSDimitry Andric       if (IDA != IDB)
5943bdd1243dSDimitry Andric         return false;
5944bdd1243dSDimitry Andric     }
5945bdd1243dSDimitry Andric     return true;
5946bdd1243dSDimitry Andric   }
5947bdd1243dSDimitry Andric 
5948bdd1243dSDimitry Andric   template <typename T1, typename T2,
5949bdd1243dSDimitry Andric             std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
operator ()__anonc4c693d01b11::TemplateArgumentListAreEqual5950bdd1243dSDimitry Andric   bool operator()(T1 *Spec, T2 *Primary) {
5951bdd1243dSDimitry Andric     ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
5952bdd1243dSDimitry Andric                                Args2 = Primary->getInjectedTemplateArgs();
5953bdd1243dSDimitry Andric 
5954bdd1243dSDimitry Andric     for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5955bdd1243dSDimitry Andric       // We use profile, instead of structural comparison of the arguments,
5956bdd1243dSDimitry Andric       // because canonicalization can't do the right thing for dependent
5957bdd1243dSDimitry Andric       // expressions.
5958bdd1243dSDimitry Andric       llvm::FoldingSetNodeID IDA, IDB;
5959bdd1243dSDimitry Andric       Args1[I].Profile(IDA, Ctx);
5960bdd1243dSDimitry Andric       // Unlike the specialization arguments, the injected arguments are not
5961bdd1243dSDimitry Andric       // always canonical.
5962bdd1243dSDimitry Andric       Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
5963bdd1243dSDimitry Andric       if (IDA != IDB)
5964bdd1243dSDimitry Andric         return false;
5965bdd1243dSDimitry Andric     }
5966bdd1243dSDimitry Andric     return true;
5967bdd1243dSDimitry Andric   }
5968bdd1243dSDimitry Andric };
5969bdd1243dSDimitry Andric } // namespace
5970bdd1243dSDimitry Andric 
5971bdd1243dSDimitry Andric /// Returns the more specialized template specialization between T1/P1 and
5972bdd1243dSDimitry Andric /// T2/P2.
5973bdd1243dSDimitry Andric /// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
5974bdd1243dSDimitry Andric ///   specialization and T2/P2 is the primary template.
5975bdd1243dSDimitry Andric /// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
5976bdd1243dSDimitry Andric ///
5977bdd1243dSDimitry Andric /// \param T1 the type of the first template partial specialization
5978bdd1243dSDimitry Andric ///
5979bdd1243dSDimitry Andric /// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
5980bdd1243dSDimitry Andric ///           template partial specialization; otherwise, the type of the
5981bdd1243dSDimitry Andric ///           primary template.
5982bdd1243dSDimitry Andric ///
5983bdd1243dSDimitry Andric /// \param P1 the first template partial specialization
5984bdd1243dSDimitry Andric ///
5985bdd1243dSDimitry Andric /// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
5986bdd1243dSDimitry Andric ///           partial specialization; otherwise, the primary template.
5987bdd1243dSDimitry Andric ///
5988bdd1243dSDimitry Andric /// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
5989bdd1243dSDimitry Andric ///            more specialized, returns nullptr if P1 is not more specialized.
5990bdd1243dSDimitry Andric ///          - otherwise, returns the more specialized template partial
5991bdd1243dSDimitry Andric ///            specialization. If neither partial specialization is more
5992bdd1243dSDimitry Andric ///            specialized, returns NULL.
5993bdd1243dSDimitry Andric template <typename TemplateLikeDecl, typename PrimaryDel>
5994bdd1243dSDimitry Andric static TemplateLikeDecl *
getMoreSpecialized(Sema & S,QualType T1,QualType T2,TemplateLikeDecl * P1,PrimaryDel * P2,TemplateDeductionInfo & Info)5995bdd1243dSDimitry Andric getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
5996bdd1243dSDimitry Andric                    PrimaryDel *P2, TemplateDeductionInfo &Info) {
5997bdd1243dSDimitry Andric   constexpr bool IsMoreSpecialThanPrimaryCheck =
5998bdd1243dSDimitry Andric       !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
5999bdd1243dSDimitry Andric 
6000bdd1243dSDimitry Andric   bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
6001bdd1243dSDimitry Andric   if (IsMoreSpecialThanPrimaryCheck && !Better1)
6002bdd1243dSDimitry Andric     return nullptr;
6003bdd1243dSDimitry Andric 
6004bdd1243dSDimitry Andric   bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
6005bdd1243dSDimitry Andric   if (IsMoreSpecialThanPrimaryCheck && !Better2)
6006bdd1243dSDimitry Andric     return P1;
6007bdd1243dSDimitry Andric 
6008bdd1243dSDimitry Andric   // C++ [temp.deduct.partial]p10:
6009bdd1243dSDimitry Andric   //   F is more specialized than G if F is at least as specialized as G and G
6010bdd1243dSDimitry Andric   //   is not at least as specialized as F.
6011bdd1243dSDimitry Andric   if (Better1 != Better2) // We have a clear winner
6012bdd1243dSDimitry Andric     return Better1 ? P1 : GetP2()(P1, P2);
6013bdd1243dSDimitry Andric 
6014bdd1243dSDimitry Andric   if (!Better1 && !Better2)
6015bdd1243dSDimitry Andric     return nullptr;
6016bdd1243dSDimitry Andric 
6017bdd1243dSDimitry Andric   // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
6018bdd1243dSDimitry Andric   // there is no wording or even resolution for this issue.
6019bdd1243dSDimitry Andric   auto *TST1 = cast<TemplateSpecializationType>(T1);
6020bdd1243dSDimitry Andric   auto *TST2 = cast<TemplateSpecializationType>(T2);
6021bdd1243dSDimitry Andric   const TemplateArgument &TA1 = TST1->template_arguments().back();
6022bdd1243dSDimitry Andric   if (TA1.getKind() == TemplateArgument::Pack) {
6023bdd1243dSDimitry Andric     assert(TST1->template_arguments().size() ==
6024bdd1243dSDimitry Andric            TST2->template_arguments().size());
6025bdd1243dSDimitry Andric     const TemplateArgument &TA2 = TST2->template_arguments().back();
6026bdd1243dSDimitry Andric     assert(TA2.getKind() == TemplateArgument::Pack);
6027bdd1243dSDimitry Andric     unsigned PackSize1 = TA1.pack_size();
6028bdd1243dSDimitry Andric     unsigned PackSize2 = TA2.pack_size();
6029bdd1243dSDimitry Andric     bool IsPackExpansion1 =
6030bdd1243dSDimitry Andric         PackSize1 && TA1.pack_elements().back().isPackExpansion();
6031bdd1243dSDimitry Andric     bool IsPackExpansion2 =
6032bdd1243dSDimitry Andric         PackSize2 && TA2.pack_elements().back().isPackExpansion();
6033bdd1243dSDimitry Andric     if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
6034bdd1243dSDimitry Andric       if (PackSize1 > PackSize2 && IsPackExpansion1)
6035bdd1243dSDimitry Andric         return GetP2()(P1, P2);
6036bdd1243dSDimitry Andric       if (PackSize1 < PackSize2 && IsPackExpansion2)
6037bdd1243dSDimitry Andric         return P1;
6038bdd1243dSDimitry Andric     }
6039bdd1243dSDimitry Andric   }
6040bdd1243dSDimitry Andric 
6041bdd1243dSDimitry Andric   if (!S.Context.getLangOpts().CPlusPlus20)
6042bdd1243dSDimitry Andric     return nullptr;
6043bdd1243dSDimitry Andric 
6044bdd1243dSDimitry Andric   // Match GCC on not implementing [temp.func.order]p6.2.1.
6045bdd1243dSDimitry Andric 
6046bdd1243dSDimitry Andric   // C++20 [temp.func.order]p6:
6047bdd1243dSDimitry Andric   //   If deduction against the other template succeeds for both transformed
6048bdd1243dSDimitry Andric   //   templates, constraints can be considered as follows:
6049bdd1243dSDimitry Andric 
6050bdd1243dSDimitry Andric   TemplateParameterList *TPL1 = P1->getTemplateParameters();
6051bdd1243dSDimitry Andric   TemplateParameterList *TPL2 = P2->getTemplateParameters();
6052bdd1243dSDimitry Andric   if (TPL1->size() != TPL2->size())
6053bdd1243dSDimitry Andric     return nullptr;
6054bdd1243dSDimitry Andric 
6055bdd1243dSDimitry Andric   // C++20 [temp.func.order]p6.2.2:
6056bdd1243dSDimitry Andric   // Otherwise, if the corresponding template-parameters of the
6057bdd1243dSDimitry Andric   // template-parameter-lists are not equivalent ([temp.over.link]) or if the
6058bdd1243dSDimitry Andric   // function parameters that positionally correspond between the two
6059bdd1243dSDimitry Andric   // templates are not of the same type, neither template is more specialized
6060bdd1243dSDimitry Andric   // than the other.
606106c3fb27SDimitry Andric   if (!S.TemplateParameterListsAreEqual(TPL1, TPL2, false,
606206c3fb27SDimitry Andric                                         Sema::TPL_TemplateParamsEquivalent))
6063bdd1243dSDimitry Andric     return nullptr;
6064bdd1243dSDimitry Andric 
6065bdd1243dSDimitry Andric   if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
6066bdd1243dSDimitry Andric     return nullptr;
6067bdd1243dSDimitry Andric 
6068bdd1243dSDimitry Andric   llvm::SmallVector<const Expr *, 3> AC1, AC2;
6069bdd1243dSDimitry Andric   P1->getAssociatedConstraints(AC1);
6070bdd1243dSDimitry Andric   P2->getAssociatedConstraints(AC2);
6071bdd1243dSDimitry Andric   bool AtLeastAsConstrained1, AtLeastAsConstrained2;
6072bdd1243dSDimitry Andric   if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
6073bdd1243dSDimitry Andric       (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
6074bdd1243dSDimitry Andric     return nullptr;
6075bdd1243dSDimitry Andric   if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
6076bdd1243dSDimitry Andric     return nullptr;
6077bdd1243dSDimitry Andric   if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
6078bdd1243dSDimitry Andric     return nullptr;
6079bdd1243dSDimitry Andric   return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
6080bdd1243dSDimitry Andric }
6081bdd1243dSDimitry Andric 
60820b57cec5SDimitry Andric ClassTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl * PS1,ClassTemplatePartialSpecializationDecl * PS2,SourceLocation Loc)60830b57cec5SDimitry Andric Sema::getMoreSpecializedPartialSpecialization(
60840b57cec5SDimitry Andric                                   ClassTemplatePartialSpecializationDecl *PS1,
60850b57cec5SDimitry Andric                                   ClassTemplatePartialSpecializationDecl *PS2,
60860b57cec5SDimitry Andric                                               SourceLocation Loc) {
60870b57cec5SDimitry Andric   QualType PT1 = PS1->getInjectedSpecializationType();
60880b57cec5SDimitry Andric   QualType PT2 = PS2->getInjectedSpecializationType();
60890b57cec5SDimitry Andric 
60900b57cec5SDimitry Andric   TemplateDeductionInfo Info(Loc);
6091bdd1243dSDimitry Andric   return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
60920b57cec5SDimitry Andric }
60930b57cec5SDimitry Andric 
isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl * Spec,TemplateDeductionInfo & Info)60940b57cec5SDimitry Andric bool Sema::isMoreSpecializedThanPrimary(
60950b57cec5SDimitry Andric     ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
60960b57cec5SDimitry Andric   ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
60970b57cec5SDimitry Andric   QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
60980b57cec5SDimitry Andric   QualType PartialT = Spec->getInjectedSpecializationType();
6099bdd1243dSDimitry Andric 
6100bdd1243dSDimitry Andric   ClassTemplatePartialSpecializationDecl *MaybeSpec =
6101bdd1243dSDimitry Andric       getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6102bdd1243dSDimitry Andric   if (MaybeSpec)
6103480093f4SDimitry Andric     Info.clearSFINAEDiagnostic();
6104bdd1243dSDimitry Andric   return MaybeSpec;
61050b57cec5SDimitry Andric }
61060b57cec5SDimitry Andric 
61070b57cec5SDimitry Andric VarTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(VarTemplatePartialSpecializationDecl * PS1,VarTemplatePartialSpecializationDecl * PS2,SourceLocation Loc)61080b57cec5SDimitry Andric Sema::getMoreSpecializedPartialSpecialization(
61090b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *PS1,
61100b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
61110b57cec5SDimitry Andric   // Pretend the variable template specializations are class template
61120b57cec5SDimitry Andric   // specializations and form a fake injected class name type for comparison.
61130b57cec5SDimitry Andric   assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
61140b57cec5SDimitry Andric          "the partial specializations being compared should specialize"
61150b57cec5SDimitry Andric          " the same template.");
61160b57cec5SDimitry Andric   TemplateName Name(PS1->getSpecializedTemplate());
61170b57cec5SDimitry Andric   TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
61180b57cec5SDimitry Andric   QualType PT1 = Context.getTemplateSpecializationType(
61190b57cec5SDimitry Andric       CanonTemplate, PS1->getTemplateArgs().asArray());
61200b57cec5SDimitry Andric   QualType PT2 = Context.getTemplateSpecializationType(
61210b57cec5SDimitry Andric       CanonTemplate, PS2->getTemplateArgs().asArray());
61220b57cec5SDimitry Andric 
61230b57cec5SDimitry Andric   TemplateDeductionInfo Info(Loc);
6124bdd1243dSDimitry Andric   return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
61250b57cec5SDimitry Andric }
61260b57cec5SDimitry Andric 
isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl * Spec,TemplateDeductionInfo & Info)61270b57cec5SDimitry Andric bool Sema::isMoreSpecializedThanPrimary(
61280b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
6129bdd1243dSDimitry Andric   VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
61300b57cec5SDimitry Andric   TemplateName CanonTemplate =
61310b57cec5SDimitry Andric       Context.getCanonicalTemplateName(TemplateName(Primary));
61320b57cec5SDimitry Andric   QualType PrimaryT = Context.getTemplateSpecializationType(
6133bdd1243dSDimitry Andric       CanonTemplate, Primary->getInjectedTemplateArgs());
61340b57cec5SDimitry Andric   QualType PartialT = Context.getTemplateSpecializationType(
61350b57cec5SDimitry Andric       CanonTemplate, Spec->getTemplateArgs().asArray());
6136480093f4SDimitry Andric 
6137bdd1243dSDimitry Andric   VarTemplatePartialSpecializationDecl *MaybeSpec =
6138bdd1243dSDimitry Andric       getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
6139bdd1243dSDimitry Andric   if (MaybeSpec)
6140480093f4SDimitry Andric     Info.clearSFINAEDiagnostic();
6141bdd1243dSDimitry Andric   return MaybeSpec;
61420b57cec5SDimitry Andric }
61430b57cec5SDimitry Andric 
isTemplateTemplateParameterAtLeastAsSpecializedAs(TemplateParameterList * P,TemplateDecl * AArg,SourceLocation Loc,bool IsDeduced)61440b57cec5SDimitry Andric bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
6145*0fca6ea1SDimitry Andric     TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc,
6146*0fca6ea1SDimitry Andric     bool IsDeduced) {
61470b57cec5SDimitry Andric   // C++1z [temp.arg.template]p4: (DR 150)
61480b57cec5SDimitry Andric   //   A template template-parameter P is at least as specialized as a
61490b57cec5SDimitry Andric   //   template template-argument A if, given the following rewrite to two
61500b57cec5SDimitry Andric   //   function templates...
61510b57cec5SDimitry Andric 
61520b57cec5SDimitry Andric   // Rather than synthesize function templates, we merely perform the
61530b57cec5SDimitry Andric   // equivalent partial ordering by performing deduction directly on
61540b57cec5SDimitry Andric   // the template parameter lists of the template template parameters.
61550b57cec5SDimitry Andric   //
61560b57cec5SDimitry Andric   TemplateParameterList *A = AArg->getTemplateParameters();
61570b57cec5SDimitry Andric 
6158*0fca6ea1SDimitry Andric   //   Given an invented class template X with the template parameter list of
6159*0fca6ea1SDimitry Andric   //   A (including default arguments):
61600b57cec5SDimitry Andric   //    - Each function template has a single function parameter whose type is
61610b57cec5SDimitry Andric   //      a specialization of X with template arguments corresponding to the
61620b57cec5SDimitry Andric   //      template parameters from the respective function template
61630b57cec5SDimitry Andric   SmallVector<TemplateArgument, 8> AArgs;
61640b57cec5SDimitry Andric   Context.getInjectedTemplateArgs(A, AArgs);
61650b57cec5SDimitry Andric 
61660b57cec5SDimitry Andric   // Check P's arguments against A's parameter list. This will fill in default
61670b57cec5SDimitry Andric   // template arguments as needed. AArgs are already correct by construction.
61680b57cec5SDimitry Andric   // We can't just use CheckTemplateIdType because that will expand alias
61690b57cec5SDimitry Andric   // templates.
61700b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> PArgs;
61710b57cec5SDimitry Andric   {
61720b57cec5SDimitry Andric     SFINAETrap Trap(*this);
61730b57cec5SDimitry Andric 
61740b57cec5SDimitry Andric     Context.getInjectedTemplateArgs(P, PArgs);
6175480093f4SDimitry Andric     TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
6176480093f4SDimitry Andric                                       P->getRAngleLoc());
61770b57cec5SDimitry Andric     for (unsigned I = 0, N = P->size(); I != N; ++I) {
61780b57cec5SDimitry Andric       // Unwrap packs that getInjectedTemplateArgs wrapped around pack
61790b57cec5SDimitry Andric       // expansions, to form an "as written" argument list.
61800b57cec5SDimitry Andric       TemplateArgument Arg = PArgs[I];
61810b57cec5SDimitry Andric       if (Arg.getKind() == TemplateArgument::Pack) {
61820b57cec5SDimitry Andric         assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
61830b57cec5SDimitry Andric         Arg = *Arg.pack_begin();
61840b57cec5SDimitry Andric       }
61850b57cec5SDimitry Andric       PArgList.addArgument(getTrivialTemplateArgumentLoc(
61860b57cec5SDimitry Andric           Arg, QualType(), P->getParam(I)->getLocation()));
61870b57cec5SDimitry Andric     }
61880b57cec5SDimitry Andric     PArgs.clear();
61890b57cec5SDimitry Andric 
61900b57cec5SDimitry Andric     // C++1z [temp.arg.template]p3:
61910b57cec5SDimitry Andric     //   If the rewrite produces an invalid type, then P is not at least as
61920b57cec5SDimitry Andric     //   specialized as A.
6193bdd1243dSDimitry Andric     SmallVector<TemplateArgument, 4> SugaredPArgs;
6194bdd1243dSDimitry Andric     if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, SugaredPArgs,
6195*0fca6ea1SDimitry Andric                                   PArgs, /*UpdateArgsWithConversions=*/true,
6196*0fca6ea1SDimitry Andric                                   /*ConstraintsNotSatisfied=*/nullptr,
6197*0fca6ea1SDimitry Andric                                   /*PartialOrderTTP=*/true) ||
61980b57cec5SDimitry Andric         Trap.hasErrorOccurred())
61990b57cec5SDimitry Andric       return false;
62000b57cec5SDimitry Andric   }
62010b57cec5SDimitry Andric 
6202*0fca6ea1SDimitry Andric   // Determine whether P1 is at least as specialized as P2.
6203*0fca6ea1SDimitry Andric   TemplateDeductionInfo Info(Loc, A->getDepth());
6204*0fca6ea1SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
6205*0fca6ea1SDimitry Andric   Deduced.resize(A->size());
62060b57cec5SDimitry Andric 
62070b57cec5SDimitry Andric   //   ... the function template corresponding to P is at least as specialized
62080b57cec5SDimitry Andric   //   as the function template corresponding to A according to the partial
62090b57cec5SDimitry Andric   //   ordering rules for function templates.
6210*0fca6ea1SDimitry Andric 
6211*0fca6ea1SDimitry Andric   // Provisional resolution for CWG2398: Regarding temp.arg.template]p4, when
6212*0fca6ea1SDimitry Andric   // applying the partial ordering rules for function templates on
6213*0fca6ea1SDimitry Andric   // the rewritten template template parameters:
6214*0fca6ea1SDimitry Andric   //   - In a deduced context, the matching of packs versus fixed-size needs to
6215*0fca6ea1SDimitry Andric   //   be inverted between Ps and As. On non-deduced context, matching needs to
6216*0fca6ea1SDimitry Andric   //   happen both ways, according to [temp.arg.template]p3, but this is
6217*0fca6ea1SDimitry Andric   //   currently implemented as a special case elsewhere.
6218*0fca6ea1SDimitry Andric   if (::DeduceTemplateArguments(*this, A, AArgs, PArgs, Info, Deduced,
6219*0fca6ea1SDimitry Andric                                 /*NumberOfArgumentsMustMatch=*/false,
6220*0fca6ea1SDimitry Andric                                 IsDeduced ? PackFold::ArgumentToParameter
6221*0fca6ea1SDimitry Andric                                           : PackFold::ParameterToArgument) !=
6222*0fca6ea1SDimitry Andric       TemplateDeductionResult::Success)
6223*0fca6ea1SDimitry Andric     return false;
6224*0fca6ea1SDimitry Andric 
6225*0fca6ea1SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
6226*0fca6ea1SDimitry Andric   Sema::InstantiatingTemplate Inst(*this, Info.getLocation(), AArg, DeducedArgs,
6227*0fca6ea1SDimitry Andric                                    Info);
6228*0fca6ea1SDimitry Andric   if (Inst.isInvalid())
6229*0fca6ea1SDimitry Andric     return false;
6230*0fca6ea1SDimitry Andric 
6231*0fca6ea1SDimitry Andric   bool AtLeastAsSpecialized;
6232*0fca6ea1SDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
6233*0fca6ea1SDimitry Andric     AtLeastAsSpecialized =
6234*0fca6ea1SDimitry Andric         ::FinishTemplateArgumentDeduction(
6235*0fca6ea1SDimitry Andric             *this, AArg, /*IsPartialOrdering=*/true, PArgs, Deduced, Info) ==
6236*0fca6ea1SDimitry Andric         TemplateDeductionResult::Success;
6237*0fca6ea1SDimitry Andric   });
6238*0fca6ea1SDimitry Andric   return AtLeastAsSpecialized;
62390b57cec5SDimitry Andric }
62400b57cec5SDimitry Andric 
6241480093f4SDimitry Andric namespace {
6242480093f4SDimitry Andric struct MarkUsedTemplateParameterVisitor :
6243480093f4SDimitry Andric     RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> {
6244480093f4SDimitry Andric   llvm::SmallBitVector &Used;
6245480093f4SDimitry Andric   unsigned Depth;
6246480093f4SDimitry Andric 
MarkUsedTemplateParameterVisitor__anonc4c693d01d11::MarkUsedTemplateParameterVisitor6247480093f4SDimitry Andric   MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
6248480093f4SDimitry Andric                                    unsigned Depth)
6249480093f4SDimitry Andric       : Used(Used), Depth(Depth) { }
6250480093f4SDimitry Andric 
VisitTemplateTypeParmType__anonc4c693d01d11::MarkUsedTemplateParameterVisitor6251480093f4SDimitry Andric   bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
6252480093f4SDimitry Andric     if (T->getDepth() == Depth)
6253480093f4SDimitry Andric       Used[T->getIndex()] = true;
6254480093f4SDimitry Andric     return true;
6255480093f4SDimitry Andric   }
6256480093f4SDimitry Andric 
TraverseTemplateName__anonc4c693d01d11::MarkUsedTemplateParameterVisitor6257480093f4SDimitry Andric   bool TraverseTemplateName(TemplateName Template) {
6258bdd1243dSDimitry Andric     if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
6259bdd1243dSDimitry Andric             Template.getAsTemplateDecl()))
6260480093f4SDimitry Andric       if (TTP->getDepth() == Depth)
6261480093f4SDimitry Andric         Used[TTP->getIndex()] = true;
6262480093f4SDimitry Andric     RecursiveASTVisitor<MarkUsedTemplateParameterVisitor>::
6263480093f4SDimitry Andric         TraverseTemplateName(Template);
6264480093f4SDimitry Andric     return true;
6265480093f4SDimitry Andric   }
6266480093f4SDimitry Andric 
VisitDeclRefExpr__anonc4c693d01d11::MarkUsedTemplateParameterVisitor6267480093f4SDimitry Andric   bool VisitDeclRefExpr(DeclRefExpr *E) {
6268480093f4SDimitry Andric     if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
6269480093f4SDimitry Andric       if (NTTP->getDepth() == Depth)
6270480093f4SDimitry Andric         Used[NTTP->getIndex()] = true;
6271480093f4SDimitry Andric     return true;
6272480093f4SDimitry Andric   }
6273480093f4SDimitry Andric };
6274480093f4SDimitry Andric }
6275480093f4SDimitry Andric 
62760b57cec5SDimitry Andric /// Mark the template parameters that are used by the given
62770b57cec5SDimitry Andric /// expression.
62780b57cec5SDimitry Andric static void
MarkUsedTemplateParameters(ASTContext & Ctx,const Expr * E,bool OnlyDeduced,unsigned Depth,llvm::SmallBitVector & Used)62790b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx,
62800b57cec5SDimitry Andric                            const Expr *E,
62810b57cec5SDimitry Andric                            bool OnlyDeduced,
62820b57cec5SDimitry Andric                            unsigned Depth,
62830b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
6284480093f4SDimitry Andric   if (!OnlyDeduced) {
6285480093f4SDimitry Andric     MarkUsedTemplateParameterVisitor(Used, Depth)
6286480093f4SDimitry Andric         .TraverseStmt(const_cast<Expr *>(E));
6287480093f4SDimitry Andric     return;
6288480093f4SDimitry Andric   }
6289480093f4SDimitry Andric 
62900b57cec5SDimitry Andric   // We can deduce from a pack expansion.
62910b57cec5SDimitry Andric   if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
62920b57cec5SDimitry Andric     E = Expansion->getPattern();
62930b57cec5SDimitry Andric 
6294e8d8bef9SDimitry Andric   const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(E, Depth);
62950b57cec5SDimitry Andric   if (!NTTP)
62960b57cec5SDimitry Andric     return;
62970b57cec5SDimitry Andric 
62980b57cec5SDimitry Andric   if (NTTP->getDepth() == Depth)
62990b57cec5SDimitry Andric     Used[NTTP->getIndex()] = true;
63000b57cec5SDimitry Andric 
63010b57cec5SDimitry Andric   // In C++17 mode, additional arguments may be deduced from the type of a
63020b57cec5SDimitry Andric   // non-type argument.
63030b57cec5SDimitry Andric   if (Ctx.getLangOpts().CPlusPlus17)
63040b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
63050b57cec5SDimitry Andric }
63060b57cec5SDimitry Andric 
63070b57cec5SDimitry Andric /// Mark the template parameters that are used by the given
63080b57cec5SDimitry Andric /// nested name specifier.
63090b57cec5SDimitry Andric static void
MarkUsedTemplateParameters(ASTContext & Ctx,NestedNameSpecifier * NNS,bool OnlyDeduced,unsigned Depth,llvm::SmallBitVector & Used)63100b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx,
63110b57cec5SDimitry Andric                            NestedNameSpecifier *NNS,
63120b57cec5SDimitry Andric                            bool OnlyDeduced,
63130b57cec5SDimitry Andric                            unsigned Depth,
63140b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
63150b57cec5SDimitry Andric   if (!NNS)
63160b57cec5SDimitry Andric     return;
63170b57cec5SDimitry Andric 
63180b57cec5SDimitry Andric   MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
63190b57cec5SDimitry Andric                              Used);
63200b57cec5SDimitry Andric   MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
63210b57cec5SDimitry Andric                              OnlyDeduced, Depth, Used);
63220b57cec5SDimitry Andric }
63230b57cec5SDimitry Andric 
63240b57cec5SDimitry Andric /// Mark the template parameters that are used by the given
63250b57cec5SDimitry Andric /// template name.
63260b57cec5SDimitry Andric static void
MarkUsedTemplateParameters(ASTContext & Ctx,TemplateName Name,bool OnlyDeduced,unsigned Depth,llvm::SmallBitVector & Used)63270b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx,
63280b57cec5SDimitry Andric                            TemplateName Name,
63290b57cec5SDimitry Andric                            bool OnlyDeduced,
63300b57cec5SDimitry Andric                            unsigned Depth,
63310b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
63320b57cec5SDimitry Andric   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
63330b57cec5SDimitry Andric     if (TemplateTemplateParmDecl *TTP
63340b57cec5SDimitry Andric           = dyn_cast<TemplateTemplateParmDecl>(Template)) {
63350b57cec5SDimitry Andric       if (TTP->getDepth() == Depth)
63360b57cec5SDimitry Andric         Used[TTP->getIndex()] = true;
63370b57cec5SDimitry Andric     }
63380b57cec5SDimitry Andric     return;
63390b57cec5SDimitry Andric   }
63400b57cec5SDimitry Andric 
63410b57cec5SDimitry Andric   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
63420b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
63430b57cec5SDimitry Andric                                Depth, Used);
63440b57cec5SDimitry Andric   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
63450b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
63460b57cec5SDimitry Andric                                Depth, Used);
63470b57cec5SDimitry Andric }
63480b57cec5SDimitry Andric 
63490b57cec5SDimitry Andric /// Mark the template parameters that are used by the given
63500b57cec5SDimitry Andric /// type.
63510b57cec5SDimitry Andric static void
MarkUsedTemplateParameters(ASTContext & Ctx,QualType T,bool OnlyDeduced,unsigned Depth,llvm::SmallBitVector & Used)63520b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
63530b57cec5SDimitry Andric                            bool OnlyDeduced,
63540b57cec5SDimitry Andric                            unsigned Depth,
63550b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
63560b57cec5SDimitry Andric   if (T.isNull())
63570b57cec5SDimitry Andric     return;
63580b57cec5SDimitry Andric 
63590b57cec5SDimitry Andric   // Non-dependent types have nothing deducible
63600b57cec5SDimitry Andric   if (!T->isDependentType())
63610b57cec5SDimitry Andric     return;
63620b57cec5SDimitry Andric 
63630b57cec5SDimitry Andric   T = Ctx.getCanonicalType(T);
63640b57cec5SDimitry Andric   switch (T->getTypeClass()) {
63650b57cec5SDimitry Andric   case Type::Pointer:
63660b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
63670b57cec5SDimitry Andric                                cast<PointerType>(T)->getPointeeType(),
63680b57cec5SDimitry Andric                                OnlyDeduced,
63690b57cec5SDimitry Andric                                Depth,
63700b57cec5SDimitry Andric                                Used);
63710b57cec5SDimitry Andric     break;
63720b57cec5SDimitry Andric 
63730b57cec5SDimitry Andric   case Type::BlockPointer:
63740b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
63750b57cec5SDimitry Andric                                cast<BlockPointerType>(T)->getPointeeType(),
63760b57cec5SDimitry Andric                                OnlyDeduced,
63770b57cec5SDimitry Andric                                Depth,
63780b57cec5SDimitry Andric                                Used);
63790b57cec5SDimitry Andric     break;
63800b57cec5SDimitry Andric 
63810b57cec5SDimitry Andric   case Type::LValueReference:
63820b57cec5SDimitry Andric   case Type::RValueReference:
63830b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
63840b57cec5SDimitry Andric                                cast<ReferenceType>(T)->getPointeeType(),
63850b57cec5SDimitry Andric                                OnlyDeduced,
63860b57cec5SDimitry Andric                                Depth,
63870b57cec5SDimitry Andric                                Used);
63880b57cec5SDimitry Andric     break;
63890b57cec5SDimitry Andric 
63900b57cec5SDimitry Andric   case Type::MemberPointer: {
63910b57cec5SDimitry Andric     const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
63920b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
63930b57cec5SDimitry Andric                                Depth, Used);
63940b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
63950b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
63960b57cec5SDimitry Andric     break;
63970b57cec5SDimitry Andric   }
63980b57cec5SDimitry Andric 
63990b57cec5SDimitry Andric   case Type::DependentSizedArray:
64000b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
64010b57cec5SDimitry Andric                                cast<DependentSizedArrayType>(T)->getSizeExpr(),
64020b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
64030b57cec5SDimitry Andric     // Fall through to check the element type
6404bdd1243dSDimitry Andric     [[fallthrough]];
64050b57cec5SDimitry Andric 
64060b57cec5SDimitry Andric   case Type::ConstantArray:
64070b57cec5SDimitry Andric   case Type::IncompleteArray:
6408*0fca6ea1SDimitry Andric   case Type::ArrayParameter:
64090b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
64100b57cec5SDimitry Andric                                cast<ArrayType>(T)->getElementType(),
64110b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
64120b57cec5SDimitry Andric     break;
64130b57cec5SDimitry Andric   case Type::Vector:
64140b57cec5SDimitry Andric   case Type::ExtVector:
64150b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
64160b57cec5SDimitry Andric                                cast<VectorType>(T)->getElementType(),
64170b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
64180b57cec5SDimitry Andric     break;
64190b57cec5SDimitry Andric 
64200b57cec5SDimitry Andric   case Type::DependentVector: {
64210b57cec5SDimitry Andric     const auto *VecType = cast<DependentVectorType>(T);
64220b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
64230b57cec5SDimitry Andric                                Depth, Used);
64240b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
64250b57cec5SDimitry Andric                                Used);
64260b57cec5SDimitry Andric     break;
64270b57cec5SDimitry Andric   }
64280b57cec5SDimitry Andric   case Type::DependentSizedExtVector: {
64290b57cec5SDimitry Andric     const DependentSizedExtVectorType *VecType
64300b57cec5SDimitry Andric       = cast<DependentSizedExtVectorType>(T);
64310b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
64320b57cec5SDimitry Andric                                Depth, Used);
64330b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
64340b57cec5SDimitry Andric                                Depth, Used);
64350b57cec5SDimitry Andric     break;
64360b57cec5SDimitry Andric   }
64370b57cec5SDimitry Andric 
64380b57cec5SDimitry Andric   case Type::DependentAddressSpace: {
64390b57cec5SDimitry Andric     const DependentAddressSpaceType *DependentASType =
64400b57cec5SDimitry Andric         cast<DependentAddressSpaceType>(T);
64410b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
64420b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
64430b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
64440b57cec5SDimitry Andric                                DependentASType->getAddrSpaceExpr(),
64450b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
64460b57cec5SDimitry Andric     break;
64470b57cec5SDimitry Andric   }
64480b57cec5SDimitry Andric 
64495ffd83dbSDimitry Andric   case Type::ConstantMatrix: {
64505ffd83dbSDimitry Andric     const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
64515ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
64525ffd83dbSDimitry Andric                                Depth, Used);
64535ffd83dbSDimitry Andric     break;
64545ffd83dbSDimitry Andric   }
64555ffd83dbSDimitry Andric 
64565ffd83dbSDimitry Andric   case Type::DependentSizedMatrix: {
64575ffd83dbSDimitry Andric     const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
64585ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
64595ffd83dbSDimitry Andric                                Depth, Used);
64605ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
64615ffd83dbSDimitry Andric                                Used);
64625ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
64635ffd83dbSDimitry Andric                                Depth, Used);
64645ffd83dbSDimitry Andric     break;
64655ffd83dbSDimitry Andric   }
64665ffd83dbSDimitry Andric 
64670b57cec5SDimitry Andric   case Type::FunctionProto: {
64680b57cec5SDimitry Andric     const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
64690b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
64700b57cec5SDimitry Andric                                Used);
64710b57cec5SDimitry Andric     for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
64720b57cec5SDimitry Andric       // C++17 [temp.deduct.type]p5:
64730b57cec5SDimitry Andric       //   The non-deduced contexts are: [...]
64740b57cec5SDimitry Andric       //   -- A function parameter pack that does not occur at the end of the
64750b57cec5SDimitry Andric       //      parameter-declaration-list.
64760b57cec5SDimitry Andric       if (!OnlyDeduced || I + 1 == N ||
64770b57cec5SDimitry Andric           !Proto->getParamType(I)->getAs<PackExpansionType>()) {
64780b57cec5SDimitry Andric         MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
64790b57cec5SDimitry Andric                                    Depth, Used);
64800b57cec5SDimitry Andric       } else {
64810b57cec5SDimitry Andric         // FIXME: C++17 [temp.deduct.call]p1:
64820b57cec5SDimitry Andric         //   When a function parameter pack appears in a non-deduced context,
64830b57cec5SDimitry Andric         //   the type of that pack is never deduced.
64840b57cec5SDimitry Andric         //
64850b57cec5SDimitry Andric         // We should also track a set of "never deduced" parameters, and
64860b57cec5SDimitry Andric         // subtract that from the list of deduced parameters after marking.
64870b57cec5SDimitry Andric       }
64880b57cec5SDimitry Andric     }
64890b57cec5SDimitry Andric     if (auto *E = Proto->getNoexceptExpr())
64900b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
64910b57cec5SDimitry Andric     break;
64920b57cec5SDimitry Andric   }
64930b57cec5SDimitry Andric 
64940b57cec5SDimitry Andric   case Type::TemplateTypeParm: {
64950b57cec5SDimitry Andric     const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
64960b57cec5SDimitry Andric     if (TTP->getDepth() == Depth)
64970b57cec5SDimitry Andric       Used[TTP->getIndex()] = true;
64980b57cec5SDimitry Andric     break;
64990b57cec5SDimitry Andric   }
65000b57cec5SDimitry Andric 
65010b57cec5SDimitry Andric   case Type::SubstTemplateTypeParmPack: {
65020b57cec5SDimitry Andric     const SubstTemplateTypeParmPackType *Subst
65030b57cec5SDimitry Andric       = cast<SubstTemplateTypeParmPackType>(T);
6504bdd1243dSDimitry Andric     if (Subst->getReplacedParameter()->getDepth() == Depth)
6505bdd1243dSDimitry Andric       Used[Subst->getIndex()] = true;
65060b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
65070b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
65080b57cec5SDimitry Andric     break;
65090b57cec5SDimitry Andric   }
65100b57cec5SDimitry Andric 
65110b57cec5SDimitry Andric   case Type::InjectedClassName:
65120b57cec5SDimitry Andric     T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6513bdd1243dSDimitry Andric     [[fallthrough]];
65140b57cec5SDimitry Andric 
65150b57cec5SDimitry Andric   case Type::TemplateSpecialization: {
65160b57cec5SDimitry Andric     const TemplateSpecializationType *Spec
65170b57cec5SDimitry Andric       = cast<TemplateSpecializationType>(T);
65180b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
65190b57cec5SDimitry Andric                                Depth, Used);
65200b57cec5SDimitry Andric 
65210b57cec5SDimitry Andric     // C++0x [temp.deduct.type]p9:
65220b57cec5SDimitry Andric     //   If the template argument list of P contains a pack expansion that is
65230b57cec5SDimitry Andric     //   not the last template argument, the entire template argument list is a
65240b57cec5SDimitry Andric     //   non-deduced context.
65250b57cec5SDimitry Andric     if (OnlyDeduced &&
65260b57cec5SDimitry Andric         hasPackExpansionBeforeEnd(Spec->template_arguments()))
65270b57cec5SDimitry Andric       break;
65280b57cec5SDimitry Andric 
6529bdd1243dSDimitry Andric     for (const auto &Arg : Spec->template_arguments())
6530bdd1243dSDimitry Andric       MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
65310b57cec5SDimitry Andric     break;
65320b57cec5SDimitry Andric   }
65330b57cec5SDimitry Andric 
65340b57cec5SDimitry Andric   case Type::Complex:
65350b57cec5SDimitry Andric     if (!OnlyDeduced)
65360b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
65370b57cec5SDimitry Andric                                  cast<ComplexType>(T)->getElementType(),
65380b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
65390b57cec5SDimitry Andric     break;
65400b57cec5SDimitry Andric 
65410b57cec5SDimitry Andric   case Type::Atomic:
65420b57cec5SDimitry Andric     if (!OnlyDeduced)
65430b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
65440b57cec5SDimitry Andric                                  cast<AtomicType>(T)->getValueType(),
65450b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
65460b57cec5SDimitry Andric     break;
65470b57cec5SDimitry Andric 
65480b57cec5SDimitry Andric   case Type::DependentName:
65490b57cec5SDimitry Andric     if (!OnlyDeduced)
65500b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
65510b57cec5SDimitry Andric                                  cast<DependentNameType>(T)->getQualifier(),
65520b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
65530b57cec5SDimitry Andric     break;
65540b57cec5SDimitry Andric 
65550b57cec5SDimitry Andric   case Type::DependentTemplateSpecialization: {
65560b57cec5SDimitry Andric     // C++14 [temp.deduct.type]p5:
65570b57cec5SDimitry Andric     //   The non-deduced contexts are:
65580b57cec5SDimitry Andric     //     -- The nested-name-specifier of a type that was specified using a
65590b57cec5SDimitry Andric     //        qualified-id
65600b57cec5SDimitry Andric     //
65610b57cec5SDimitry Andric     // C++14 [temp.deduct.type]p6:
65620b57cec5SDimitry Andric     //   When a type name is specified in a way that includes a non-deduced
65630b57cec5SDimitry Andric     //   context, all of the types that comprise that type name are also
65640b57cec5SDimitry Andric     //   non-deduced.
65650b57cec5SDimitry Andric     if (OnlyDeduced)
65660b57cec5SDimitry Andric       break;
65670b57cec5SDimitry Andric 
65680b57cec5SDimitry Andric     const DependentTemplateSpecializationType *Spec
65690b57cec5SDimitry Andric       = cast<DependentTemplateSpecializationType>(T);
65700b57cec5SDimitry Andric 
65710b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
65720b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
65730b57cec5SDimitry Andric 
6574bdd1243dSDimitry Andric     for (const auto &Arg : Spec->template_arguments())
6575bdd1243dSDimitry Andric       MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
65760b57cec5SDimitry Andric     break;
65770b57cec5SDimitry Andric   }
65780b57cec5SDimitry Andric 
65790b57cec5SDimitry Andric   case Type::TypeOf:
65800b57cec5SDimitry Andric     if (!OnlyDeduced)
6581bdd1243dSDimitry Andric       MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
65820b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
65830b57cec5SDimitry Andric     break;
65840b57cec5SDimitry Andric 
65850b57cec5SDimitry Andric   case Type::TypeOfExpr:
65860b57cec5SDimitry Andric     if (!OnlyDeduced)
65870b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
65880b57cec5SDimitry Andric                                  cast<TypeOfExprType>(T)->getUnderlyingExpr(),
65890b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
65900b57cec5SDimitry Andric     break;
65910b57cec5SDimitry Andric 
65920b57cec5SDimitry Andric   case Type::Decltype:
65930b57cec5SDimitry Andric     if (!OnlyDeduced)
65940b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
65950b57cec5SDimitry Andric                                  cast<DecltypeType>(T)->getUnderlyingExpr(),
65960b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
65970b57cec5SDimitry Andric     break;
65980b57cec5SDimitry Andric 
6599*0fca6ea1SDimitry Andric   case Type::PackIndexing:
6600*0fca6ea1SDimitry Andric     if (!OnlyDeduced) {
6601*0fca6ea1SDimitry Andric       MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getPattern(),
6602*0fca6ea1SDimitry Andric                                  OnlyDeduced, Depth, Used);
6603*0fca6ea1SDimitry Andric       MarkUsedTemplateParameters(Ctx, cast<PackIndexingType>(T)->getIndexExpr(),
6604*0fca6ea1SDimitry Andric                                  OnlyDeduced, Depth, Used);
6605*0fca6ea1SDimitry Andric     }
6606*0fca6ea1SDimitry Andric     break;
6607*0fca6ea1SDimitry Andric 
66080b57cec5SDimitry Andric   case Type::UnaryTransform:
66090b57cec5SDimitry Andric     if (!OnlyDeduced)
66100b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
66110b57cec5SDimitry Andric                                  cast<UnaryTransformType>(T)->getUnderlyingType(),
66120b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
66130b57cec5SDimitry Andric     break;
66140b57cec5SDimitry Andric 
66150b57cec5SDimitry Andric   case Type::PackExpansion:
66160b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
66170b57cec5SDimitry Andric                                cast<PackExpansionType>(T)->getPattern(),
66180b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
66190b57cec5SDimitry Andric     break;
66200b57cec5SDimitry Andric 
66210b57cec5SDimitry Andric   case Type::Auto:
66220b57cec5SDimitry Andric   case Type::DeducedTemplateSpecialization:
66230b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
66240b57cec5SDimitry Andric                                cast<DeducedType>(T)->getDeducedType(),
66250b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
66260b57cec5SDimitry Andric     break;
66270eae32dcSDimitry Andric   case Type::DependentBitInt:
66285ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx,
66290eae32dcSDimitry Andric                                cast<DependentBitIntType>(T)->getNumBitsExpr(),
66305ffd83dbSDimitry Andric                                OnlyDeduced, Depth, Used);
66315ffd83dbSDimitry Andric     break;
66320b57cec5SDimitry Andric 
66330b57cec5SDimitry Andric   // None of these types have any template parameters in them.
66340b57cec5SDimitry Andric   case Type::Builtin:
66350b57cec5SDimitry Andric   case Type::VariableArray:
66360b57cec5SDimitry Andric   case Type::FunctionNoProto:
66370b57cec5SDimitry Andric   case Type::Record:
66380b57cec5SDimitry Andric   case Type::Enum:
66390b57cec5SDimitry Andric   case Type::ObjCInterface:
66400b57cec5SDimitry Andric   case Type::ObjCObject:
66410b57cec5SDimitry Andric   case Type::ObjCObjectPointer:
66420b57cec5SDimitry Andric   case Type::UnresolvedUsing:
66430b57cec5SDimitry Andric   case Type::Pipe:
66440eae32dcSDimitry Andric   case Type::BitInt:
66450b57cec5SDimitry Andric #define TYPE(Class, Base)
66460b57cec5SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
66470b57cec5SDimitry Andric #define DEPENDENT_TYPE(Class, Base)
66480b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6649a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
66500b57cec5SDimitry Andric     break;
66510b57cec5SDimitry Andric   }
66520b57cec5SDimitry Andric }
66530b57cec5SDimitry Andric 
66540b57cec5SDimitry Andric /// Mark the template parameters that are used by this
66550b57cec5SDimitry Andric /// template argument.
66560b57cec5SDimitry Andric static void
MarkUsedTemplateParameters(ASTContext & Ctx,const TemplateArgument & TemplateArg,bool OnlyDeduced,unsigned Depth,llvm::SmallBitVector & Used)66570b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx,
66580b57cec5SDimitry Andric                            const TemplateArgument &TemplateArg,
66590b57cec5SDimitry Andric                            bool OnlyDeduced,
66600b57cec5SDimitry Andric                            unsigned Depth,
66610b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
66620b57cec5SDimitry Andric   switch (TemplateArg.getKind()) {
66630b57cec5SDimitry Andric   case TemplateArgument::Null:
66640b57cec5SDimitry Andric   case TemplateArgument::Integral:
66650b57cec5SDimitry Andric   case TemplateArgument::Declaration:
66660b57cec5SDimitry Andric   case TemplateArgument::NullPtr:
66677a6dacacSDimitry Andric   case TemplateArgument::StructuralValue:
66680b57cec5SDimitry Andric     break;
66690b57cec5SDimitry Andric 
66700b57cec5SDimitry Andric   case TemplateArgument::Type:
66710b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
66720b57cec5SDimitry Andric                                Depth, Used);
66730b57cec5SDimitry Andric     break;
66740b57cec5SDimitry Andric 
66750b57cec5SDimitry Andric   case TemplateArgument::Template:
66760b57cec5SDimitry Andric   case TemplateArgument::TemplateExpansion:
66770b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
66780b57cec5SDimitry Andric                                TemplateArg.getAsTemplateOrTemplatePattern(),
66790b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
66800b57cec5SDimitry Andric     break;
66810b57cec5SDimitry Andric 
66820b57cec5SDimitry Andric   case TemplateArgument::Expression:
66830b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
66840b57cec5SDimitry Andric                                Depth, Used);
66850b57cec5SDimitry Andric     break;
66860b57cec5SDimitry Andric 
66870b57cec5SDimitry Andric   case TemplateArgument::Pack:
66880b57cec5SDimitry Andric     for (const auto &P : TemplateArg.pack_elements())
66890b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
66900b57cec5SDimitry Andric     break;
66910b57cec5SDimitry Andric   }
66920b57cec5SDimitry Andric }
66930b57cec5SDimitry Andric 
6694480093f4SDimitry Andric void
MarkUsedTemplateParameters(const Expr * E,bool OnlyDeduced,unsigned Depth,llvm::SmallBitVector & Used)6695480093f4SDimitry Andric Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6696480093f4SDimitry Andric                                  unsigned Depth,
6697480093f4SDimitry Andric                                  llvm::SmallBitVector &Used) {
6698480093f4SDimitry Andric   ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6699480093f4SDimitry Andric }
6700480093f4SDimitry Andric 
67010b57cec5SDimitry Andric void
MarkUsedTemplateParameters(const TemplateArgumentList & TemplateArgs,bool OnlyDeduced,unsigned Depth,llvm::SmallBitVector & Used)67020b57cec5SDimitry Andric Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
67030b57cec5SDimitry Andric                                  bool OnlyDeduced, unsigned Depth,
67040b57cec5SDimitry Andric                                  llvm::SmallBitVector &Used) {
67050b57cec5SDimitry Andric   // C++0x [temp.deduct.type]p9:
67060b57cec5SDimitry Andric   //   If the template argument list of P contains a pack expansion that is not
67070b57cec5SDimitry Andric   //   the last template argument, the entire template argument list is a
67080b57cec5SDimitry Andric   //   non-deduced context.
67090b57cec5SDimitry Andric   if (OnlyDeduced &&
67100b57cec5SDimitry Andric       hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
67110b57cec5SDimitry Andric     return;
67120b57cec5SDimitry Andric 
67130b57cec5SDimitry Andric   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
67140b57cec5SDimitry Andric     ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
67150b57cec5SDimitry Andric                                  Depth, Used);
67160b57cec5SDimitry Andric }
67170b57cec5SDimitry Andric 
MarkDeducedTemplateParameters(ASTContext & Ctx,const FunctionTemplateDecl * FunctionTemplate,llvm::SmallBitVector & Deduced)67180b57cec5SDimitry Andric void Sema::MarkDeducedTemplateParameters(
67190b57cec5SDimitry Andric     ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
67200b57cec5SDimitry Andric     llvm::SmallBitVector &Deduced) {
67210b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
67220b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
67230b57cec5SDimitry Andric   Deduced.clear();
67240b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
67250b57cec5SDimitry Andric 
67260b57cec5SDimitry Andric   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
67270b57cec5SDimitry Andric   for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
67280b57cec5SDimitry Andric     ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
67290b57cec5SDimitry Andric                                  true, TemplateParams->getDepth(), Deduced);
67300b57cec5SDimitry Andric }
67310b57cec5SDimitry Andric 
hasDeducibleTemplateParameters(Sema & S,FunctionTemplateDecl * FunctionTemplate,QualType T)67320b57cec5SDimitry Andric bool hasDeducibleTemplateParameters(Sema &S,
67330b57cec5SDimitry Andric                                     FunctionTemplateDecl *FunctionTemplate,
67340b57cec5SDimitry Andric                                     QualType T) {
67350b57cec5SDimitry Andric   if (!T->isDependentType())
67360b57cec5SDimitry Andric     return false;
67370b57cec5SDimitry Andric 
67380b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
67390b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
67400b57cec5SDimitry Andric   llvm::SmallBitVector Deduced(TemplateParams->size());
67410b57cec5SDimitry Andric   ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
67420b57cec5SDimitry Andric                                Deduced);
67430b57cec5SDimitry Andric 
67440b57cec5SDimitry Andric   return Deduced.any();
67450b57cec5SDimitry Andric }
6746