blob: 51d2bae08ca8ff3506c542b2b800b40c673ce424 [file] [log] [blame]
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor55ca8f62009-06-04 00:03:07 +00007//
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00008//===----------------------------------------------------------------------===//
Douglas Gregor55ca8f62009-06-04 00:03:07 +00009//
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000010// This file implements C++ template argument deduction.
11//
12//===----------------------------------------------------------------------===//
Douglas Gregor55ca8f62009-06-04 00:03:07 +000013
John McCall19c1bfd2010-08-25 05:32:35 +000014#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "TreeTransform.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000016#include "TypeLocBuilder.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000017#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000018#include "clang/AST/ASTLambda.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000019#include "clang/AST/Decl.h"
20#include "clang/AST/DeclAccessPair.h"
21#include "clang/AST/DeclBase.h"
22#include "clang/AST/DeclCXX.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000023#include "clang/AST/DeclTemplate.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000024#include "clang/AST/DeclarationName.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000025#include "clang/AST/Expr.h"
26#include "clang/AST/ExprCXX.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000027#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/AST/TemplateBase.h"
29#include "clang/AST/TemplateName.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/AddressSpaces.h"
34#include "clang/Basic/ExceptionSpecificationType.h"
35#include "clang/Basic/LLVM.h"
36#include "clang/Basic/LangOptions.h"
37#include "clang/Basic/PartialDiagnostic.h"
38#include "clang/Basic/SourceLocation.h"
39#include "clang/Basic/Specifiers.h"
40#include "clang/Sema/Ownership.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "clang/Sema/Sema.h"
42#include "clang/Sema/Template.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000043#include "llvm/ADT/APInt.h"
44#include "llvm/ADT/APSInt.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/DenseMap.h"
47#include "llvm/ADT/FoldingSet.h"
48#include "llvm/ADT/Optional.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000049#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000050#include "llvm/ADT/SmallPtrSet.h"
51#include "llvm/ADT/SmallVector.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000055#include <algorithm>
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000056#include <cassert>
57#include <tuple>
58#include <utility>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000059
60namespace clang {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000061
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000062 /// Various flags that control template argument deduction.
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000063 ///
64 /// These flags can be bitwise-OR'd together.
65 enum TemplateDeductionFlags {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000066 /// No template argument deduction flags, which indicates the
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000067 /// strictest results for template argument deduction (as used for, e.g.,
68 /// matching class template partial specializations).
69 TDF_None = 0,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Within template argument deduction from a function call, we are
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000072 /// matching with a parameter type for which the original parameter was
73 /// a reference.
74 TDF_ParamWithReferenceType = 0x1,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000076 /// Within template argument deduction from a function call, we
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000077 /// are matching in a case where we ignore cv-qualifiers.
78 TDF_IgnoreQualifiers = 0x02,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000079
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000080 /// Within template argument deduction from a function call,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000081 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000082 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000083 TDF_DerivedClass = 0x04,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000084
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000085 /// Allow non-dependent types to differ, e.g., when performing
Douglas Gregor406f6342009-09-14 20:00:47 +000086 /// template argument deduction from a function call where conversions
87 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000088 TDF_SkipNonDependent = 0x08,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000089
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000090 /// Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000091 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000092 TDF_TopLevelParameterTypeList = 0x10,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000093
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000094 /// Within template argument deduction from overload resolution per
Douglas Gregor19a41f12013-04-17 08:45:07 +000095 /// C++ [over.over] allow matching function types that are compatible in
Richard Smithcd198152017-06-07 21:46:22 +000096 /// terms of noreturn and default calling convention adjustments, or
97 /// similarly matching a declared template specialization against a
98 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
99 /// deduction where the parameter is a function type that can be converted
100 /// to the argument type.
101 TDF_AllowCompatibleFunctionType = 0x20,
Richard Smithb884ed12018-07-11 23:19:41 +0000102
103 /// Within template argument deduction for a conversion function, we are
104 /// matching with an argument type for which the original argument was
105 /// a reference.
106 TDF_ArgWithReferenceType = 0x40,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000107 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000108}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000109
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000110using namespace clang;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000111using namespace sema;
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000112
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000113/// Compare two APSInts, extending and switching the sign as
Douglas Gregor0a29a052010-03-26 05:50:28 +0000114/// necessary to compare their values regardless of underlying type.
115static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
116 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000117 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +0000118 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000119 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +0000120
121 // If there is a signedness mismatch, correct it.
122 if (X.isSigned() != Y.isSigned()) {
123 // If the signed value is negative, then the values cannot be the same.
124 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
125 return false;
126
127 Y.setIsSigned(true);
128 X.setIsSigned(true);
129 }
130
131 return X == Y;
132}
133
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000134static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000135DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000136 TemplateParameterList *TemplateParams,
137 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000138 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000139 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000140 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000141
Douglas Gregor7baabef2010-12-22 18:17:10 +0000142static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000143DeduceTemplateArgumentsByTypeMatch(Sema &S,
144 TemplateParameterList *TemplateParams,
145 QualType Param,
146 QualType Arg,
147 TemplateDeductionInfo &Info,
148 SmallVectorImpl<DeducedTemplateArgument> &
149 Deduced,
150 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000151 bool PartialOrdering = false,
152 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000153
154static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000155DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000156 ArrayRef<TemplateArgument> Params,
157 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000158 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000159 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
160 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000161
Richard Smith130cc442017-02-21 23:49:18 +0000162static void MarkUsedTemplateParameters(ASTContext &Ctx,
163 const TemplateArgument &TemplateArg,
164 bool OnlyDeduced, unsigned Depth,
165 llvm::SmallBitVector &Used);
166
167static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
168 bool OnlyDeduced, unsigned Level,
169 llvm::SmallBitVector &Deduced);
170
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000171/// If the given expression is of a form that permits the deduction
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000172/// of a non-type template parameter, return the declaration of that
173/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000174static NonTypeTemplateParmDecl *
175getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000176 // If we are within an alias template, the expression may have undergone
177 // any number of parameter substitutions already.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000178 while (true) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000179 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
180 E = IC->getSubExpr();
181 else if (SubstNonTypeTemplateParmExpr *Subst =
182 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
183 E = Subst->getReplacement();
184 else
185 break;
186 }
Mike Stump11289f42009-09-09 15:08:12 +0000187
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000188 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000189 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
190 if (NTTP->getDepth() == Info.getDeducedDepth())
191 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000192
Craig Topperc3ec1492014-05-26 06:22:03 +0000193 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000194}
195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000196/// Determine whether two declaration pointers refer to the same
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000197/// declaration.
198static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000199 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
200 X = NX->getUnderlyingDecl();
201 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
202 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000203
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000204 return X->getCanonicalDecl() == Y->getCanonicalDecl();
205}
206
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000207/// Verify that the given, deduced template arguments are compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000208///
209/// \returns The deduced template argument, or a NULL template argument if
210/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000211static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000212checkDeducedTemplateArguments(ASTContext &Context,
213 const DeducedTemplateArgument &X,
214 const DeducedTemplateArgument &Y) {
215 // We have no deduction for one or both of the arguments; they're compatible.
216 if (X.isNull())
217 return Y;
218 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000220
Richard Smith593d6a12016-12-23 01:30:39 +0000221 // If we have two non-type template argument values deduced for the same
222 // parameter, they must both match the type of the parameter, and thus must
223 // match each other's type. As we're only keeping one of them, we must check
224 // for that now. The exception is that if either was deduced from an array
225 // bound, the type is permitted to differ.
226 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
227 QualType XType = X.getNonTypeTemplateArgumentType();
228 if (!XType.isNull()) {
229 QualType YType = Y.getNonTypeTemplateArgumentType();
230 if (YType.isNull() || !Context.hasSameType(XType, YType))
231 return DeducedTemplateArgument();
232 }
233 }
234
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000235 switch (X.getKind()) {
236 case TemplateArgument::Null:
237 llvm_unreachable("Non-deduced template arguments handled above");
238
239 case TemplateArgument::Type:
240 // If two template type arguments have the same type, they're compatible.
241 if (Y.getKind() == TemplateArgument::Type &&
242 Context.hasSameType(X.getAsType(), Y.getAsType()))
243 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000244
Richard Smith5f274382016-09-28 23:55:27 +0000245 // If one of the two arguments was deduced from an array bound, the other
246 // supersedes it.
247 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
248 return X.wasDeducedFromArrayBound() ? Y : X;
249
250 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000251 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000252
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000253 case TemplateArgument::Integral:
254 // If we deduced a constant in one case and either a dependent expression or
255 // declaration in another case, keep the integral constant.
256 // If both are integral constants with the same value, keep that value.
257 if (Y.getKind() == TemplateArgument::Expression ||
258 Y.getKind() == TemplateArgument::Declaration ||
259 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000260 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000261 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000262
263 // All other combinations are incompatible.
264 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000265
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000266 case TemplateArgument::Template:
267 if (Y.getKind() == TemplateArgument::Template &&
268 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
269 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000270
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000271 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000272 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000273
274 case TemplateArgument::TemplateExpansion:
275 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000276 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000277 Y.getAsTemplateOrTemplatePattern()))
278 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000280 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000281 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000282
Richard Smith593d6a12016-12-23 01:30:39 +0000283 case TemplateArgument::Expression: {
284 if (Y.getKind() != TemplateArgument::Expression)
285 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000286
Richard Smith593d6a12016-12-23 01:30:39 +0000287 // Compare the expressions for equality
288 llvm::FoldingSetNodeID ID1, ID2;
289 X.getAsExpr()->Profile(ID1, Context, true);
290 Y.getAsExpr()->Profile(ID2, Context, true);
291 if (ID1 == ID2)
292 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000293
Richard Smith593d6a12016-12-23 01:30:39 +0000294 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000295 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000296 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000297
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000298 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000299 assert(!X.wasDeducedFromArrayBound());
300
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000301 // If we deduced a declaration and a dependent expression, keep the
302 // declaration.
303 if (Y.getKind() == TemplateArgument::Expression)
304 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000306 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000307 // integral constant and whichever type did not come from an array
308 // bound.
309 if (Y.getKind() == TemplateArgument::Integral) {
310 if (Y.wasDeducedFromArrayBound())
311 return TemplateArgument(Context, Y.getAsIntegral(),
312 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000313 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000315
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000316 // If we deduced two declarations, make sure that they refer to the
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000317 // same declaration.
318 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000319 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000320 return X;
321
322 // All other combinations are incompatible.
323 return DeducedTemplateArgument();
324
325 case TemplateArgument::NullPtr:
326 // If we deduced a null pointer and a dependent expression, keep the
327 // null pointer.
328 if (Y.getKind() == TemplateArgument::Expression)
329 return X;
330
331 // If we deduced a null pointer and an integral constant, keep the
332 // integral constant.
333 if (Y.getKind() == TemplateArgument::Integral)
334 return Y;
335
Richard Smith593d6a12016-12-23 01:30:39 +0000336 // If we deduced two null pointers, they are the same.
337 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000338 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000339
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000340 // All other combinations are incompatible.
341 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000342
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000343 case TemplateArgument::Pack: {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000344 if (Y.getKind() != TemplateArgument::Pack ||
345 X.pack_size() != Y.pack_size())
346 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000347
Richard Smith539e8e32017-01-04 01:48:55 +0000348 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000349 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000350 XAEnd = X.pack_end(),
351 YA = Y.pack_begin();
352 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000353 TemplateArgument Merged = checkDeducedTemplateArguments(
354 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
355 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
356 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000357 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000358 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360
Richard Smith539e8e32017-01-04 01:48:55 +0000361 return DeducedTemplateArgument(
362 TemplateArgument::CreatePackCopy(Context, NewPack),
363 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000364 }
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000365 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000366
David Blaikiee4d798f2012-01-20 21:50:17 +0000367 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000368}
369
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000370/// Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000371/// as the given deduced template argument. All non-type template parameter
372/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000373static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000374 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000375 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
376 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000377 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000378 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
379 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000380
Richard Smith5d102892016-12-27 03:59:58 +0000381 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
382 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000383 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000384 Info.Param = NTTP;
385 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000386 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000390 Deduced[NTTP->getIndex()] = Result;
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000391 if (!S.getLangOpts().CPlusPlus17)
Richard Smithd92eddf2016-12-27 06:14:37 +0000392 return Sema::TDK_Success;
393
Richard Smith130cc442017-02-21 23:49:18 +0000394 if (NTTP->isExpandedParameterPack())
395 // FIXME: We may still need to deduce parts of the type here! But we
396 // don't have any way to find which slice of the type to use, and the
397 // type stored on the NTTP itself is nonsense. Perhaps the type of an
398 // expanded NTTP should be a pack expansion type?
399 return Sema::TDK_Success;
400
Richard Smith7bfcc052017-12-01 21:24:36 +0000401 // Get the type of the parameter for deduction. If it's a (dependent) array
402 // or function type, we will not have decayed it yet, so do that now.
403 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
Richard Smith130cc442017-02-21 23:49:18 +0000404 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
405 ParamType = Expansion->getPattern();
406
Richard Smithd92eddf2016-12-27 06:14:37 +0000407 // FIXME: It's not clear how deduction of a parameter of reference
408 // type from an argument (of non-reference type) should be performed.
409 // For now, we just remove reference types from both sides and let
410 // the final check for matching types sort out the mess.
411 return DeduceTemplateArgumentsByTypeMatch(
Richard Smith130cc442017-02-21 23:49:18 +0000412 S, TemplateParams, ParamType.getNonReferenceType(),
Richard Smithd92eddf2016-12-27 06:14:37 +0000413 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
414 /*PartialOrdering=*/false,
415 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000416}
417
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000418/// Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000419/// from the given integral constant.
420static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
421 Sema &S, TemplateParameterList *TemplateParams,
422 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
423 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
424 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
425 return DeduceNonTypeTemplateArgument(
426 S, TemplateParams, NTTP,
427 DeducedTemplateArgument(S.Context, Value, ValueType,
428 DeducedFromArrayBound),
429 ValueType, Info, Deduced);
430}
431
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432/// Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000433/// from the given null pointer template argument type.
434static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000435 Sema &S, TemplateParameterList *TemplateParams,
436 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000437 TemplateDeductionInfo &Info,
438 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
439 Expr *Value =
440 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
441 S.Context.NullPtrTy, NTTP->getLocation()),
442 NullPtrType, CK_NullToPointer)
443 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000444 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
445 DeducedTemplateArgument(Value),
446 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000447}
448
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449/// Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000450/// from the given type- or value-dependent expression.
451///
452/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000453static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
454 Sema &S, TemplateParameterList *TemplateParams,
455 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
456 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000457 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
458 DeducedTemplateArgument(Value),
459 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000460}
461
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000462/// Deduce the value of the given non-type template parameter
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000463/// from the given declaration.
464///
465/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000466static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
467 Sema &S, TemplateParameterList *TemplateParams,
468 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
469 TemplateDeductionInfo &Info,
470 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000471 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000472 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000473 return DeduceNonTypeTemplateArgument(
474 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000475}
476
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000477static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000478DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000479 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000480 TemplateName Param,
481 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000482 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000483 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000484 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000485 if (!ParamDecl) {
486 // The parameter type is dependent and is not a template template parameter,
487 // so there is nothing that we can deduce.
488 return Sema::TDK_Success;
489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490
Douglas Gregoradee3e32009-11-11 23:06:43 +0000491 if (TemplateTemplateParmDecl *TempParam
492 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000493 // If we're not deducing at this depth, there's nothing to deduce.
494 if (TempParam->getDepth() != Info.getDeducedDepth())
495 return Sema::TDK_Success;
496
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000497 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000498 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000499 Deduced[TempParam->getIndex()],
500 NewDeduced);
501 if (Result.isNull()) {
502 Info.Param = TempParam;
503 Info.FirstArg = Deduced[TempParam->getIndex()];
504 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000505 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000506 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000508 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000509 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000511
Douglas Gregoradee3e32009-11-11 23:06:43 +0000512 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000513 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000514 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000515
Douglas Gregoradee3e32009-11-11 23:06:43 +0000516 // Mismatch of non-dependent template parameter to argument.
517 Info.FirstArg = TemplateArgument(Param);
518 Info.SecondArg = TemplateArgument(Arg);
519 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000520}
521
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000522/// Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000523/// type (which is a template-id) with the template argument type.
524///
Chandler Carruthc1263112010-02-07 21:33:28 +0000525/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000526///
527/// \param TemplateParams the template parameters that we are deducing
528///
529/// \param Param the parameter type
530///
531/// \param Arg the argument type
532///
533/// \param Info information about the template argument deduction itself
534///
535/// \param Deduced the deduced template arguments
536///
537/// \returns the result of template argument deduction so far. Note that a
538/// "success" result means that template argument deduction has not yet failed,
539/// but it may still fail, later, for other reasons.
540static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000541DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000542 TemplateParameterList *TemplateParams,
543 const TemplateSpecializationType *Param,
544 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000545 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000546 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000547 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000548
Richard Smith13373182018-01-04 01:24:17 +0000549 // Treat an injected-class-name as its underlying template-id.
550 if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg))
551 Arg = Injected->getInjectedSpecializationType();
552
Douglas Gregore81f3e72009-07-07 23:09:34 +0000553 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000554 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000555 = dyn_cast<TemplateSpecializationType>(Arg)) {
556 // Perform template argument deduction for the template name.
557 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000558 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000559 Param->getTemplateName(),
560 SpecArg->getTemplateName(),
561 Info, Deduced))
562 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000563
Mike Stump11289f42009-09-09 15:08:12 +0000564
Douglas Gregore81f3e72009-07-07 23:09:34 +0000565 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000566 // argument. Ignore any missing/extra arguments, since they could be
567 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000568 return DeduceTemplateArguments(S, TemplateParams,
569 Param->template_arguments(),
570 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000571 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000572 }
Mike Stump11289f42009-09-09 15:08:12 +0000573
Douglas Gregore81f3e72009-07-07 23:09:34 +0000574 // If the argument type is a class template specialization, we
575 // perform template argument deduction using its template
576 // arguments.
577 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000578 if (!RecordArg) {
579 Info.FirstArg = TemplateArgument(QualType(Param, 0));
580 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000581 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000582 }
Mike Stump11289f42009-09-09 15:08:12 +0000583
584 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000585 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000586 if (!SpecArg) {
587 Info.FirstArg = TemplateArgument(QualType(Param, 0));
588 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000589 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000590 }
Mike Stump11289f42009-09-09 15:08:12 +0000591
Douglas Gregore81f3e72009-07-07 23:09:34 +0000592 // Perform template argument deduction for the template name.
593 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000594 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000595 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000596 Param->getTemplateName(),
597 TemplateName(SpecArg->getSpecializedTemplate()),
598 Info, Deduced))
599 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000600
Douglas Gregor7baabef2010-12-22 18:17:10 +0000601 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000602 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
603 SpecArg->getTemplateArgs().asArray(), Info,
604 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000605}
606
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000607/// Determines whether the given type is an opaque type that
John McCall08569062010-08-28 22:14:41 +0000608/// might be more qualified when instantiated.
609static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
610 switch (T->getTypeClass()) {
611 case Type::TypeOfExpr:
612 case Type::TypeOf:
613 case Type::DependentName:
614 case Type::Decltype:
615 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000616 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000617 return true;
618
619 case Type::ConstantArray:
620 case Type::IncompleteArray:
621 case Type::VariableArray:
622 case Type::DependentSizedArray:
623 return IsPossiblyOpaquelyQualifiedType(
624 cast<ArrayType>(T)->getElementType());
625
626 default:
627 return false;
628 }
629}
630
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000631/// Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000633getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000634 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
635 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000636
Douglas Gregor5499af42011-01-05 23:12:31 +0000637 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
638 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor5499af42011-01-05 23:12:31 +0000640 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
641 return std::make_pair(TTP->getDepth(), TTP->getIndex());
642}
643
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000644/// Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000645static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000646getDepthAndIndex(UnexpandedParameterPack UPP) {
647 if (const TemplateTypeParmType *TTP
648 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
649 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000651 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
652}
653
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000654/// Helper function to build a TemplateParameter when we don't
Douglas Gregor5499af42011-01-05 23:12:31 +0000655/// know its type statically.
656static TemplateParameter makeTemplateParameter(Decl *D) {
657 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
658 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000659 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000660 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661
Douglas Gregor5499af42011-01-05 23:12:31 +0000662 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
663}
664
Richard Smith0a80d572014-05-29 01:12:14 +0000665/// A pack that we're currently deducing.
666struct clang::DeducedPack {
Richard Smith0a80d572014-05-29 01:12:14 +0000667 // The index of the pack.
668 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Richard Smith0a80d572014-05-29 01:12:14 +0000670 // The old value of the pack before we started deducing it.
671 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000672
Richard Smith0a80d572014-05-29 01:12:14 +0000673 // A deferred value of this pack from an inner deduction, that couldn't be
674 // deduced because this deduction hadn't happened yet.
675 DeducedTemplateArgument DeferredDeduction;
676
677 // The new value of the pack.
678 SmallVector<DeducedTemplateArgument, 4> New;
679
680 // The outer deduction for this pack, if any.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000681 DeducedPack *Outer = nullptr;
682
683 DeducedPack(unsigned Index) : Index(Index) {}
Richard Smith0a80d572014-05-29 01:12:14 +0000684};
685
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000686namespace {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000687
Richard Smith0a80d572014-05-29 01:12:14 +0000688/// A scope in which we're performing pack deduction.
689class PackDeductionScope {
690public:
691 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
692 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
693 TemplateDeductionInfo &Info, TemplateArgument Pattern)
694 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
Richard Smith130cc442017-02-21 23:49:18 +0000695 // Dig out the partially-substituted pack, if there is one.
696 const TemplateArgument *PartialPackArgs = nullptr;
697 unsigned NumPartialPackArgs = 0;
698 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
699 if (auto *Scope = S.CurrentInstantiationScope)
700 if (auto *Partial = Scope->getPartiallySubstitutedPack(
701 &PartialPackArgs, &NumPartialPackArgs))
702 PartialPackDepthIndex = getDepthAndIndex(Partial);
703
Richard Smith0a80d572014-05-29 01:12:14 +0000704 // Compute the set of template parameter indices that correspond to
705 // parameter packs expanded by the pack expansion.
706 {
707 llvm::SmallBitVector SawIndices(TemplateParams->size());
Richard Smith130cc442017-02-21 23:49:18 +0000708
709 auto AddPack = [&](unsigned Index) {
710 if (SawIndices[Index])
711 return;
712 SawIndices[Index] = true;
713
714 // Save the deduced template argument for the parameter pack expanded
715 // by this pack expansion, then clear out the deduction.
716 DeducedPack Pack(Index);
717 Pack.Saved = Deduced[Index];
718 Deduced[Index] = TemplateArgument();
719
720 Packs.push_back(Pack);
721 };
722
723 // First look for unexpanded packs in the pattern.
Richard Smith0a80d572014-05-29 01:12:14 +0000724 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
725 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
726 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
727 unsigned Depth, Index;
728 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith130cc442017-02-21 23:49:18 +0000729 if (Depth == Info.getDeducedDepth())
730 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000731 }
Richard Smith130cc442017-02-21 23:49:18 +0000732 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
733
734 // This pack expansion will have been partially expanded iff the only
735 // unexpanded parameter pack within it is the partially-substituted pack.
736 IsPartiallyExpanded =
737 Packs.size() == 1 &&
738 PartialPackDepthIndex ==
739 std::make_pair(Info.getDeducedDepth(), Packs.front().Index);
740
741 // Skip over the pack elements that were expanded into separate arguments.
742 if (IsPartiallyExpanded)
743 PackElements += NumPartialPackArgs;
744
745 // We can also have deduced template parameters that do not actually
746 // appear in the pattern, but can be deduced by it (the type of a non-type
747 // template parameter pack, in particular). These won't have prevented us
748 // from partially expanding the pack.
749 llvm::SmallBitVector Used(TemplateParams->size());
750 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
751 Info.getDeducedDepth(), Used);
752 for (int Index = Used.find_first(); Index != -1;
753 Index = Used.find_next(Index))
754 if (TemplateParams->getParam(Index)->isParameterPack())
755 AddPack(Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000756 }
Richard Smith0a80d572014-05-29 01:12:14 +0000757
758 for (auto &Pack : Packs) {
759 if (Info.PendingDeducedPacks.size() > Pack.Index)
760 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
761 else
762 Info.PendingDeducedPacks.resize(Pack.Index + 1);
763 Info.PendingDeducedPacks[Pack.Index] = &Pack;
764
Richard Smith130cc442017-02-21 23:49:18 +0000765 if (PartialPackDepthIndex ==
766 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
767 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
768 // We pre-populate the deduced value of the partially-substituted
769 // pack with the specified value. This is not entirely correct: the
770 // value is supposed to have been substituted, not deduced, but the
771 // cases where this is observable require an exact type match anyway.
772 //
773 // FIXME: If we could represent a "depth i, index j, pack elem k"
774 // parameter, we could substitute the partially-substituted pack
775 // everywhere and avoid this.
776 if (Pack.New.size() > PackElements)
777 Deduced[Pack.Index] = Pack.New[PackElements];
Richard Smith0a80d572014-05-29 01:12:14 +0000778 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000779 }
780 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000781
Richard Smith0a80d572014-05-29 01:12:14 +0000782 ~PackDeductionScope() {
783 for (auto &Pack : Packs)
784 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000785 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000786
Richard Smithde0d34a2017-01-09 07:14:40 +0000787 /// Determine whether this pack has already been partially expanded into a
788 /// sequence of (prior) function parameters / template arguments.
Richard Smith130cc442017-02-21 23:49:18 +0000789 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
Richard Smithde0d34a2017-01-09 07:14:40 +0000790
Richard Smith0a80d572014-05-29 01:12:14 +0000791 /// Move to deducing the next element in each pack that is being deduced.
792 void nextPackElement() {
793 // Capture the deduced template arguments for each parameter pack expanded
794 // by this pack expansion, add them to the list of arguments we've deduced
795 // for that pack, then clear out the deduced argument.
796 for (auto &Pack : Packs) {
797 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000798 if (!Pack.New.empty() || !DeducedArg.isNull()) {
799 while (Pack.New.size() < PackElements)
800 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith130cc442017-02-21 23:49:18 +0000801 if (Pack.New.size() == PackElements)
802 Pack.New.push_back(DeducedArg);
803 else
804 Pack.New[PackElements] = DeducedArg;
805 DeducedArg = Pack.New.size() > PackElements + 1
806 ? Pack.New[PackElements + 1]
807 : DeducedTemplateArgument();
Richard Smith0a80d572014-05-29 01:12:14 +0000808 }
809 }
Richard Smith539e8e32017-01-04 01:48:55 +0000810 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000811 }
812
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000813 /// Finish template argument deduction for a set of argument packs,
Richard Smith0a80d572014-05-29 01:12:14 +0000814 /// producing the argument packs and checking for consistency with prior
815 /// deductions.
Richard Smith539e8e32017-01-04 01:48:55 +0000816 Sema::TemplateDeductionResult finish() {
Richard Smith0a80d572014-05-29 01:12:14 +0000817 // Build argument packs for each of the parameter packs expanded by this
818 // pack expansion.
819 for (auto &Pack : Packs) {
820 // Put back the old value for this pack.
821 Deduced[Pack.Index] = Pack.Saved;
822
823 // Build or find a new value for this pack.
824 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000825 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000826 if (Pack.DeferredDeduction.isNull()) {
827 // We were not able to deduce anything for this parameter pack
828 // (because it only appeared in non-deduced contexts), so just
829 // restore the saved argument pack.
830 continue;
831 }
832
833 NewPack = Pack.DeferredDeduction;
834 Pack.DeferredDeduction = TemplateArgument();
835 } else if (Pack.New.empty()) {
836 // If we deduced an empty argument pack, create it now.
837 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
838 } else {
839 TemplateArgument *ArgumentPack =
840 new (S.Context) TemplateArgument[Pack.New.size()];
841 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
842 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000843 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith7fa88bb2017-02-21 07:22:31 +0000844 // FIXME: This is wrong, it's possible that some pack elements are
845 // deduced from an array bound and others are not:
846 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
847 // g({1, 2, 3}, {{}, {}});
848 // ... should deduce T = {int, size_t (from array bound)}.
Richard Smith0a80d572014-05-29 01:12:14 +0000849 Pack.New[0].wasDeducedFromArrayBound());
850 }
851
852 // Pick where we're going to put the merged pack.
853 DeducedTemplateArgument *Loc;
854 if (Pack.Outer) {
855 if (Pack.Outer->DeferredDeduction.isNull()) {
856 // Defer checking this pack until we have a complete pack to compare
857 // it against.
858 Pack.Outer->DeferredDeduction = NewPack;
859 continue;
860 }
861 Loc = &Pack.Outer->DeferredDeduction;
862 } else {
863 Loc = &Deduced[Pack.Index];
864 }
865
866 // Check the new pack matches any previous value.
867 DeducedTemplateArgument OldPack = *Loc;
868 DeducedTemplateArgument Result =
869 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
870
871 // If we deferred a deduction of this pack, check that one now too.
872 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
873 OldPack = Result;
874 NewPack = Pack.DeferredDeduction;
875 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
876 }
877
878 if (Result.isNull()) {
879 Info.Param =
880 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
881 Info.FirstArg = OldPack;
882 Info.SecondArg = NewPack;
883 return Sema::TDK_Inconsistent;
884 }
885
886 *Loc = Result;
887 }
888
889 return Sema::TDK_Success;
890 }
891
892private:
893 Sema &S;
894 TemplateParameterList *TemplateParams;
895 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
896 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000897 unsigned PackElements = 0;
Richard Smith130cc442017-02-21 23:49:18 +0000898 bool IsPartiallyExpanded = false;
Richard Smith0a80d572014-05-29 01:12:14 +0000899
900 SmallVector<DeducedPack, 2> Packs;
901};
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000902
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000903} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000904
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000905/// Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000906/// types to the list of argument types, as in the parameter-type-lists of
907/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000908///
909/// \param S The semantic analysis object within which we are deducing
910///
911/// \param TemplateParams The template parameters that we are deducing
912///
913/// \param Params The list of parameter types
914///
915/// \param NumParams The number of types in \c Params
916///
917/// \param Args The list of argument types
918///
919/// \param NumArgs The number of types in \c Args
920///
921/// \param Info information about the template argument deduction itself
922///
923/// \param Deduced the deduced template arguments
924///
925/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
926/// how template argument deduction is performed.
927///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000928/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000929/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000930/// (C++0x [temp.deduct.partial]).
931///
Douglas Gregor5499af42011-01-05 23:12:31 +0000932/// \returns the result of template argument deduction so far. Note that a
933/// "success" result means that template argument deduction has not yet failed,
934/// but it may still fail, later, for other reasons.
935static Sema::TemplateDeductionResult
936DeduceTemplateArguments(Sema &S,
937 TemplateParameterList *TemplateParams,
938 const QualType *Params, unsigned NumParams,
939 const QualType *Args, unsigned NumArgs,
940 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000941 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000942 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000943 bool PartialOrdering = false) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000944 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000945 // Similarly, if P has a form that contains (T), then each parameter type
946 // Pi of the respective parameter-type- list of P is compared with the
947 // corresponding parameter type Ai of the corresponding parameter-type-list
948 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000949 unsigned ArgIdx = 0, ParamIdx = 0;
950 for (; ParamIdx != NumParams; ++ParamIdx) {
951 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000952 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000953 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
954 if (!Expansion) {
955 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000956
Douglas Gregor5499af42011-01-05 23:12:31 +0000957 // Make sure we have an argument.
958 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000959 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000960
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000961 if (isa<PackExpansionType>(Args[ArgIdx])) {
962 // C++0x [temp.deduct.type]p22:
963 // If the original function parameter associated with A is a function
964 // parameter pack and the function parameter associated with P is not
965 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000966 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000967 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000968
Douglas Gregor5499af42011-01-05 23:12:31 +0000969 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000970 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
971 Params[ParamIdx], Args[ArgIdx],
972 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000973 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000974 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000975
Douglas Gregor5499af42011-01-05 23:12:31 +0000976 ++ArgIdx;
977 continue;
978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000979
Douglas Gregor5499af42011-01-05 23:12:31 +0000980 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000981 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000982 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000984 // comparison deduces template arguments for subsequent positions in the
985 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000986
Douglas Gregor5499af42011-01-05 23:12:31 +0000987 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000988 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989
Richard Smithc379d1a2018-07-12 23:32:39 +0000990 if (ParamIdx + 1 == NumParams) {
991 for (; ArgIdx < NumArgs; ++ArgIdx) {
992 // Deduce template arguments from the pattern.
993 if (Sema::TemplateDeductionResult Result
994 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
995 Args[ArgIdx], Info, Deduced,
996 TDF, PartialOrdering))
997 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000998
Richard Smithc379d1a2018-07-12 23:32:39 +0000999 PackScope.nextPackElement();
1000 }
1001 } else {
1002 // C++0x [temp.deduct.type]p5:
1003 // The non-deduced contexts are:
1004 // - A function parameter pack that does not occur at the end of the
1005 // parameter-declaration-clause.
1006 //
1007 // FIXME: There is no wording to say what we should do in this case. We
1008 // choose to resolve this by applying the same rule that is applied for a
1009 // function call: that is, deduce all contained packs to their
1010 // explicitly-specified values (or to <> if there is no such value).
1011 //
1012 // This is seemingly-arbitrarily different from the case of a template-id
1013 // with a non-trailing pack-expansion in its arguments, which renders the
1014 // entire template-argument-list a non-deduced context.
1015
1016 // If the parameter type contains an explicitly-specified pack that we
1017 // could not expand, skip the number of parameters notionally created
1018 // by the expansion.
1019 Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1020 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1021 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1022 ++I, ++ArgIdx)
1023 PackScope.nextPackElement();
1024 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001025 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026
Douglas Gregor5499af42011-01-05 23:12:31 +00001027 // Build argument packs for each of the parameter packs expanded by this
1028 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001029 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001030 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +00001031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001032
Douglas Gregor5499af42011-01-05 23:12:31 +00001033 // Make sure we don't have any extra arguments.
1034 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +00001035 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
Douglas Gregor5499af42011-01-05 23:12:31 +00001037 return Sema::TDK_Success;
1038}
1039
Richard Smith34c32502018-07-11 21:07:04 +00001040/// Determine whether the parameter has qualifiers that the argument
1041/// lacks. Put another way, determine whether there is no way to add
1042/// a deduced set of qualifiers to the ParamType that would result in
1043/// its qualifiers matching those of the ArgType.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001044static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1045 QualType ArgType) {
1046 Qualifiers ParamQs = ParamType.getQualifiers();
1047 Qualifiers ArgQs = ArgType.getQualifiers();
1048
1049 if (ParamQs == ArgQs)
1050 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001051
Douglas Gregor1d684c22011-04-28 00:56:09 +00001052 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +00001053 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +00001054 ParamQs.hasObjCGCAttr())
1055 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001056
Douglas Gregor1d684c22011-04-28 00:56:09 +00001057 // Mismatched (but not missing) address spaces.
1058 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1059 ParamQs.hasAddressSpace())
1060 return true;
1061
John McCall31168b02011-06-15 23:02:42 +00001062 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1063 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1064 ParamQs.hasObjCLifetime())
1065 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001066
Richard Smith34c32502018-07-11 21:07:04 +00001067 // CVR qualifiers inconsistent or a superset.
1068 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
Douglas Gregor1d684c22011-04-28 00:56:09 +00001069}
1070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001071/// Compare types for equality with respect to possibly compatible
Douglas Gregor19a41f12013-04-17 08:45:07 +00001072/// function types (noreturn adjustment, implicit calling conventions). If any
1073/// of parameter and argument is not a function, just perform type comparison.
1074///
1075/// \param Param the template parameter type.
1076///
1077/// \param Arg the argument type.
1078bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1079 CanQualType Arg) {
1080 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1081 *ArgFunction = Arg->getAs<FunctionType>();
1082
1083 // Just compare if not functions.
1084 if (!ParamFunction || !ArgFunction)
1085 return Param == Arg;
1086
Richard Smith3c4f8d22016-10-16 17:54:23 +00001087 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001088 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +00001089 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +00001090 return Arg == Context.getCanonicalType(AdjustedParam);
1091
1092 // FIXME: Compatible calling conventions.
1093
1094 return Param == Arg;
1095}
1096
Richard Smith32918772017-02-14 00:25:28 +00001097/// Get the index of the first template parameter that was originally from the
1098/// innermost template-parameter-list. This is 0 except when we concatenate
1099/// the template parameter lists of a class template and a constructor template
1100/// when forming an implicit deduction guide.
1101static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
Richard Smithbc491202017-02-17 20:05:37 +00001102 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1103 if (!Guide || !Guide->isImplicit())
Richard Smith32918772017-02-14 00:25:28 +00001104 return 0;
Richard Smithbc491202017-02-17 20:05:37 +00001105 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
Richard Smith32918772017-02-14 00:25:28 +00001106}
1107
1108/// Determine whether a type denotes a forwarding reference.
1109static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1110 // C++1z [temp.deduct.call]p3:
1111 // A forwarding reference is an rvalue reference to a cv-unqualified
1112 // template parameter that does not represent a template parameter of a
1113 // class template.
1114 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1115 if (ParamRef->getPointeeType().getQualifiers())
1116 return false;
1117 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1118 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1119 }
1120 return false;
1121}
1122
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001123/// Deduce the template arguments by comparing the parameter type and
Douglas Gregorcceb9752009-06-26 18:27:22 +00001124/// the argument type (C++ [temp.deduct.type]).
1125///
Chandler Carruthc1263112010-02-07 21:33:28 +00001126/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +00001127///
1128/// \param TemplateParams the template parameters that we are deducing
1129///
1130/// \param ParamIn the parameter type
1131///
1132/// \param ArgIn the argument type
1133///
1134/// \param Info information about the template argument deduction itself
1135///
1136/// \param Deduced the deduced template arguments
1137///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001138/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001139/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001140///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001141/// \param PartialOrdering Whether we're performing template argument deduction
1142/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1143///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001144/// \returns the result of template argument deduction so far. Note that a
1145/// "success" result means that template argument deduction has not yet failed,
1146/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001147static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001148DeduceTemplateArgumentsByTypeMatch(Sema &S,
1149 TemplateParameterList *TemplateParams,
1150 QualType ParamIn, QualType ArgIn,
1151 TemplateDeductionInfo &Info,
1152 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1153 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001154 bool PartialOrdering,
1155 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001156 // We only want to look at the canonical types, since typedefs and
1157 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001158 QualType Param = S.Context.getCanonicalType(ParamIn);
1159 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001160
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001161 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001162 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001163 if (const PackExpansionType *ArgExpansion
1164 = dyn_cast<PackExpansionType>(Arg))
1165 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001166
Douglas Gregorb837ea42011-01-11 17:34:58 +00001167 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001168 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001169 // Before the partial ordering is done, certain transformations are
1170 // performed on the types used for partial ordering:
1171 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001172 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1173 if (ParamRef)
1174 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001175
Douglas Gregorb837ea42011-01-11 17:34:58 +00001176 // - If A is a reference type, A is replaced by the type referred to.
1177 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1178 if (ArgRef)
1179 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001180
Richard Smithed563c22015-02-20 04:45:22 +00001181 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1182 // C++11 [temp.deduct.partial]p9:
1183 // If, for a given type, deduction succeeds in both directions (i.e.,
1184 // the types are identical after the transformations above) and both
1185 // P and A were reference types [...]:
1186 // - if [one type] was an lvalue reference and [the other type] was
1187 // not, [the other type] is not considered to be at least as
1188 // specialized as [the first type]
1189 // - if [one type] is more cv-qualified than [the other type],
1190 // [the other type] is not considered to be at least as specialized
1191 // as [the first type]
1192 // Objective-C ARC adds:
1193 // - [one type] has non-trivial lifetime, [the other type] has
1194 // __unsafe_unretained lifetime, and the types are otherwise
1195 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001196 //
Richard Smithed563c22015-02-20 04:45:22 +00001197 // A is "considered to be at least as specialized" as P iff deduction
1198 // succeeds, so we model this as a deduction failure. Note that
1199 // [the first type] is P and [the other type] is A here; the standard
1200 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001201 Qualifiers ParamQuals = Param.getQualifiers();
1202 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001203 if ((ParamRef->isLValueReferenceType() &&
1204 !ArgRef->isLValueReferenceType()) ||
1205 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1206 (ParamQuals.hasNonTrivialObjCLifetime() &&
1207 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1208 ParamQuals.withoutObjCLifetime() ==
1209 ArgQuals.withoutObjCLifetime())) {
1210 Info.FirstArg = TemplateArgument(ParamIn);
1211 Info.SecondArg = TemplateArgument(ArgIn);
1212 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001213 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001215
Richard Smithed563c22015-02-20 04:45:22 +00001216 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001217 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001219 // version of P.
1220 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001221 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001222 // version of A.
1223 Arg = Arg.getUnqualifiedType();
1224 } else {
1225 // C++0x [temp.deduct.call]p4 bullet 1:
1226 // - If the original P is a reference type, the deduced A (i.e., the type
1227 // referred to by the reference) can be more cv-qualified than the
1228 // transformed A.
1229 if (TDF & TDF_ParamWithReferenceType) {
1230 Qualifiers Quals;
1231 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1232 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001233 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001234 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236
Douglas Gregor85f240c2011-01-25 17:19:08 +00001237 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1238 // C++0x [temp.deduct.type]p10:
1239 // If P and A are function types that originated from deduction when
1240 // taking the address of a function template (14.8.2.2) or when deducing
1241 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001242 // Ai are parameters of the top-level parameter-type-list of P and A,
Richard Smith32918772017-02-14 00:25:28 +00001243 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1244 // is an lvalue reference, in
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001245 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001246 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1247 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001248 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001249 TDF &= ~TDF_TopLevelParameterTypeList;
Richard Smith32918772017-02-14 00:25:28 +00001250 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1251 Param = Param->getPointeeType();
Douglas Gregor85f240c2011-01-25 17:19:08 +00001252 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001254
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001255 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001256 // A template type argument T, a template template argument TT or a
1257 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001258 // the following forms:
1259 //
1260 // T
1261 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001262 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001263 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001264 // Just skip any attempts to deduce from a placeholder type or a parameter
1265 // at a different depth.
1266 if (Arg->isPlaceholderType() ||
1267 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001268 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001269
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001270 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001271 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001272
Douglas Gregor60454822009-07-22 20:02:25 +00001273 // If the argument type is an array type, move the qualifiers up to the
1274 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001275 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001276 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001277 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001278 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001279 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001280 RecanonicalizeArg = true;
1281 }
1282 }
Mike Stump11289f42009-09-09 15:08:12 +00001283
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001284 // The argument type can not be less qualified than the parameter
1285 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001286 if (!(TDF & TDF_IgnoreQualifiers) &&
1287 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001288 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001289 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001290 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001291 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001292 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001293
Lei Liu413f3c52018-05-03 01:43:23 +00001294 // Do not match a function type with a cv-qualified type.
1295 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1296 if (Arg->isFunctionType() && Param.hasQualifiers()) {
1297 return Sema::TDK_NonDeducedMismatch;
1298 }
1299
Richard Smith87d263e2016-12-25 08:05:23 +00001300 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1301 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001302 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001303 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001304
Douglas Gregor1d684c22011-04-28 00:56:09 +00001305 // Remove any qualifiers on the parameter from the deduced type.
1306 // We checked the qualifiers for consistency above.
1307 Qualifiers DeducedQs = DeducedType.getQualifiers();
1308 Qualifiers ParamQs = Param.getQualifiers();
1309 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1310 if (ParamQs.hasObjCGCAttr())
1311 DeducedQs.removeObjCGCAttr();
1312 if (ParamQs.hasAddressSpace())
1313 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001314 if (ParamQs.hasObjCLifetime())
1315 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001316
Douglas Gregore46db902011-06-17 22:11:49 +00001317 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001318 // If template deduction would produce a lifetime qualifier on a type
1319 // that is not a lifetime type, template argument deduction fails.
1320 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1321 !DeducedType->isDependentType()) {
1322 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1323 Info.FirstArg = TemplateArgument(Param);
1324 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001325 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001326 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001327
Douglas Gregora4f2b432011-07-26 14:53:44 +00001328 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001329 // If template deduction would produce an argument type with lifetime type
1330 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001331 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001332 DeducedType->isObjCLifetimeType() &&
1333 !DeducedQs.hasObjCLifetime())
1334 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001335
Douglas Gregor1d684c22011-04-28 00:56:09 +00001336 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1337 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001338
Douglas Gregord6605db2009-07-22 21:30:48 +00001339 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001340 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001341
Richard Smith5f274382016-09-28 23:55:27 +00001342 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001343 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001344 Deduced[Index],
1345 NewDeduced);
1346 if (Result.isNull()) {
1347 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1348 Info.FirstArg = Deduced[Index];
1349 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001350 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001352
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001353 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001355 }
1356
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001357 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001358 Info.FirstArg = TemplateArgument(ParamIn);
1359 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001360
Douglas Gregorfb322d82011-01-14 05:11:40 +00001361 // If the parameter is an already-substituted template parameter
1362 // pack, do nothing: we don't know which of its arguments to look
1363 // at, so we have to wait until all of the parameter packs in this
1364 // expansion have arguments.
1365 if (isa<SubstTemplateTypeParmPackType>(Param))
1366 return Sema::TDK_Success;
1367
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001368 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001369 CanQualType CanParam = S.Context.getCanonicalType(Param);
1370 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001371 if (!(TDF & TDF_IgnoreQualifiers)) {
1372 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001373 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001374 return Sema::TDK_NonDeducedMismatch;
Richard Smithb884ed12018-07-11 23:19:41 +00001375 } else if (TDF & TDF_ArgWithReferenceType) {
1376 // C++ [temp.deduct.conv]p4:
1377 // If the original A is a reference type, A can be more cv-qualified
1378 // than the deduced A
1379 if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers()))
1380 return Sema::TDK_NonDeducedMismatch;
1381
1382 // Strip out all extra qualifiers from the argument to figure out the
1383 // type we're converting to, prior to the qualification conversion.
1384 Qualifiers Quals;
1385 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1386 Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers());
John McCall08569062010-08-28 22:14:41 +00001387 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001388 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001389 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001390 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001391
Douglas Gregor194ea692012-03-11 03:29:50 +00001392 // If the parameter type is not dependent, there is nothing to deduce.
1393 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001394 if (!(TDF & TDF_SkipNonDependent)) {
Richard Smithcd198152017-06-07 21:46:22 +00001395 bool NonDeduced =
1396 (TDF & TDF_AllowCompatibleFunctionType)
1397 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1398 : Param != Arg;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001399 if (NonDeduced) {
1400 return Sema::TDK_NonDeducedMismatch;
1401 }
1402 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001403 return Sema::TDK_Success;
1404 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001405 } else if (!Param->isDependentType()) {
1406 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1407 ArgUnqualType = CanArg.getUnqualifiedType();
Richard Smithcd198152017-06-07 21:46:22 +00001408 bool Success =
1409 (TDF & TDF_AllowCompatibleFunctionType)
1410 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1411 : ParamUnqualType == ArgUnqualType;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001412 if (Success)
1413 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001414 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001415
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001416 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001417 // Non-canonical types cannot appear here.
1418#define NON_CANONICAL_TYPE(Class, Base) \
1419 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1420#define TYPE(Class, Base)
1421#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001422
Douglas Gregor39c02722011-06-15 16:02:29 +00001423 case Type::TemplateTypeParm:
1424 case Type::SubstTemplateTypeParmPack:
1425 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001426
1427 // These types cannot be dependent, so simply check whether the types are
1428 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001429 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001430 case Type::VariableArray:
1431 case Type::Vector:
1432 case Type::FunctionNoProto:
1433 case Type::Record:
1434 case Type::Enum:
1435 case Type::ObjCObject:
1436 case Type::ObjCInterface:
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001437 case Type::ObjCObjectPointer:
Douglas Gregor194ea692012-03-11 03:29:50 +00001438 if (TDF & TDF_SkipNonDependent)
1439 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001440
Douglas Gregor194ea692012-03-11 03:29:50 +00001441 if (TDF & TDF_IgnoreQualifiers) {
1442 Param = Param.getUnqualifiedType();
1443 Arg = Arg.getUnqualifiedType();
1444 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001445
Douglas Gregor194ea692012-03-11 03:29:50 +00001446 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001447
1448 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001449 case Type::Complex:
1450 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001451 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1452 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001453 ComplexArg->getElementType(),
1454 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001455
1456 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001457
1458 // _Atomic T [extension]
1459 case Type::Atomic:
1460 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001461 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001462 cast<AtomicType>(Param)->getValueType(),
1463 AtomicArg->getValueType(),
1464 Info, Deduced, TDF);
1465
1466 return Sema::TDK_NonDeducedMismatch;
1467
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001468 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001469 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001470 QualType PointeeType;
1471 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1472 PointeeType = PointerArg->getPointeeType();
1473 } else if (const ObjCObjectPointerType *PointerArg
1474 = Arg->getAs<ObjCObjectPointerType>()) {
1475 PointeeType = PointerArg->getPointeeType();
1476 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001477 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001478 }
Mike Stump11289f42009-09-09 15:08:12 +00001479
Douglas Gregorfc516c92009-06-26 23:27:24 +00001480 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001481 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1482 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001483 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001484 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001487 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001488 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001489 const LValueReferenceType *ReferenceArg =
1490 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001491 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001492 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001493
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001494 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001495 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001496 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001497 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001498
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001499 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001500 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001501 const RValueReferenceType *ReferenceArg =
1502 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001503 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001504 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001505
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001506 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1507 cast<RValueReferenceType>(Param)->getPointeeType(),
1508 ReferenceArg->getPointeeType(),
1509 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001510 }
Mike Stump11289f42009-09-09 15:08:12 +00001511
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001512 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001513 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001514 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001515 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001516 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001517 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001518
John McCallf7332682010-08-19 00:20:19 +00001519 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001520 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1521 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1522 IncompleteArrayArg->getElementType(),
1523 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001524 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001525
1526 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001527 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001528 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001529 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001530 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001531 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001532
1533 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001534 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001535 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001536 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001537
John McCallf7332682010-08-19 00:20:19 +00001538 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001539 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1540 ConstantArrayParm->getElementType(),
1541 ConstantArrayArg->getElementType(),
1542 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001543 }
1544
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001545 // type [i]
1546 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001547 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001548 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001549 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001550
John McCallf7332682010-08-19 00:20:19 +00001551 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1552
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001553 // Check the element type of the arrays
1554 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001555 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001556 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001557 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1558 DependentArrayParm->getElementType(),
1559 ArrayArg->getElementType(),
1560 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001561 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001562
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001563 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001564 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001565 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001566 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001567 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001568
1569 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001570 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001571 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1572 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001573 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001574 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1575 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001576 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001577 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001578 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001579 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001580 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001581 if (const DependentSizedArrayType *DependentArrayArg
1582 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001583 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001584 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001585 DependentArrayArg->getSizeExpr(),
1586 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001587
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001588 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001589 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001590 }
Mike Stump11289f42009-09-09 15:08:12 +00001591
1592 // type(*)(T)
1593 // T(*)()
1594 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001595 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001596 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001597 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001598 dyn_cast<FunctionProtoType>(Arg);
1599 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001600 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001601
1602 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001603 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001604
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001605 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001606 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001607 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001608 != FunctionProtoArg->getRefQualifier() ||
1609 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001610 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001611
Anders Carlsson2128ec72009-06-08 15:19:08 +00001612 // Check return types.
Richard Smithcd198152017-06-07 21:46:22 +00001613 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1614 S, TemplateParams, FunctionProtoParam->getReturnType(),
1615 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001616 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001617
Richard Smithcd198152017-06-07 21:46:22 +00001618 // Check parameter types.
1619 if (auto Result = DeduceTemplateArguments(
1620 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1621 FunctionProtoParam->getNumParams(),
1622 FunctionProtoArg->param_type_begin(),
1623 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1624 return Result;
1625
1626 if (TDF & TDF_AllowCompatibleFunctionType)
1627 return Sema::TDK_Success;
1628
1629 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1630 // deducing through the noexcept-specifier if it's part of the canonical
1631 // type. libstdc++ relies on this.
1632 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1633 if (NonTypeTemplateParmDecl *NTTP =
1634 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1635 : nullptr) {
1636 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1637 "saw non-type template parameter with wrong depth");
1638
1639 llvm::APSInt Noexcept(1);
Richard Smitheaf11ad2018-05-03 03:58:32 +00001640 switch (FunctionProtoArg->canThrow()) {
Richard Smithcd198152017-06-07 21:46:22 +00001641 case CT_Cannot:
1642 Noexcept = 1;
1643 LLVM_FALLTHROUGH;
1644
1645 case CT_Can:
1646 // We give E in noexcept(E) the "deduced from array bound" treatment.
1647 // FIXME: Should we?
1648 return DeduceNonTypeTemplateArgument(
1649 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1650 /*ArrayBound*/true, Info, Deduced);
1651
1652 case CT_Dependent:
1653 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1654 return DeduceNonTypeTemplateArgument(
1655 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1656 // Can't deduce anything from throw(T...).
1657 break;
1658 }
1659 }
1660 // FIXME: Detect non-deduced exception specification mismatches?
Richard Smith746e35e2018-07-12 18:49:13 +00001661 //
1662 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1663 // top-level differences in noexcept-specifications.
Richard Smithcd198152017-06-07 21:46:22 +00001664
1665 return Sema::TDK_Success;
Anders Carlsson2128ec72009-06-08 15:19:08 +00001666 }
Mike Stump11289f42009-09-09 15:08:12 +00001667
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001668 case Type::InjectedClassName:
John McCalle78aac42010-03-10 03:28:59 +00001669 // Treat a template's injected-class-name as if the template
1670 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001671 Param = cast<InjectedClassNameType>(Param)
1672 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001673 assert(isa<TemplateSpecializationType>(Param) &&
1674 "injected class name is not a template specialization type");
Richard Smithcd198152017-06-07 21:46:22 +00001675 LLVM_FALLTHROUGH;
John McCalle78aac42010-03-10 03:28:59 +00001676
Douglas Gregor705c9002009-06-26 20:57:09 +00001677 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001678 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001679 // TT<T>
1680 // TT<i>
1681 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001682 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001683 const TemplateSpecializationType *SpecParam =
1684 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001685
Richard Smith9b296e32016-04-25 19:09:05 +00001686 // When Arg cannot be a derived class, we can just try to deduce template
1687 // arguments from the template-id.
1688 const RecordType *RecordT = Arg->getAs<RecordType>();
1689 if (!(TDF & TDF_DerivedClass) || !RecordT)
1690 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1691 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001692
Richard Smith9b296e32016-04-25 19:09:05 +00001693 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1694 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001695
Richard Smith9b296e32016-04-25 19:09:05 +00001696 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1697 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001698
Richard Smith9b296e32016-04-25 19:09:05 +00001699 if (Result == Sema::TDK_Success)
1700 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001701
Richard Smith9b296e32016-04-25 19:09:05 +00001702 // We cannot inspect base classes as part of deduction when the type
1703 // is incomplete, so either instantiate any templates necessary to
1704 // complete the type, or skip over it if it cannot be completed.
1705 if (!S.isCompleteType(Info.getLocation(), Arg))
1706 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001707
Richard Smith9b296e32016-04-25 19:09:05 +00001708 // C++14 [temp.deduct.call] p4b3:
1709 // If P is a class and P has the form simple-template-id, then the
1710 // transformed A can be a derived class of the deduced A. Likewise if
1711 // P is a pointer to a class of the form simple-template-id, the
1712 // transformed A can be a pointer to a derived class pointed to by the
1713 // deduced A.
1714 //
1715 // These alternatives are considered only if type deduction would
1716 // otherwise fail. If they yield more than one possible deduced A, the
1717 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001718
Faisal Vali683b0742016-05-19 02:28:21 +00001719 // Reset the incorrectly deduced argument from above.
1720 Deduced = DeducedOrig;
1721
1722 // Use data recursion to crawl through the list of base classes.
1723 // Visited contains the set of nodes we have already visited, while
1724 // ToVisit is our stack of records that we still need to visit.
1725 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1726 SmallVector<const RecordType *, 8> ToVisit;
1727 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001728 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001729 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001730 while (!ToVisit.empty()) {
1731 // Retrieve the next class in the inheritance hierarchy.
1732 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001733
Faisal Vali683b0742016-05-19 02:28:21 +00001734 // If we have already seen this type, skip it.
1735 if (!Visited.insert(NextT).second)
1736 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001737
Faisal Vali683b0742016-05-19 02:28:21 +00001738 // If this is a base class, try to perform template argument
1739 // deduction from it.
1740 if (NextT != RecordT) {
1741 TemplateDeductionInfo BaseInfo(Info.getLocation());
1742 Sema::TemplateDeductionResult BaseResult =
1743 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1744 QualType(NextT, 0), BaseInfo, Deduced);
1745
1746 // If template argument deduction for this base was successful,
1747 // note that we had some success. Otherwise, ignore any deductions
1748 // from this base class.
1749 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001750 // If we've already seen some success, then deduction fails due to
1751 // an ambiguity (temp.deduct.call p5).
1752 if (Successful)
1753 return Sema::TDK_MiscellaneousDeductionFailure;
1754
Faisal Vali683b0742016-05-19 02:28:21 +00001755 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001756 std::swap(SuccessfulDeduced, Deduced);
1757
Faisal Vali683b0742016-05-19 02:28:21 +00001758 Info.Param = BaseInfo.Param;
1759 Info.FirstArg = BaseInfo.FirstArg;
1760 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001761 }
1762
1763 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001764 }
Mike Stump11289f42009-09-09 15:08:12 +00001765
Faisal Vali683b0742016-05-19 02:28:21 +00001766 // Visit base classes
1767 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1768 for (const auto &Base : Next->bases()) {
1769 assert(Base.getType()->isRecordType() &&
1770 "Base class that isn't a record?");
1771 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1772 }
1773 }
Mike Stump11289f42009-09-09 15:08:12 +00001774
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001775 if (Successful) {
1776 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001777 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001778 }
Richard Smith9b296e32016-04-25 19:09:05 +00001779
Douglas Gregore81f3e72009-07-07 23:09:34 +00001780 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001781 }
1782
Douglas Gregor637d9982009-06-10 23:47:09 +00001783 // T type::*
1784 // T T::*
1785 // T (type::*)()
1786 // type (T::*)()
1787 // type (type::*)(T)
1788 // type (T::*)(T)
1789 // T (type::*)(T)
1790 // T (T::*)()
1791 // T (T::*)(T)
1792 case Type::MemberPointer: {
1793 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1794 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1795 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001796 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001797
David Majnemera381cda2015-11-30 20:34:28 +00001798 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1799 if (ParamPointeeType->isFunctionType())
1800 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1801 /*IsCtorOrDtor=*/false, Info.getLocation());
1802 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1803 if (ArgPointeeType->isFunctionType())
1804 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1805 /*IsCtorOrDtor=*/false, Info.getLocation());
1806
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001807 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001808 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001809 ParamPointeeType,
1810 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001811 Info, Deduced,
1812 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001813 return Result;
1814
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001815 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1816 QualType(MemPtrParam->getClass(), 0),
1817 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001818 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001819 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001820 }
1821
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001822 // (clang extension)
1823 //
Mike Stump11289f42009-09-09 15:08:12 +00001824 // type(^)(T)
1825 // T(^)()
1826 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001827 case Type::BlockPointer: {
1828 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1829 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001830
Anders Carlssona767eee2009-06-12 16:23:10 +00001831 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001832 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001833
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001834 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1835 BlockPtrParam->getPointeeType(),
1836 BlockPtrArg->getPointeeType(),
1837 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001838 }
1839
Douglas Gregor39c02722011-06-15 16:02:29 +00001840 // (clang extension)
1841 //
1842 // T __attribute__(((ext_vector_type(<integral constant>))))
1843 case Type::ExtVector: {
1844 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1845 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1846 // Make sure that the vectors have the same number of elements.
1847 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1848 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001849
Douglas Gregor39c02722011-06-15 16:02:29 +00001850 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001851 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1852 VectorParam->getElementType(),
1853 VectorArg->getElementType(),
1854 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001855 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001856
1857 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001858 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1859 // We can't check the number of elements, since the argument has a
1860 // dependent number of elements. This can only occur during partial
1861 // ordering.
1862
1863 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001864 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1865 VectorParam->getElementType(),
1866 VectorArg->getElementType(),
1867 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001868 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001869
Douglas Gregor39c02722011-06-15 16:02:29 +00001870 return Sema::TDK_NonDeducedMismatch;
1871 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001872
Erich Keanef702b022018-07-13 19:46:04 +00001873 case Type::DependentVector: {
1874 const auto *VectorParam = cast<DependentVectorType>(Param);
1875
1876 if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) {
1877 // Perform deduction on the element types.
1878 if (Sema::TemplateDeductionResult Result =
1879 DeduceTemplateArgumentsByTypeMatch(
1880 S, TemplateParams, VectorParam->getElementType(),
1881 VectorArg->getElementType(), Info, Deduced, TDF))
1882 return Result;
1883
1884 // Perform deduction on the vector size, if we can.
1885 NonTypeTemplateParmDecl *NTTP =
1886 getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1887 if (!NTTP)
1888 return Sema::TDK_Success;
1889
1890 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1891 ArgSize = VectorArg->getNumElements();
1892 // Note that we use the "array bound" rules here; just like in that
1893 // case, we don't have any particular type for the vector size, but
1894 // we can provide one if necessary.
1895 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1896 S.Context.UnsignedIntTy, true,
1897 Info, Deduced);
1898 }
1899
1900 if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) {
1901 // Perform deduction on the element types.
1902 if (Sema::TemplateDeductionResult Result =
1903 DeduceTemplateArgumentsByTypeMatch(
1904 S, TemplateParams, VectorParam->getElementType(),
1905 VectorArg->getElementType(), Info, Deduced, TDF))
1906 return Result;
1907
1908 // Perform deduction on the vector size, if we can.
1909 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1910 Info, VectorParam->getSizeExpr());
1911 if (!NTTP)
1912 return Sema::TDK_Success;
1913
1914 return DeduceNonTypeTemplateArgument(
1915 S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced);
1916 }
1917
1918 return Sema::TDK_NonDeducedMismatch;
1919 }
1920
Douglas Gregor39c02722011-06-15 16:02:29 +00001921 // (clang extension)
1922 //
1923 // T __attribute__(((ext_vector_type(N))))
1924 case Type::DependentSizedExtVector: {
1925 const DependentSizedExtVectorType *VectorParam
1926 = cast<DependentSizedExtVectorType>(Param);
1927
1928 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1929 // Perform deduction on the element types.
1930 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001931 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1932 VectorParam->getElementType(),
1933 VectorArg->getElementType(),
1934 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001935 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001936
Douglas Gregor39c02722011-06-15 16:02:29 +00001937 // Perform deduction on the vector size, if we can.
1938 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001939 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001940 if (!NTTP)
1941 return Sema::TDK_Success;
1942
1943 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1944 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001945 // Note that we use the "array bound" rules here; just like in that
1946 // case, we don't have any particular type for the vector size, but
1947 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001948 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001949 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001950 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001951 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001952
1953 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001954 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1955 // Perform deduction on the element types.
1956 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001957 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1958 VectorParam->getElementType(),
1959 VectorArg->getElementType(),
1960 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001961 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001962
Douglas Gregor39c02722011-06-15 16:02:29 +00001963 // Perform deduction on the vector size, if we can.
1964 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001965 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001966 if (!NTTP)
1967 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001968
Richard Smith5f274382016-09-28 23:55:27 +00001969 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1970 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001971 Info, Deduced);
1972 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001973
Douglas Gregor39c02722011-06-15 16:02:29 +00001974 return Sema::TDK_NonDeducedMismatch;
1975 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001976
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001977 // (clang extension)
1978 //
1979 // T __attribute__(((address_space(N))))
1980 case Type::DependentAddressSpace: {
1981 const DependentAddressSpaceType *AddressSpaceParam =
1982 cast<DependentAddressSpaceType>(Param);
1983
1984 if (const DependentAddressSpaceType *AddressSpaceArg =
1985 dyn_cast<DependentAddressSpaceType>(Arg)) {
1986 // Perform deduction on the pointer type.
1987 if (Sema::TemplateDeductionResult Result =
1988 DeduceTemplateArgumentsByTypeMatch(
1989 S, TemplateParams, AddressSpaceParam->getPointeeType(),
1990 AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
1991 return Result;
1992
1993 // Perform deduction on the address space, if we can.
1994 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1995 Info, AddressSpaceParam->getAddrSpaceExpr());
1996 if (!NTTP)
1997 return Sema::TDK_Success;
1998
1999 return DeduceNonTypeTemplateArgument(
2000 S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
2001 Deduced);
2002 }
2003
Alexander Richardson6d989432017-10-15 18:48:14 +00002004 if (isTargetAddressSpace(Arg.getAddressSpace())) {
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002005 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2006 false);
Alexander Richardson6d989432017-10-15 18:48:14 +00002007 ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002008
2009 // Perform deduction on the pointer types.
2010 if (Sema::TemplateDeductionResult Result =
2011 DeduceTemplateArgumentsByTypeMatch(
2012 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2013 S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
2014 return Result;
2015
2016 // Perform deduction on the address space, if we can.
2017 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2018 Info, AddressSpaceParam->getAddrSpaceExpr());
2019 if (!NTTP)
2020 return Sema::TDK_Success;
2021
2022 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2023 ArgAddressSpace, S.Context.IntTy,
2024 true, Info, Deduced);
2025 }
2026
2027 return Sema::TDK_NonDeducedMismatch;
2028 }
2029
Douglas Gregor637d9982009-06-10 23:47:09 +00002030 case Type::TypeOfExpr:
2031 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002032 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00002033 case Type::UnresolvedUsing:
2034 case Type::Decltype:
2035 case Type::UnaryTransform:
2036 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002037 case Type::DeducedTemplateSpecialization:
Douglas Gregor39c02722011-06-15 16:02:29 +00002038 case Type::DependentTemplateSpecialization:
2039 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002040 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00002041 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002042 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002043 }
2044
David Blaikiee4d798f2012-01-20 21:50:17 +00002045 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002046}
2047
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002048static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002049DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002050 TemplateParameterList *TemplateParams,
2051 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002052 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00002053 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002054 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002055 // If the template argument is a pack expansion, perform template argument
2056 // deduction against the pattern of that expansion. This only occurs during
2057 // partial ordering.
2058 if (Arg.isPackExpansion())
2059 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002060
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002061 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002062 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002063 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00002064
2065 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002066 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00002067 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2068 Param.getAsType(),
2069 Arg.getAsType(),
2070 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002071 Info.FirstArg = Param;
2072 Info.SecondArg = Arg;
2073 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002074
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002075 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00002076 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002078 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00002079 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002080 Info.FirstArg = Param;
2081 Info.SecondArg = Arg;
2082 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002083
2084 case TemplateArgument::TemplateExpansion:
2085 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002087 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002088 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00002089 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00002090 return Sema::TDK_Success;
2091
2092 Info.FirstArg = Param;
2093 Info.SecondArg = Arg;
2094 return Sema::TDK_NonDeducedMismatch;
2095
2096 case TemplateArgument::NullPtr:
2097 if (Arg.getKind() == TemplateArgument::NullPtr &&
2098 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002099 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002100
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002101 Info.FirstArg = Param;
2102 Info.SecondArg = Arg;
2103 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00002104
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002105 case TemplateArgument::Integral:
2106 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002107 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002108 return Sema::TDK_Success;
2109
2110 Info.FirstArg = Param;
2111 Info.SecondArg = Arg;
2112 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002113 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002114
2115 if (Arg.getKind() == TemplateArgument::Expression) {
2116 Info.FirstArg = Param;
2117 Info.SecondArg = Arg;
2118 return Sema::TDK_NonDeducedMismatch;
2119 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002120
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002121 Info.FirstArg = Param;
2122 Info.SecondArg = Arg;
2123 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00002124
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00002125 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00002126 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00002127 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002128 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00002129 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002130 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00002131 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002132 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002133 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00002134 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00002135 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2136 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00002137 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002138 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00002139 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2140 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002141 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00002142 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2143 Arg.getAsDecl(),
2144 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002145 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002146
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002147 Info.FirstArg = Param;
2148 Info.SecondArg = Arg;
2149 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002150 }
Mike Stump11289f42009-09-09 15:08:12 +00002151
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002152 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002153 return Sema::TDK_Success;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00002154
Anders Carlssonbc343912009-06-15 17:04:53 +00002155 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00002156 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002157 }
Mike Stump11289f42009-09-09 15:08:12 +00002158
David Blaikiee4d798f2012-01-20 21:50:17 +00002159 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002160}
2161
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002162/// Determine whether there is a template argument to be used for
Douglas Gregor7baabef2010-12-22 18:17:10 +00002163/// deduction.
2164///
2165/// This routine "expands" argument packs in-place, overriding its input
2166/// parameters so that \c Args[ArgIdx] will be the available template argument.
2167///
2168/// \returns true if there is another template argument (which will be at
2169/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00002170static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2171 unsigned &ArgIdx) {
2172 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00002173 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002174
Douglas Gregor7baabef2010-12-22 18:17:10 +00002175 const TemplateArgument &Arg = Args[ArgIdx];
2176 if (Arg.getKind() != TemplateArgument::Pack)
2177 return true;
2178
Richard Smith0bda5b52016-12-23 23:46:56 +00002179 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2180 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002181 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002182 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002183}
2184
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002185/// Determine whether the given set of template arguments has a pack
Douglas Gregord0ad2942010-12-23 01:24:45 +00002186/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00002187static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2188 bool FoundPackExpansion = false;
2189 for (const auto &A : Args) {
2190 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00002191 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00002192
2193 if (A.getKind() == TemplateArgument::Pack)
2194 return hasPackExpansionBeforeEnd(A.pack_elements());
2195
2196 if (A.isPackExpansion())
2197 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00002198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002199
Douglas Gregord0ad2942010-12-23 01:24:45 +00002200 return false;
2201}
2202
Douglas Gregor7baabef2010-12-22 18:17:10 +00002203static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002204DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00002205 ArrayRef<TemplateArgument> Params,
2206 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00002207 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002208 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2209 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002210 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002211 // If the template argument list of P contains a pack expansion that is not
2212 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002213 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00002214 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00002215 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002216
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002217 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002218 // If P has a form that contains <T> or <i>, then each argument Pi of the
2219 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002220 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002221 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002222 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00002223 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002224 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002225
Douglas Gregor7baabef2010-12-22 18:17:10 +00002226 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00002227 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00002228 return NumberOfArgumentsMustMatch
2229 ? Sema::TDK_MiscellaneousDeductionFailure
2230 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002231
Richard Smith26b86ea2016-12-31 21:41:23 +00002232 // C++1z [temp.deduct.type]p9:
2233 // During partial ordering, if Ai was originally a pack expansion [and]
2234 // Pi is not a pack expansion, template argument deduction fails.
2235 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00002236 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002237
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002238 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002239 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002240 = DeduceTemplateArguments(S, TemplateParams,
2241 Params[ParamIdx], Args[ArgIdx],
2242 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002243 return Result;
2244
Douglas Gregor7baabef2010-12-22 18:17:10 +00002245 // Move to the next argument.
2246 ++ArgIdx;
2247 continue;
2248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002249
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002250 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002251
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002252 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002253 // If Pi is a pack expansion, then the pattern of Pi is compared with
2254 // each remaining argument in the template argument list of A. Each
2255 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002256 // template parameter packs expanded by Pi.
2257 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002258
Richard Smith0a80d572014-05-29 01:12:14 +00002259 // Prepare to deduce the packs within the pattern.
2260 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002261
2262 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002263 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002264 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00002265 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002266 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002267 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002268 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2269 Info, Deduced))
2270 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002271
Richard Smith0a80d572014-05-29 01:12:14 +00002272 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002275 // Build argument packs for each of the parameter packs expanded by this
2276 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00002277 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002278 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00002279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280
Douglas Gregor7baabef2010-12-22 18:17:10 +00002281 return Sema::TDK_Success;
2282}
2283
Mike Stump11289f42009-09-09 15:08:12 +00002284static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002285DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002286 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002287 const TemplateArgumentList &ParamList,
2288 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002289 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002290 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002291 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00002292 ArgList.asArray(), Info, Deduced,
2293 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002294}
2295
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002296/// Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002297static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00002298 TemplateArgument X,
2299 const TemplateArgument &Y,
2300 bool PackExpansionMatchesPack = false) {
2301 // If we're checking deduced arguments (X) against original arguments (Y),
2302 // we will have flattened packs to non-expansions in X.
2303 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2304 X = X.getPackExpansionPattern();
2305
Douglas Gregor705c9002009-06-26 20:57:09 +00002306 if (X.getKind() != Y.getKind())
2307 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002308
Douglas Gregor705c9002009-06-26 20:57:09 +00002309 switch (X.getKind()) {
2310 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002311 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002312
Douglas Gregor705c9002009-06-26 20:57:09 +00002313 case TemplateArgument::Type:
2314 return Context.getCanonicalType(X.getAsType()) ==
2315 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002316
Douglas Gregor705c9002009-06-26 20:57:09 +00002317 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002318 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002319
2320 case TemplateArgument::NullPtr:
2321 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002322
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002323 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002324 case TemplateArgument::TemplateExpansion:
2325 return Context.getCanonicalTemplateName(
2326 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2327 Context.getCanonicalTemplateName(
2328 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329
Douglas Gregor705c9002009-06-26 20:57:09 +00002330 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002331 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002332
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002333 case TemplateArgument::Expression: {
2334 llvm::FoldingSetNodeID XID, YID;
2335 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002336 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002337 return XID == YID;
2338 }
Mike Stump11289f42009-09-09 15:08:12 +00002339
Douglas Gregor705c9002009-06-26 20:57:09 +00002340 case TemplateArgument::Pack:
2341 if (X.pack_size() != Y.pack_size())
2342 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002343
2344 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2345 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002346 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002347 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002348 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002349 return false;
2350
2351 return true;
2352 }
2353
David Blaikiee4d798f2012-01-20 21:50:17 +00002354 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002355}
2356
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002357/// Allocate a TemplateArgumentLoc where all locations have
Douglas Gregorca4686d2011-01-04 23:35:54 +00002358/// been initialized to the given location.
2359///
James Dennett634962f2012-06-14 21:40:34 +00002360/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002361/// location information for.
2362///
2363/// \param NTTPType For a declaration template argument, the type of
2364/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002365/// argument. Can be null if no type sugar is available to add to the
2366/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002367///
2368/// \param Loc The source location to use for the resulting template
2369/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002370TemplateArgumentLoc
2371Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2372 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002373 switch (Arg.getKind()) {
2374 case TemplateArgument::Null:
2375 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002376
Douglas Gregorca4686d2011-01-04 23:35:54 +00002377 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002378 return TemplateArgumentLoc(
2379 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002380
Douglas Gregorca4686d2011-01-04 23:35:54 +00002381 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002382 if (NTTPType.isNull())
2383 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002384 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2385 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002386 return TemplateArgumentLoc(TemplateArgument(E), E);
2387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002388
Eli Friedmanb826a002012-09-26 02:36:12 +00002389 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002390 if (NTTPType.isNull())
2391 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002392 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2393 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002394 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2395 E);
2396 }
2397
Douglas Gregorca4686d2011-01-04 23:35:54 +00002398 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002399 Expr *E =
2400 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002401 return TemplateArgumentLoc(TemplateArgument(E), E);
2402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002403
Douglas Gregor9d802122011-03-02 17:09:35 +00002404 case TemplateArgument::Template:
2405 case TemplateArgument::TemplateExpansion: {
2406 NestedNameSpecifierLocBuilder Builder;
2407 TemplateName Template = Arg.getAsTemplate();
2408 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002409 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002410 else if (QualifiedTemplateName *QTN =
2411 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002412 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002413
Douglas Gregor9d802122011-03-02 17:09:35 +00002414 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002415 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002416 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002417
2418 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002419 Loc, Loc);
2420 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002421
Douglas Gregorca4686d2011-01-04 23:35:54 +00002422 case TemplateArgument::Expression:
2423 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002424
Douglas Gregorca4686d2011-01-04 23:35:54 +00002425 case TemplateArgument::Pack:
2426 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002428
David Blaikiee4d798f2012-01-20 21:50:17 +00002429 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002430}
2431
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002432/// Convert the given deduced template argument and add it to the set of
Douglas Gregorca4686d2011-01-04 23:35:54 +00002433/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002434static bool
2435ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2436 DeducedTemplateArgument Arg,
2437 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002438 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002439 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002440 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002441 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2442 unsigned ArgumentPackIndex) {
2443 // Convert the deduced template argument into a template
2444 // argument that we can check, almost as if the user had written
2445 // the template argument explicitly.
2446 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002447 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002448
2449 // Check the template argument, converting it as necessary.
2450 return S.CheckTemplateArgument(
2451 Param, ArgLoc, Template, Template->getLocation(),
2452 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002453 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002454 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2455 : Sema::CTAK_Deduced)
2456 : Sema::CTAK_Specified);
2457 };
2458
Douglas Gregorca4686d2011-01-04 23:35:54 +00002459 if (Arg.getKind() == TemplateArgument::Pack) {
2460 // This is a template argument pack, so check each of its arguments against
2461 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002462 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002463 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002464 // When converting the deduced template argument, append it to the
2465 // general output list. We need to do this so that the template argument
2466 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002467 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002468 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002469 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2470 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002471 if (P.isNull()) {
2472 // We deduced arguments for some elements of this pack, but not for
2473 // all of them. This happens if we get a conditionally-non-deduced
2474 // context in a pack expansion (such as an overload set in one of the
2475 // arguments).
2476 S.Diag(Param->getLocation(),
2477 diag::err_template_arg_deduced_incomplete_pack)
2478 << Arg << Param;
2479 return true;
2480 }
Richard Smith37acb792016-02-03 20:15:01 +00002481 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002482 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002483
Douglas Gregor51bc5712011-01-05 20:52:18 +00002484 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002485 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002486 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002487
Richard Smithdf18ee92016-02-03 20:40:30 +00002488 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002489 // itself, in case that substitution fails.
2490 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002491 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002492 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002493 MultiLevelTemplateArgumentList Args(TemplateArgs);
2494
2495 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2496 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2497 NTTP, Output,
2498 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002499 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002500 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2501 NTTP->getDeclName()).isNull())
2502 return true;
2503 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2504 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2505 TTP, Output,
2506 Template->getSourceRange());
2507 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2508 return true;
2509 }
2510 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002511 }
Richard Smith37acb792016-02-03 20:15:01 +00002512
Douglas Gregorca4686d2011-01-04 23:35:54 +00002513 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002514 Output.push_back(
2515 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002516 return false;
2517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002518
Richard Smith37acb792016-02-03 20:15:01 +00002519 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002520}
2521
Richard Smith1f5be4d2016-12-21 01:10:31 +00002522// FIXME: This should not be a template, but
2523// ClassTemplatePartialSpecializationDecl sadly does not derive from
2524// TemplateDecl.
2525template<typename TemplateDeclT>
2526static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002527 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002528 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2529 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2530 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
Richard Smithf0393bf2017-02-16 04:22:56 +00002531 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002532 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2533
2534 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2535 NamedDecl *Param = TemplateParams->getParam(I);
2536
2537 if (!Deduced[I].isNull()) {
2538 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002539 // We may have had explicitly-specified template arguments for a
2540 // template parameter pack (that may or may not have been extended
2541 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002542 if (Param->isParameterPack() && CurrentInstantiationScope &&
2543 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2544 // Forget the partially-substituted pack; its substitution is now
2545 // complete.
2546 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2547 // We still need to check the argument in case it was extended by
2548 // deduction.
2549 } else {
2550 // We have already fully type-checked and converted this
2551 // argument, because it was explicitly-specified. Just record the
2552 // presence of this argument.
2553 Builder.push_back(Deduced[I]);
2554 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002555 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002556 }
2557
Richard Smith9c0c9862017-01-05 20:27:28 +00002558 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002559 // checked and converted.
2560 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002561 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002562 Info.Param = makeTemplateParameter(Param);
2563 // FIXME: These template arguments are temporary. Free them!
2564 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2565 return Sema::TDK_SubstitutionFailure;
2566 }
2567
2568 continue;
2569 }
2570
2571 // C++0x [temp.arg.explicit]p3:
2572 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2573 // be deduced to an empty sequence of template arguments.
2574 // FIXME: Where did the word "trailing" come from?
2575 if (Param->isTemplateParameterPack()) {
2576 // We may have had explicitly-specified template arguments for this
2577 // template parameter pack. If so, our empty deduction extends the
2578 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2579 const TemplateArgument *ExplicitArgs;
2580 unsigned NumExplicitArgs;
2581 if (CurrentInstantiationScope &&
2582 CurrentInstantiationScope->getPartiallySubstitutedPack(
2583 &ExplicitArgs, &NumExplicitArgs) == Param) {
2584 Builder.push_back(TemplateArgument(
2585 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2586
2587 // Forget the partially-substituted pack; its substitution is now
2588 // complete.
2589 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2590 } else {
2591 // Go through the motions of checking the empty argument pack against
2592 // the parameter pack.
2593 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002594 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2595 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002596 Info.Param = makeTemplateParameter(Param);
2597 // FIXME: These template arguments are temporary. Free them!
2598 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2599 return Sema::TDK_SubstitutionFailure;
2600 }
2601 }
2602 continue;
2603 }
2604
2605 // Substitute into the default template argument, if available.
2606 bool HasDefaultArg = false;
2607 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2608 if (!TD) {
Richard Smithf8ba3fd2017-06-02 22:53:06 +00002609 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2610 isa<VarTemplatePartialSpecializationDecl>(Template));
Richard Smith1f5be4d2016-12-21 01:10:31 +00002611 return Sema::TDK_Incomplete;
2612 }
2613
2614 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2615 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2616 HasDefaultArg);
2617
2618 // If there was no default argument, deduction is incomplete.
2619 if (DefArg.getArgument().isNull()) {
2620 Info.Param = makeTemplateParameter(
2621 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2622 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Richard Smithf0393bf2017-02-16 04:22:56 +00002623 if (PartialOverloading) break;
2624
Richard Smith1f5be4d2016-12-21 01:10:31 +00002625 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2626 : Sema::TDK_Incomplete;
2627 }
2628
2629 // Check whether we can actually use the default argument.
2630 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2631 TD->getSourceRange().getEnd(), 0, Builder,
2632 Sema::CTAK_Specified)) {
2633 Info.Param = makeTemplateParameter(
2634 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2635 // FIXME: These template arguments are temporary. Free them!
2636 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2637 return Sema::TDK_SubstitutionFailure;
2638 }
2639
2640 // If we get here, we successfully used the default template argument.
2641 }
2642
2643 return Sema::TDK_Success;
2644}
2645
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002646static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
Richard Smith0da6dc42016-12-24 16:40:51 +00002647 if (auto *DC = dyn_cast<DeclContext>(D))
2648 return DC;
2649 return D->getDeclContext();
2650}
2651
2652template<typename T> struct IsPartialSpecialization {
2653 static constexpr bool value = false;
2654};
2655template<>
2656struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2657 static constexpr bool value = true;
2658};
2659template<>
2660struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2661 static constexpr bool value = true;
2662};
2663
2664/// Complete template argument deduction for a partial specialization.
2665template <typename T>
2666static typename std::enable_if<IsPartialSpecialization<T>::value,
2667 Sema::TemplateDeductionResult>::type
2668FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002669 Sema &S, T *Partial, bool IsPartialOrdering,
2670 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002671 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2672 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002673 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002674 EnterExpressionEvaluationContext Unevaluated(
2675 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002676 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677
Richard Smith0da6dc42016-12-24 16:40:51 +00002678 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002679
2680 // C++ [temp.deduct.type]p2:
2681 // [...] or if any template argument remains neither deduced nor
2682 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002683 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002684 if (auto Result = ConvertDeducedTemplateArguments(
2685 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002686 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002687
Douglas Gregor684268d2010-04-29 06:21:43 +00002688 // Form the template argument list from the deduced template arguments.
2689 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002690 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002691
Douglas Gregor684268d2010-04-29 06:21:43 +00002692 Info.reset(DeducedArgumentList);
2693
2694 // Substitute the deduced template arguments into the template
2695 // arguments of the class template partial specialization, and
2696 // verify that the instantiated template arguments are both valid
2697 // and are equivalent to the template arguments originally provided
2698 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002699 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002700 auto *Template = Partial->getSpecializedTemplate();
2701 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2702 Partial->getTemplateArgsAsWritten();
2703 const TemplateArgumentLoc *PartialTemplateArgs =
2704 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002705
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002706 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2707 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002708
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002709 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002710 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2711 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2712 if (ParamIdx >= Partial->getTemplateParameters()->size())
2713 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2714
Richard Smith0da6dc42016-12-24 16:40:51 +00002715 Decl *Param = const_cast<NamedDecl *>(
2716 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002717 Info.Param = makeTemplateParameter(Param);
2718 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2719 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002720 }
2721
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002722 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002723 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2724 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002725 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002726
Richard Smith0da6dc42016-12-24 16:40:51 +00002727 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002728 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002729 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002730 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002731 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002732 Info.FirstArg = TemplateArgs[I];
2733 Info.SecondArg = InstArg;
2734 return Sema::TDK_NonDeducedMismatch;
2735 }
2736 }
2737
2738 if (Trap.hasErrorOccurred())
2739 return Sema::TDK_SubstitutionFailure;
2740
2741 return Sema::TDK_Success;
2742}
2743
Richard Smith0e617ec2016-12-27 07:56:27 +00002744/// Complete template argument deduction for a class or variable template,
2745/// when partial ordering against a partial specialization.
2746// FIXME: Factor out duplication with partial specialization version above.
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002747static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
Richard Smith0e617ec2016-12-27 07:56:27 +00002748 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2749 const TemplateArgumentList &TemplateArgs,
2750 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2751 TemplateDeductionInfo &Info) {
2752 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002753 EnterExpressionEvaluationContext Unevaluated(
2754 S, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith0e617ec2016-12-27 07:56:27 +00002755 Sema::SFINAETrap Trap(S);
2756
2757 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2758
2759 // C++ [temp.deduct.type]p2:
2760 // [...] or if any template argument remains neither deduced nor
2761 // explicitly specified, template argument deduction fails.
2762 SmallVector<TemplateArgument, 4> Builder;
2763 if (auto Result = ConvertDeducedTemplateArguments(
2764 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2765 return Result;
2766
2767 // Check that we produced the correct argument list.
2768 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2769 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2770 TemplateArgument InstArg = Builder[I];
2771 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2772 /*PackExpansionMatchesPack*/true)) {
2773 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2774 Info.FirstArg = TemplateArgs[I];
2775 Info.SecondArg = InstArg;
2776 return Sema::TDK_NonDeducedMismatch;
2777 }
2778 }
2779
2780 if (Trap.hasErrorOccurred())
2781 return Sema::TDK_SubstitutionFailure;
2782
2783 return Sema::TDK_Success;
2784}
2785
2786
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002787/// Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002788/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002789/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002790Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002791Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002792 const TemplateArgumentList &TemplateArgs,
2793 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002794 if (Partial->isInvalidDecl())
2795 return TDK_Invalid;
2796
Douglas Gregor170bc422009-06-12 22:31:52 +00002797 // C++ [temp.class.spec.match]p2:
2798 // A partial specialization matches a given actual template
2799 // argument list if the template arguments of the partial
2800 // specialization can be deduced from the actual template argument
2801 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002802
2803 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002804 EnterExpressionEvaluationContext Unevaluated(
2805 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002806 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002807
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002808 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002809 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002810 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002811 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002812 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002813 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002814 TemplateArgs, Info, Deduced))
2815 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002816
Richard Smith80934652012-07-16 01:09:10 +00002817 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002818 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2819 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002820 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002821 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002822
Douglas Gregore1416332009-06-14 08:02:22 +00002823 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002824 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002825
Richard Smith87d263e2016-12-25 08:05:23 +00002826 return ::FinishTemplateArgumentDeduction(
2827 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002828}
Douglas Gregor91772d12009-06-13 00:26:55 +00002829
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002830/// Perform template argument deduction to determine whether
Larisse Voufo39a1e502013-08-06 01:03:05 +00002831/// the given template arguments match the given variable template
2832/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002833Sema::TemplateDeductionResult
2834Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2835 const TemplateArgumentList &TemplateArgs,
2836 TemplateDeductionInfo &Info) {
2837 if (Partial->isInvalidDecl())
2838 return TDK_Invalid;
2839
2840 // C++ [temp.class.spec.match]p2:
2841 // A partial specialization matches a given actual template
2842 // argument list if the template arguments of the partial
2843 // specialization can be deduced from the actual template argument
2844 // list (14.8.2).
2845
2846 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002847 EnterExpressionEvaluationContext Unevaluated(
2848 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002849 SFINAETrap Trap(*this);
2850
2851 SmallVector<DeducedTemplateArgument, 4> Deduced;
2852 Deduced.resize(Partial->getTemplateParameters()->size());
2853 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2854 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2855 TemplateArgs, Info, Deduced))
2856 return Result;
2857
2858 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002859 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2860 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002861 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002862 return TDK_InstantiationDepth;
2863
2864 if (Trap.hasErrorOccurred())
2865 return Sema::TDK_SubstitutionFailure;
2866
Richard Smith87d263e2016-12-25 08:05:23 +00002867 return ::FinishTemplateArgumentDeduction(
2868 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002869}
2870
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002871/// Determine whether the given type T is a simple-template-id type.
Douglas Gregorfc516c92009-06-26 23:27:24 +00002872static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002873 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002874 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002875 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002876
Richard Smith1363e8f2017-09-07 07:22:36 +00002877 // C++17 [temp.local]p2:
2878 // the injected-class-name [...] is equivalent to the template-name followed
2879 // by the template-arguments of the class template specialization or partial
2880 // specialization enclosed in <>
2881 // ... which means it's equivalent to a simple-template-id.
2882 //
2883 // This only arises during class template argument deduction for a copy
2884 // deduction candidate, where it permits slicing.
2885 if (T->getAs<InjectedClassNameType>())
2886 return true;
2887
Douglas Gregorfc516c92009-06-26 23:27:24 +00002888 return false;
2889}
Douglas Gregor9b146582009-07-08 20:55:45 +00002890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002891/// Substitute the explicitly-provided template arguments into the
Douglas Gregor9b146582009-07-08 20:55:45 +00002892/// given function template according to C++ [temp.arg.explicit].
2893///
2894/// \param FunctionTemplate the function template into which the explicit
2895/// template arguments will be substituted.
2896///
James Dennett634962f2012-06-14 21:40:34 +00002897/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002898/// arguments.
2899///
Mike Stump11289f42009-09-09 15:08:12 +00002900/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002901/// with the converted and checked explicit template arguments.
2902///
Mike Stump11289f42009-09-09 15:08:12 +00002903/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002904/// parameters.
2905///
2906/// \param FunctionType if non-NULL, the result type of the function template
2907/// will also be instantiated and the pointed-to value will be updated with
2908/// the instantiated function type.
2909///
2910/// \param Info if substitution fails for any reason, this object will be
2911/// populated with more information about the failure.
2912///
2913/// \returns TDK_Success if substitution was successful, or some failure
2914/// condition.
2915Sema::TemplateDeductionResult
2916Sema::SubstituteExplicitTemplateArguments(
2917 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002918 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002919 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2920 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002921 QualType *FunctionType,
2922 TemplateDeductionInfo &Info) {
2923 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2924 TemplateParameterList *TemplateParams
2925 = FunctionTemplate->getTemplateParameters();
2926
John McCall6b51f282009-11-23 01:53:49 +00002927 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002928 // No arguments to substitute; just copy over the parameter types and
2929 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002930 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002931 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002932
Douglas Gregor9b146582009-07-08 20:55:45 +00002933 if (FunctionType)
2934 *FunctionType = Function->getType();
2935 return TDK_Success;
2936 }
Mike Stump11289f42009-09-09 15:08:12 +00002937
Eli Friedman77dcc722012-02-08 03:07:05 +00002938 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002939 EnterExpressionEvaluationContext Unevaluated(
2940 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002941 SFINAETrap Trap(*this);
2942
Douglas Gregor9b146582009-07-08 20:55:45 +00002943 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002944 // Template arguments that are present shall be specified in the
2945 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002946 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002947 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002948 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002949
2950 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002951 // explicitly-specified template arguments against this function template,
2952 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00002953 SmallVector<TemplateArgument, 4> DeducedArgs;
Richard Smith696e3122017-02-23 01:43:54 +00002954 InstantiatingTemplate Inst(
2955 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
2956 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002957 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002958 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002959
Richard Smith11255ec2017-01-18 19:19:22 +00002960 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
2961 ExplicitTemplateArgs, true, Builder, false) ||
2962 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002963 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002964 if (Index >= TemplateParams->size())
2965 Index = TemplateParams->size() - 1;
2966 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002967 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002968 }
Mike Stump11289f42009-09-09 15:08:12 +00002969
Douglas Gregor9b146582009-07-08 20:55:45 +00002970 // Form the template argument list from the explicitly-specified
2971 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002972 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002973 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002974 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002975
John McCall036855a2010-10-12 19:40:14 +00002976 // Template argument deduction and the final substitution should be
2977 // done in the context of the templated declaration. Explicit
2978 // argument substitution, on the other hand, needs to happen in the
2979 // calling context.
2980 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2981
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002982 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002983 // note that the template argument pack is partially substituted and record
2984 // the explicit template arguments. They'll be used as part of deduction
2985 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002986 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2987 const TemplateArgument &Arg = Builder[I];
2988 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002989 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002990 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002991 Arg.pack_begin(),
2992 Arg.pack_size());
2993 break;
2994 }
2995 }
2996
Richard Smith5e580292012-02-10 09:58:53 +00002997 const FunctionProtoType *Proto
2998 = Function->getType()->getAs<FunctionProtoType>();
2999 assert(Proto && "Function template does not have a prototype?");
3000
Richard Smith70b13042015-01-09 01:19:56 +00003001 // Isolate our substituted parameters from our caller.
3002 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3003
John McCallc8e321d2016-03-01 02:09:25 +00003004 ExtParameterInfoBuilder ExtParamInfos;
3005
Douglas Gregor9b146582009-07-08 20:55:45 +00003006 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00003007 // explicitly-specified template arguments. If the function has a trailing
3008 // return type, substitute it after the arguments to ensure we substitute
3009 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00003010 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00003011 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00003012 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00003013 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00003014 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00003015 return TDK_SubstitutionFailure;
3016 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003017
Richard Smith5e580292012-02-10 09:58:53 +00003018 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00003019 QualType ResultType;
3020 {
3021 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00003022 // If a declaration declares a member function or member function
3023 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00003024 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00003025 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00003026 // declarator.
3027 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00003028 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00003029 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3030 ThisContext = Method->getParent();
3031 ThisTypeQuals = Method->getTypeQualifiers();
3032 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003033
Douglas Gregor3024f072012-04-16 07:05:22 +00003034 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003035 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00003036
3037 ResultType =
3038 SubstType(Proto->getReturnType(),
3039 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3040 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00003041 if (ResultType.isNull() || Trap.hasErrorOccurred())
3042 return TDK_SubstitutionFailure;
3043 }
John McCallc8e321d2016-03-01 02:09:25 +00003044
Richard Smith5e580292012-02-10 09:58:53 +00003045 // Instantiate the types of each of the function parameters given the
3046 // explicitly-specified template arguments if we didn't do so earlier.
3047 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00003048 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00003049 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00003050 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00003051 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00003052 return TDK_SubstitutionFailure;
3053
Douglas Gregor9b146582009-07-08 20:55:45 +00003054 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00003055 auto EPI = Proto->getExtProtoInfo();
3056 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Richard Smithcd198152017-06-07 21:46:22 +00003057
3058 // In C++1z onwards, exception specifications are part of the function type,
3059 // so substitution into the type must also substitute into the exception
3060 // specification.
3061 SmallVector<QualType, 4> ExceptionStorage;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003062 if (getLangOpts().CPlusPlus17 &&
Richard Smithcd198152017-06-07 21:46:22 +00003063 SubstExceptionSpec(
3064 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
3065 MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
3066 return TDK_SubstitutionFailure;
3067
Jordan Rose5c382722013-03-08 21:51:21 +00003068 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003069 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00003070 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00003071 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00003072 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3073 return TDK_SubstitutionFailure;
3074 }
Mike Stump11289f42009-09-09 15:08:12 +00003075
Douglas Gregor9b146582009-07-08 20:55:45 +00003076 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003077 // Trailing template arguments that can be deduced (14.8.2) may be
3078 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00003079 // template arguments can be deduced, they may all be omitted; in this
3080 // case, the empty template argument list <> itself may also be omitted.
3081 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003082 // Take all of the explicitly-specified arguments and put them into
3083 // the set of deduced template arguments. Explicitly-specified
3084 // parameter packs, however, will be set to NULL since the deduction
3085 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00003086 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003087 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
3088 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
3089 if (Arg.getKind() == TemplateArgument::Pack)
3090 Deduced.push_back(DeducedTemplateArgument());
3091 else
3092 Deduced.push_back(Arg);
3093 }
Mike Stump11289f42009-09-09 15:08:12 +00003094
Douglas Gregor9b146582009-07-08 20:55:45 +00003095 return TDK_Success;
3096}
3097
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003098/// Check whether the deduced argument type for a call to a function
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003099/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Richard Smithb1efc9b2017-08-30 00:44:08 +00003100static Sema::TemplateDeductionResult
3101CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3102 Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003103 QualType DeducedA) {
3104 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003105
Richard Smithb1efc9b2017-08-30 00:44:08 +00003106 auto Failed = [&]() -> Sema::TemplateDeductionResult {
3107 Info.FirstArg = TemplateArgument(DeducedA);
3108 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3109 Info.CallArgIndex = OriginalArg.ArgIdx;
3110 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
3111 : Sema::TDK_DeducedMismatch;
3112 };
3113
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003114 QualType A = OriginalArg.OriginalArgType;
3115 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003116
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003117 // Check for type equality (top-level cv-qualifiers are ignored).
3118 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003119 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003120
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003121 // Strip off references on the argument types; they aren't needed for
3122 // the following checks.
3123 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3124 DeducedA = DeducedARef->getPointeeType();
3125 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3126 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003127
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003128 // C++ [temp.deduct.call]p4:
3129 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00003130 // - If the original P is a reference type, the deduced A (i.e., the
3131 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003132 // the transformed A.
3133 if (const ReferenceType *OriginalParamRef
3134 = OriginalParamType->getAs<ReferenceType>()) {
3135 // We don't want to keep the reference around any more.
3136 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003137
Richard Smith1be59c52016-10-22 01:32:19 +00003138 // FIXME: Resolve core issue (no number yet): if the original P is a
3139 // reference type and the transformed A is function type "noexcept F",
3140 // the deduced A can be F.
3141 QualType Tmp;
3142 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003143 return Sema::TDK_Success;
Richard Smith1be59c52016-10-22 01:32:19 +00003144
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003145 Qualifiers AQuals = A.getQualifiers();
3146 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00003147
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003148 // Under Objective-C++ ARC, the deduced type may have implicitly
3149 // been given strong or (when dealing with a const reference)
3150 // unsafe_unretained lifetime. If so, update the original
3151 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00003152 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003153 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3154 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3155 (DeducedAQuals.hasConst() &&
3156 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3157 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00003158 }
3159
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003160 if (AQuals == DeducedAQuals) {
3161 // Qualifiers match; there's nothing to do.
3162 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00003163 return Failed();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003164 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003165 // Qualifiers are compatible, so have the argument type adopt the
3166 // deduced argument type's qualifiers as if we had performed the
3167 // qualification conversion.
3168 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3169 }
3170 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003171
3172 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00003173 // type that can be converted to the deduced A via a function pointer
3174 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00003175 //
Richard Smith1be59c52016-10-22 01:32:19 +00003176 // Also allow conversions which merely strip __attribute__((noreturn)) from
3177 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003178 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00003179 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003180 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00003181 (S.IsQualificationConversion(A, DeducedA, false,
3182 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00003183 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003184 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003185
Simon Pilgrim728134c2016-08-12 11:43:57 +00003186 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003187 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003188 // [...] Likewise, if P is a pointer to a class of the form
3189 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003190 // derived class pointed to by the deduced A.
3191 if (const PointerType *OriginalParamPtr
3192 = OriginalParamType->getAs<PointerType>()) {
3193 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3194 if (const PointerType *APtr = A->getAs<PointerType>()) {
3195 if (A->getPointeeType()->isRecordType()) {
3196 OriginalParamType = OriginalParamPtr->getPointeeType();
3197 DeducedA = DeducedAPtr->getPointeeType();
3198 A = APtr->getPointeeType();
3199 }
3200 }
3201 }
3202 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003203
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003204 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003205 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003206
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003207 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith148bc6a2018-02-20 23:47:12 +00003208 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003209 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003210
Richard Smithb1efc9b2017-08-30 00:44:08 +00003211 return Failed();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003212}
3213
Richard Smithc92d2062017-01-05 23:02:44 +00003214/// Find the pack index for a particular parameter index in an instantiation of
3215/// a function template with specific arguments.
3216///
3217/// \return The pack index for whichever pack produced this parameter, or -1
3218/// if this was not produced by a parameter. Intended to be used as the
3219/// ArgumentPackSubstitutionIndex for further substitutions.
3220// FIXME: We should track this in OriginalCallArgs so we don't need to
3221// reconstruct it here.
3222static unsigned getPackIndexForParam(Sema &S,
3223 FunctionTemplateDecl *FunctionTemplate,
3224 const MultiLevelTemplateArgumentList &Args,
3225 unsigned ParamIdx) {
3226 unsigned Idx = 0;
3227 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3228 if (PD->isParameterPack()) {
3229 unsigned NumExpansions =
3230 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3231 if (Idx + NumExpansions > ParamIdx)
3232 return ParamIdx - Idx;
3233 Idx += NumExpansions;
3234 } else {
3235 if (Idx == ParamIdx)
3236 return -1; // Not a pack expansion
3237 ++Idx;
3238 }
3239 }
3240
3241 llvm_unreachable("parameter index would not be produced from template");
3242}
3243
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003244/// Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003245/// checking the deduced template arguments for completeness and forming
3246/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00003247///
3248/// \param OriginalCallArgs If non-NULL, the original call arguments against
3249/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00003250Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3251 FunctionTemplateDecl *FunctionTemplate,
3252 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3253 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3254 TemplateDeductionInfo &Info,
3255 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3256 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00003257 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003258 EnterExpressionEvaluationContext Unevaluated(
3259 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003260 SFINAETrap Trap(*this);
3261
Douglas Gregor9b146582009-07-08 20:55:45 +00003262 // Enter a new template instantiation context while we instantiate the
3263 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00003264 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Richard Smith696e3122017-02-23 01:43:54 +00003265 InstantiatingTemplate Inst(
3266 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3267 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003268 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00003269 return TDK_InstantiationDepth;
3270
John McCalle23b8712010-04-29 01:18:58 +00003271 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00003272
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003273 // C++ [temp.deduct.type]p2:
3274 // [...] or if any template argument remains neither deduced nor
3275 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003276 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00003277 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00003278 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00003279 CurrentInstantiationScope, NumExplicitlySpecified,
3280 PartialOverloading))
3281 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003282
Richard Smith6eedfe72017-01-09 08:01:21 +00003283 // C++ [temp.deduct.call]p10: [DR1391]
3284 // If deduction succeeds for all parameters that contain
3285 // template-parameters that participate in template argument deduction,
3286 // and all template arguments are explicitly specified, deduced, or
3287 // obtained from default template arguments, remaining parameters are then
3288 // compared with the corresponding arguments. For each remaining parameter
3289 // P with a type that was non-dependent before substitution of any
3290 // explicitly-specified template arguments, if the corresponding argument
3291 // A cannot be implicitly converted to P, deduction fails.
3292 if (CheckNonDependent())
3293 return TDK_NonDependentConversionFailure;
3294
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003295 // Form the template argument list from the deduced template arguments.
3296 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00003297 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003298 Info.reset(DeducedArgumentList);
3299
Mike Stump11289f42009-09-09 15:08:12 +00003300 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003301 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00003302 DeclContext *Owner = FunctionTemplate->getDeclContext();
3303 if (FunctionTemplate->getFriendObjectKind())
3304 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00003305 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00003306 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00003307 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003308 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00003309 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00003310
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003311 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00003312 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003313
Mike Stump11289f42009-09-09 15:08:12 +00003314 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003315 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00003316 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3317 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00003318 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00003319
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003320 // There may have been an error that did not prevent us from constructing a
3321 // declaration. Mark the declaration invalid and return with a substitution
3322 // failure.
3323 if (Trap.hasErrorOccurred()) {
3324 Specialization->setInvalidDecl(true);
3325 return TDK_SubstitutionFailure;
3326 }
3327
Douglas Gregore65aacb2011-06-16 16:50:48 +00003328 if (OriginalCallArgs) {
3329 // C++ [temp.deduct.call]p4:
3330 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00003331 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00003332 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00003333 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003334 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3335 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003336
Richard Smithc92d2062017-01-05 23:02:44 +00003337 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003338 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003339 // FIXME: This presumably means a pack ended up smaller than we
3340 // expected while deducing. Should this not result in deduction
3341 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003342 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003343
Richard Smithc92d2062017-01-05 23:02:44 +00003344 QualType DeducedA;
3345 if (!OriginalArg.DecomposedParam) {
3346 // P is one of the function parameters, just look up its substituted
3347 // type.
3348 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3349 } else {
3350 // P is a decomposed element of a parameter corresponding to a
3351 // braced-init-list argument. Substitute back into P to find the
3352 // deduced A.
3353 QualType &CacheEntry =
3354 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3355 if (CacheEntry.isNull()) {
3356 ArgumentPackSubstitutionIndexRAII PackIndex(
3357 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3358 ParamIdx));
3359 CacheEntry =
3360 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3361 Specialization->getTypeSpecStartLoc(),
3362 Specialization->getDeclName());
3363 }
3364 DeducedA = CacheEntry;
3365 }
3366
Richard Smithb1efc9b2017-08-30 00:44:08 +00003367 if (auto TDK =
3368 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3369 return TDK;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003370 }
3371 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003372
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003373 // If we suppressed any diagnostics while performing template argument
3374 // deduction, and if we haven't already instantiated this declaration,
3375 // keep track of these diagnostics. They'll be emitted if this specialization
3376 // is actually used.
3377 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003378 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003379 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3380 if (Pos == SuppressedDiagnostics.end())
3381 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3382 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003383 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003384
Mike Stump11289f42009-09-09 15:08:12 +00003385 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003386}
3387
John McCall8d08b9b2010-08-27 09:08:28 +00003388/// Gets the type of a function for template-argument-deducton
3389/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003390static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003391 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003392 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003393 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003394 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003395 return {};
Richard Smith2a7d4812013-05-04 07:00:32 +00003396
John McCallc1f69982010-02-02 02:21:27 +00003397 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003398 if (Method->isInstance()) {
3399 // An instance method that's referenced in a form that doesn't
3400 // look like a member pointer is just invalid.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003401 if (!R.HasFormOfMemberPointer)
3402 return {};
John McCall8d08b9b2010-08-27 09:08:28 +00003403
Richard Smith2a7d4812013-05-04 07:00:32 +00003404 return S.Context.getMemberPointerType(Fn->getType(),
3405 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003406 }
3407
3408 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003409 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003410}
3411
3412/// Apply the deduction rules for overload sets.
3413///
3414/// \return the null type if this argument should be treated as an
3415/// undeduced context
3416static QualType
3417ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003418 Expr *Arg, QualType ParamType,
3419 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
John McCall8d08b9b2010-08-27 09:08:28 +00003421 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003422
John McCall8d08b9b2010-08-27 09:08:28 +00003423 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003424
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003425 // C++0x [temp.deduct.call]p4
3426 unsigned TDF = 0;
3427 if (ParamWasReference)
3428 TDF |= TDF_ParamWithReferenceType;
3429 if (R.IsAddressOfOperand)
3430 TDF |= TDF_IgnoreQualifiers;
3431
John McCallc1f69982010-02-02 02:21:27 +00003432 // C++0x [temp.deduct.call]p6:
3433 // When P is a function type, pointer to function type, or pointer
3434 // to member function type:
3435
3436 if (!ParamType->isFunctionType() &&
3437 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003438 !ParamType->isMemberFunctionPointerType()) {
3439 if (Ovl->hasExplicitTemplateArgs()) {
3440 // But we can still look for an explicit specialization.
3441 if (FunctionDecl *ExplicitSpec
3442 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003443 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003444 }
John McCallc1f69982010-02-02 02:21:27 +00003445
George Burgess IVcc2f3552016-03-19 21:51:45 +00003446 DeclAccessPair DAP;
3447 if (FunctionDecl *Viable =
3448 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3449 return GetTypeOfFunction(S, R, Viable);
3450
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003451 return {};
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003452 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003453
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003454 // Gather the explicit template arguments, if any.
3455 TemplateArgumentListInfo ExplicitTemplateArgs;
3456 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003457 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003458 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003459 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3460 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003461 NamedDecl *D = (*I)->getUnderlyingDecl();
3462
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003463 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3464 // - If the argument is an overload set containing one or more
3465 // function templates, the parameter is treated as a
3466 // non-deduced context.
3467 if (!Ovl->hasExplicitTemplateArgs())
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003468 return {};
Simon Pilgrim728134c2016-08-12 11:43:57 +00003469
3470 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003471 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003472 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003473 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3474 Specialization, Info))
3475 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003476
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003477 D = Specialization;
3478 }
John McCallc1f69982010-02-02 02:21:27 +00003479
3480 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003481 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003482 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003483
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003484 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003485 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003486 ArgType->isFunctionType())
3487 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488
John McCallc1f69982010-02-02 02:21:27 +00003489 // - If the argument is an overload set (not containing function
3490 // templates), trial argument deduction is attempted using each
3491 // of the members of the set. If deduction succeeds for only one
3492 // of the overload set members, that member is used as the
3493 // argument value for the deduction. If deduction succeeds for
3494 // more than one member of the overload set the parameter is
3495 // treated as a non-deduced context.
3496
3497 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3498 // Type deduction is done independently for each P/A pair, and
3499 // the deduced template argument values are then combined.
3500 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003501 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003502 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003503 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003504 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003505 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3506 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003507 if (Result) continue;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003508 if (!Match.isNull())
3509 return {};
John McCallc1f69982010-02-02 02:21:27 +00003510 Match = ArgType;
3511 }
3512
3513 return Match;
3514}
3515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003516/// Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003517/// described in C++ [temp.deduct.call].
3518///
3519/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003520/// argument deduction based on this P/A pair because the argument is an
3521/// overloaded function set that could not be resolved.
Richard Smith32918772017-02-14 00:25:28 +00003522static bool AdjustFunctionParmAndArgTypesForDeduction(
3523 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3524 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003525 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003526 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003527 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003528 if (ParamType.hasQualifiers())
3529 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003530
3531 // [...] If P is a reference type, the type referred to by P is
3532 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003533 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003534 if (ParamRefType)
3535 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003536
Nathan Sidwell96090022015-01-16 15:20:14 +00003537 // Overload sets usually make this parameter an undeduced context,
3538 // but there are sometimes special circumstances. Typically
3539 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003540 if (ArgType == S.Context.OverloadTy) {
3541 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3542 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003543 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003544 if (ArgType.isNull())
3545 return true;
3546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003547
Douglas Gregor7825bf32011-01-06 22:09:01 +00003548 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003549 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003550 if (ArgType->isIncompleteArrayType()) {
3551 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003552 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003553 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003554
Richard Smith32918772017-02-14 00:25:28 +00003555 // C++1z [temp.deduct.call]p3:
3556 // If P is a forwarding reference and the argument is an lvalue, the type
3557 // "lvalue reference to A" is used in place of A for type deduction.
3558 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003559 Arg->isLValue())
3560 ArgType = S.Context.getLValueReferenceType(ArgType);
3561 } else {
3562 // C++ [temp.deduct.call]p2:
3563 // If P is not a reference type:
3564 // - If A is an array type, the pointer type produced by the
3565 // array-to-pointer standard conversion (4.2) is used in place of
3566 // A for type deduction; otherwise,
3567 if (ArgType->isArrayType())
3568 ArgType = S.Context.getArrayDecayedType(ArgType);
3569 // - If A is a function type, the pointer type produced by the
3570 // function-to-pointer standard conversion (4.3) is used in place
3571 // of A for type deduction; otherwise,
3572 else if (ArgType->isFunctionType())
3573 ArgType = S.Context.getPointerType(ArgType);
3574 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003575 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003576 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003577 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003578 }
3579 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003580
Douglas Gregor7825bf32011-01-06 22:09:01 +00003581 // C++0x [temp.deduct.call]p4:
3582 // In general, the deduction process attempts to find template argument
3583 // values that will make the deduced A identical to A (after the type A
3584 // is transformed as described above). [...]
3585 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003586
Douglas Gregor7825bf32011-01-06 22:09:01 +00003587 // - If the original P is a reference type, the deduced A (i.e., the
3588 // type referred to by the reference) can be more cv-qualified than
3589 // the transformed A.
3590 if (ParamRefType)
3591 TDF |= TDF_ParamWithReferenceType;
3592 // - The transformed A can be another pointer or pointer to member
3593 // type that can be converted to the deduced A via a qualification
3594 // conversion (4.4).
3595 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3596 ArgType->isObjCObjectPointerType())
3597 TDF |= TDF_IgnoreQualifiers;
3598 // - If P is a class and P has the form simple-template-id, then the
3599 // transformed A can be a derived class of the deduced A. Likewise,
3600 // if P is a pointer to a class of the form simple-template-id, the
3601 // transformed A can be a pointer to a derived class pointed to by
3602 // the deduced A.
3603 if (isSimpleTemplateIdType(ParamType) ||
3604 (isa<PointerType>(ParamType) &&
3605 isSimpleTemplateIdType(
3606 ParamType->getAs<PointerType>()->getPointeeType())))
3607 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608
Douglas Gregor7825bf32011-01-06 22:09:01 +00003609 return false;
3610}
3611
Richard Smithf0393bf2017-02-16 04:22:56 +00003612static bool
3613hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3614 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003615
Richard Smith707eab62017-01-05 04:08:31 +00003616static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003617 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3618 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003619 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3620 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003621 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003622
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003623/// Attempt template argument deduction from an initializer list
Hubert Tong3280b332015-06-25 00:25:49 +00003624/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003625static Sema::TemplateDeductionResult DeduceFromInitializerList(
3626 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3627 InitListExpr *ILE, TemplateDeductionInfo &Info,
3628 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003629 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3630 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003631 // C++ [temp.deduct.call]p1: (CWG 1591)
3632 // If removing references and cv-qualifiers from P gives
3633 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3634 // a non-empty initializer list, then deduction is performed instead for
3635 // each element of the initializer list, taking P0 as a function template
3636 // parameter type and the initializer element as its argument
3637 //
Richard Smith707eab62017-01-05 04:08:31 +00003638 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003639 if (!ILE->getNumInits())
3640 return Sema::TDK_Success;
3641
Richard Smitha7d5ec92017-01-04 19:47:19 +00003642 QualType ElTy;
3643 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3644 if (ArrTy)
3645 ElTy = ArrTy->getElementType();
3646 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3647 // Otherwise, an initializer list argument causes the parameter to be
3648 // considered a non-deduced context
3649 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003650 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003651
Faisal Valif6dfdb32015-12-10 05:36:39 +00003652 // Deduction only needs to be done for dependent types.
3653 if (ElTy->isDependentType()) {
3654 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003655 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003656 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
Richard Smithc92d2062017-01-05 23:02:44 +00003657 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003658 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003659 }
3660 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003661
3662 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3663 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003664 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003665 // Determine the array bound is something we can deduce.
3666 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003667 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003668 // We can perform template argument deduction for the given non-type
3669 // template parameter.
Richard Smith7fa88bb2017-02-21 07:22:31 +00003670 // C++ [temp.deduct.type]p13:
3671 // The type of N in the type T[N] is std::size_t.
3672 QualType T = S.Context.getSizeType();
3673 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003674 if (auto Result = DeduceNonTypeTemplateArgument(
Richard Smith7fa88bb2017-02-21 07:22:31 +00003675 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
Richard Smitha7d5ec92017-01-04 19:47:19 +00003676 /*ArrayBound=*/true, Info, Deduced))
3677 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003678 }
3679 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003680
3681 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003682}
3683
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003684/// Perform template argument deduction per [temp.deduct.call] for a
Richard Smith707eab62017-01-05 04:08:31 +00003685/// single parameter / argument pair.
3686static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003687 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3688 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003689 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3690 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003691 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003692 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003693 QualType OrigParamType = ParamType;
3694
3695 // If P is a reference type [...]
3696 // If P is a cv-qualified type [...]
Richard Smith32918772017-02-14 00:25:28 +00003697 if (AdjustFunctionParmAndArgTypesForDeduction(
3698 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
Richard Smith363ae812017-01-04 22:03:59 +00003699 return Sema::TDK_Success;
3700
Richard Smith707eab62017-01-05 04:08:31 +00003701 // If [...] the argument is a non-empty initializer list [...]
3702 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3703 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003704 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003705
3706 // [...] the deduction process attempts to find template argument values
3707 // that will make the deduced A identical to A
3708 //
3709 // Keep track of the argument type and corresponding parameter index,
3710 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003711 OriginalCallArgs.push_back(
3712 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003713 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003714 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003715}
3716
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003717/// Perform template argument deduction from a function call
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003718/// (C++ [temp.deduct.call]).
3719///
3720/// \param FunctionTemplate the function template for which we are performing
3721/// template argument deduction.
3722///
James Dennett18348b62012-06-22 08:52:37 +00003723/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003724/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003725///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003726/// \param Args the function call arguments
3727///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003728/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003729/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003730/// template argument deduction.
3731///
3732/// \param Info the argument will be updated to provide additional information
3733/// about template argument deduction.
3734///
Richard Smith6eedfe72017-01-09 08:01:21 +00003735/// \param CheckNonDependent A callback to invoke to check conversions for
3736/// non-dependent parameters, between deduction and substitution, per DR1391.
3737/// If this returns true, substitution will be skipped and we return
3738/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3739/// types (after substituting explicit template arguments).
3740///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003741/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003742Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3743 FunctionTemplateDecl *FunctionTemplate,
3744 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003745 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003746 bool PartialOverloading,
3747 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003748 if (FunctionTemplate->isInvalidDecl())
3749 return TDK_Invalid;
3750
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003751 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003752 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003753
Richard Smith32918772017-02-14 00:25:28 +00003754 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3755
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003756 // C++ [temp.deduct.call]p1:
3757 // Template argument deduction is done by comparing each function template
3758 // parameter type (call it P) with the type of the corresponding argument
3759 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003760 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003761 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003762 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003763 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003764 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003765 if (Proto->isTemplateVariadic())
3766 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003767 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003768 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003769 }
Mike Stump11289f42009-09-09 15:08:12 +00003770
Douglas Gregor89026b52009-06-30 23:57:56 +00003771 // The types of the parameters from which we will perform template argument
3772 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003773 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003774 TemplateParameterList *TemplateParams
3775 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003776 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003777 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003778 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003779 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003780 TemplateDeductionResult Result =
3781 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003782 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003783 Deduced,
3784 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003785 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003786 Info);
3787 if (Result)
3788 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003789
3790 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003791 } else {
3792 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003793 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003794 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3795 }
Mike Stump11289f42009-09-09 15:08:12 +00003796
Richard Smith6eedfe72017-01-09 08:01:21 +00003797 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003798
3799 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3800 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003801 // C++ [demp.deduct.call]p1: (DR1391)
3802 // Template argument deduction is done by comparing each function template
3803 // parameter that contains template-parameters that participate in
3804 // template argument deduction ...
Richard Smithf0393bf2017-02-16 04:22:56 +00003805 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003806 return Sema::TDK_Success;
3807
Richard Smith707eab62017-01-05 04:08:31 +00003808 // ... with the type of the corresponding argument
3809 return DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003810 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003811 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003812 };
3813
Douglas Gregor89026b52009-06-30 23:57:56 +00003814 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003815 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003816 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003817 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003818 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003819 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003820
Richard Smitha7d5ec92017-01-04 19:47:19 +00003821 const PackExpansionType *ParamExpansion =
3822 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003823 if (!ParamExpansion) {
3824 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003825 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003826 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003827
Richard Smith6eedfe72017-01-09 08:01:21 +00003828 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003829 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003830 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003831
Douglas Gregor7825bf32011-01-06 22:09:01 +00003832 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003834
Richard Smithde0d34a2017-01-09 07:14:40 +00003835 QualType ParamPattern = ParamExpansion->getPattern();
3836 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3837 ParamPattern);
3838
Douglas Gregor7825bf32011-01-06 22:09:01 +00003839 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003840 // For a function parameter pack that occurs at the end of the
3841 // parameter-declaration-list, the type A of each remaining argument of
3842 // the call is compared with the type P of the declarator-id of the
3843 // function parameter pack. Each comparison deduces template arguments
3844 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003845 // the function parameter pack. When a function parameter pack appears
3846 // in a non-deduced context [not at the end of the list], the type of
3847 // that parameter pack is never deduced.
3848 //
3849 // FIXME: The above rule allows the size of the parameter pack to change
3850 // after we skip it (in the non-deduced case). That makes no sense, so
3851 // we instead notionally deduce the pack against N arguments, where N is
3852 // the length of the explicitly-specified pack if it's expanded by the
3853 // parameter pack and 0 otherwise, and we treat each deduction as a
3854 // non-deduced context.
3855 if (ParamIdx + 1 == NumParamTypes) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003856 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx) {
3857 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003858 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3859 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003860 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003861 } else {
3862 // If the parameter type contains an explicitly-specified pack that we
3863 // could not expand, skip the number of parameters notionally created
3864 // by the expansion.
3865 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003866 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003867 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003868 ++I, ++ArgIdx) {
3869 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003870 // FIXME: Should we add OriginalCallArgs for these? What if the
3871 // corresponding argument is a list?
3872 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003873 }
3874 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003876
Douglas Gregor7825bf32011-01-06 22:09:01 +00003877 // Build argument packs for each of the parameter packs expanded by this
3878 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003879 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003881 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003882
Akira Hatanaka4ac16db2018-06-13 05:26:23 +00003883 // Capture the context in which the function call is made. This is the context
3884 // that is needed when the accessibility of template arguments is checked.
3885 DeclContext *CallingCtx = CurContext;
3886
Richard Smith6eedfe72017-01-09 08:01:21 +00003887 return FinishTemplateArgumentDeduction(
3888 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
Akira Hatanaka4ac16db2018-06-13 05:26:23 +00003889 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
3890 ContextRAII SavedContext(*this, CallingCtx);
3891 return CheckNonDependent(ParamTypesForArgChecking);
3892 });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003893}
3894
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003895QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003896 QualType FunctionType,
3897 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003898 if (ArgFunctionType.isNull())
3899 return ArgFunctionType;
3900
3901 const FunctionProtoType *FunctionTypeP =
3902 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003903 const FunctionProtoType *ArgFunctionTypeP =
3904 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003905
3906 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3907 bool Rebuild = false;
3908
3909 CallingConv CC = FunctionTypeP->getCallConv();
3910 if (EPI.ExtInfo.getCC() != CC) {
3911 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3912 Rebuild = true;
3913 }
3914
3915 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3916 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3917 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3918 Rebuild = true;
3919 }
3920
3921 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3922 ArgFunctionTypeP->hasExceptionSpec())) {
3923 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3924 Rebuild = true;
3925 }
3926
3927 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003928 return ArgFunctionType;
3929
Richard Smithbaa47832016-12-01 02:11:49 +00003930 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3931 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003932}
3933
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003934/// Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003935/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3936/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003937///
3938/// \param FunctionTemplate the function template for which we are performing
3939/// template argument deduction.
3940///
James Dennett18348b62012-06-22 08:52:37 +00003941/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003942/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003943///
3944/// \param ArgFunctionType the function type that will be used as the
3945/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003946/// function template's function type. This type may be NULL, if there is no
3947/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003948///
3949/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003950/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003951/// template argument deduction.
3952///
3953/// \param Info the argument will be updated to provide additional information
3954/// about template argument deduction.
3955///
Richard Smithbaa47832016-12-01 02:11:49 +00003956/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3957/// the address of a function template per [temp.deduct.funcaddr] and
3958/// [over.over]. If \c false, we are looking up a function template
3959/// specialization based on its signature, per [temp.deduct.decl].
3960///
Douglas Gregor9b146582009-07-08 20:55:45 +00003961/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003962Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3963 FunctionTemplateDecl *FunctionTemplate,
3964 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3965 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3966 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003967 if (FunctionTemplate->isInvalidDecl())
3968 return TDK_Invalid;
3969
Douglas Gregor9b146582009-07-08 20:55:45 +00003970 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3971 TemplateParameterList *TemplateParams
3972 = FunctionTemplate->getTemplateParameters();
3973 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003974
Douglas Gregor9b146582009-07-08 20:55:45 +00003975 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003976 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003977 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003978 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003979 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003980 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003981 if (TemplateDeductionResult Result
3982 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003983 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003984 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003985 &FunctionType, Info))
3986 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003987
3988 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003989 }
3990
Richard Smithcd198152017-06-07 21:46:22 +00003991 // When taking the address of a function, we require convertibility of
3992 // the resulting function type. Otherwise, we allow arbitrary mismatches
3993 // of calling convention and noreturn.
3994 if (!IsAddressOfFunction)
3995 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3996 /*AdjustExceptionSpec*/false);
3997
Eli Friedman77dcc722012-02-08 03:07:05 +00003998 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003999 EnterExpressionEvaluationContext Unevaluated(
4000 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00004001 SFINAETrap Trap(*this);
4002
John McCallc1f69982010-02-02 02:21:27 +00004003 Deduced.resize(TemplateParams->size());
4004
Richard Smith2a7d4812013-05-04 07:00:32 +00004005 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00004006 // type so that we treat it as a non-deduced context in what follows. If we
4007 // are looking up by signature, the signature type should also have a deduced
4008 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00004009 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00004010 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00004011 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00004012 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00004013 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00004014 }
4015
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004016 if (!ArgFunctionType.isNull()) {
Richard Smithcd198152017-06-07 21:46:22 +00004017 unsigned TDF =
4018 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004019 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004020 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004021 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004022 FunctionType, ArgFunctionType,
4023 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004024 return Result;
4025 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004026
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004027 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004028 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4029 NumExplicitlySpecified,
4030 Specialization, Info))
4031 return Result;
4032
Richard Smith2a7d4812013-05-04 07:00:32 +00004033 // If the function has a deduced return type, deduce it now, so we can check
4034 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00004035 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00004036 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00004037 DeduceReturnType(Specialization, Info.getLocation(), false))
4038 return TDK_MiscellaneousDeductionFailure;
4039
Richard Smith9095e5b2016-11-01 01:31:23 +00004040 // If the function has a dependent exception specification, resolve it now,
4041 // so we can check that the exception specification matches.
4042 auto *SpecializationFPT =
4043 Specialization->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004044 if (getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +00004045 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
4046 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
4047 return TDK_MiscellaneousDeductionFailure;
4048
Richard Smithcd198152017-06-07 21:46:22 +00004049 // Adjust the exception specification of the argument to match the
Richard Smithbaa47832016-12-01 02:11:49 +00004050 // substituted and resolved type we just formed. (Calling convention and
4051 // noreturn can't be dependent, so we don't actually need this for them
4052 // right now.)
4053 QualType SpecializationType = Specialization->getType();
4054 if (!IsAddressOfFunction)
4055 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4056 /*AdjustExceptionSpec*/true);
4057
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004058 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00004059 // specialization with respect to arguments of compatible pointer to function
4060 // types, template argument deduction fails.
4061 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00004062 if (IsAddressOfFunction &&
4063 !isSameOrCompatibleFunctionType(
4064 Context.getCanonicalType(SpecializationType),
4065 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00004066 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00004067
4068 if (!IsAddressOfFunction &&
4069 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00004070 return TDK_MiscellaneousDeductionFailure;
4071 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004072
4073 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00004074}
4075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004076/// Deduce template arguments for a templated conversion
Douglas Gregor05155d82009-08-21 23:19:43 +00004077/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4078/// conversion function template specialization.
4079Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00004080Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00004081 QualType ToType,
4082 CXXConversionDecl *&Specialization,
4083 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00004084 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00004085 return TDK_Invalid;
4086
Faisal Vali2b3a3012013-10-24 23:40:02 +00004087 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00004088 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4089
Faisal Vali2b3a3012013-10-24 23:40:02 +00004090 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00004091
4092 // Canonicalize the types for deduction.
4093 QualType P = Context.getCanonicalType(FromType);
4094 QualType A = Context.getCanonicalType(ToType);
4095
Douglas Gregord99609a2011-03-06 09:03:20 +00004096 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00004097 // If P is a reference type, the type referred to by P is used for
4098 // type deduction.
4099 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4100 P = PRef->getPointeeType();
4101
Douglas Gregord99609a2011-03-06 09:03:20 +00004102 // C++0x [temp.deduct.conv]p4:
4103 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00004104 // for type deduction.
Richard Smithb884ed12018-07-11 23:19:41 +00004105 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4106 A = ARef->getPointeeType();
4107 // We work around a defect in the standard here: cv-qualifiers are also
4108 // removed from P and A in this case, unless P was a reference type. This
4109 // seems to mostly match what other compilers are doing.
4110 if (!FromType->getAs<ReferenceType>()) {
4111 A = A.getUnqualifiedType();
4112 P = P.getUnqualifiedType();
4113 }
4114
Douglas Gregord99609a2011-03-06 09:03:20 +00004115 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00004116 //
Mike Stump11289f42009-09-09 15:08:12 +00004117 // If A is not a reference type:
Richard Smithb884ed12018-07-11 23:19:41 +00004118 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004119 assert(!A->isReferenceType() && "Reference types were handled above");
4120
4121 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00004122 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00004123 // of P for type deduction; otherwise,
4124 if (P->isArrayType())
4125 P = Context.getArrayDecayedType(P);
4126 // - If P is a function type, the pointer type produced by the
4127 // function-to-pointer standard conversion (4.3) is used in
4128 // place of P for type deduction; otherwise,
4129 else if (P->isFunctionType())
4130 P = Context.getPointerType(P);
4131 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004132 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004133 else
4134 P = P.getUnqualifiedType();
4135
Douglas Gregord99609a2011-03-06 09:03:20 +00004136 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004137 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00004138 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00004139 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004140 A = A.getUnqualifiedType();
4141 }
4142
Eli Friedman77dcc722012-02-08 03:07:05 +00004143 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00004144 EnterExpressionEvaluationContext Unevaluated(
4145 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00004146 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004147
4148 // C++ [temp.deduct.conv]p1:
4149 // Template argument deduction is done by comparing the return
4150 // type of the template conversion function (call it P) with the
4151 // type that is required as the result of the conversion (call it
4152 // A) as described in 14.8.2.4.
4153 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00004154 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004155 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00004156 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00004157
4158 // C++0x [temp.deduct.conv]p4:
4159 // In general, the deduction process attempts to find template
4160 // argument values that will make the deduced A identical to
4161 // A. However, there are two cases that allow a difference:
4162 unsigned TDF = 0;
4163 // - If the original A is a reference type, A can be more
4164 // cv-qualified than the deduced A (i.e., the type referred to
4165 // by the reference)
4166 if (ToType->isReferenceType())
Richard Smithb884ed12018-07-11 23:19:41 +00004167 TDF |= TDF_ArgWithReferenceType;
Douglas Gregor05155d82009-08-21 23:19:43 +00004168 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004169 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00004170 // conversion.
4171 //
4172 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4173 // both P and A are pointers or member pointers. In this case, we
4174 // just ignore cv-qualifiers completely).
4175 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00004176 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00004177 TDF |= TDF_IgnoreQualifiers;
4178 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004179 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4180 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00004181 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00004182
4183 // Create an Instantiation Scope for finalizing the operator.
4184 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004185 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00004186 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00004187 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00004188 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004189 ConversionSpecialized, Info);
4190 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
Douglas Gregor05155d82009-08-21 23:19:43 +00004191 return Result;
4192}
4193
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004194/// Deduce template arguments for a function template when there is
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004195/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4196///
4197/// \param FunctionTemplate the function template for which we are performing
4198/// template argument deduction.
4199///
James Dennett18348b62012-06-22 08:52:37 +00004200/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004201/// arguments.
4202///
4203/// \param Specialization if template argument deduction was successful,
4204/// this will be set to the function template specialization produced by
4205/// template argument deduction.
4206///
4207/// \param Info the argument will be updated to provide additional information
4208/// about template argument deduction.
4209///
Richard Smithbaa47832016-12-01 02:11:49 +00004210/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4211/// the address of a function template in a context where we do not have a
4212/// target type, per [over.over]. If \c false, we are looking up a function
4213/// template specialization based on its signature, which only happens when
4214/// deducing a function parameter type from an argument that is a template-id
4215/// naming a function template specialization.
4216///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004217/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004218Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4219 FunctionTemplateDecl *FunctionTemplate,
4220 TemplateArgumentListInfo *ExplicitTemplateArgs,
4221 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4222 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004223 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004224 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004225 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004226}
4227
Richard Smith30482bc2011-02-20 03:19:35 +00004228namespace {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004229
Richard Smith60437622017-02-09 19:17:44 +00004230 /// Substitute the 'auto' specifier or deduced template specialization type
4231 /// specifier within a type for a given replacement type.
4232 class SubstituteDeducedTypeTransform :
4233 public TreeTransform<SubstituteDeducedTypeTransform> {
Richard Smith30482bc2011-02-20 03:19:35 +00004234 QualType Replacement;
Richard Smith60437622017-02-09 19:17:44 +00004235 bool UseTypeSugar;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004236
Richard Smith30482bc2011-02-20 03:19:35 +00004237 public:
Richard Smith60437622017-02-09 19:17:44 +00004238 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4239 bool UseTypeSugar = true)
4240 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4241 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4242
4243 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4244 assert(isa<TemplateTypeParmType>(Replacement) &&
4245 "unexpected unsugared replacement kind");
4246 QualType Result = Replacement;
4247 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4248 NewTL.setNameLoc(TL.getNameLoc());
4249 return Result;
4250 }
Nico Weberc153d242014-07-28 00:02:09 +00004251
Richard Smith30482bc2011-02-20 03:19:35 +00004252 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4253 // If we're building the type pattern to deduce against, don't wrap the
4254 // substituted type in an AutoType. Certain template deduction rules
4255 // apply only when a template type parameter appears directly (and not if
4256 // the parameter is found through desugaring). For instance:
4257 // auto &&lref = lvalue;
4258 // must transform into "rvalue reference to T" not "rvalue reference to
4259 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith60437622017-02-09 19:17:44 +00004260 //
4261 // FIXME: Is this still necessary?
4262 if (!UseTypeSugar)
4263 return TransformDesugared(TLB, TL);
4264
4265 QualType Result = SemaRef.Context.getAutoType(
4266 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4267 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4268 NewTL.setNameLoc(TL.getNameLoc());
4269 return Result;
4270 }
4271
4272 QualType TransformDeducedTemplateSpecializationType(
4273 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4274 if (!UseTypeSugar)
4275 return TransformDesugared(TLB, TL);
4276
4277 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4278 TL.getTypePtr()->getTemplateName(),
4279 Replacement, Replacement.isNull());
4280 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4281 NewTL.setNameLoc(TL.getNameLoc());
4282 return Result;
Richard Smith30482bc2011-02-20 03:19:35 +00004283 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004284
4285 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4286 // Lambdas never need to be transformed.
4287 return E;
4288 }
Richard Smith061f1e22013-04-30 21:23:01 +00004289
Richard Smith2a7d4812013-05-04 07:00:32 +00004290 QualType Apply(TypeLoc TL) {
4291 // Create some scratch storage for the transformed type locations.
4292 // FIXME: We're just going to throw this information away. Don't build it.
4293 TypeLocBuilder TLB;
4294 TLB.reserve(TL.getFullDataSize());
4295 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004296 }
Richard Smith30482bc2011-02-20 03:19:35 +00004297 };
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004298
4299} // namespace
Richard Smith30482bc2011-02-20 03:19:35 +00004300
Richard Smith2a7d4812013-05-04 07:00:32 +00004301Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004302Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4303 Optional<unsigned> DependentDeductionDepth) {
4304 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4305 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004306}
4307
Richard Smithb1efc9b2017-08-30 00:44:08 +00004308/// Attempt to produce an informative diagostic explaining why auto deduction
4309/// failed.
4310/// \return \c true if diagnosed, \c false if not.
4311static bool diagnoseAutoDeductionFailure(Sema &S,
4312 Sema::TemplateDeductionResult TDK,
4313 TemplateDeductionInfo &Info,
4314 ArrayRef<SourceRange> Ranges) {
4315 switch (TDK) {
4316 case Sema::TDK_Inconsistent: {
4317 // Inconsistent deduction means we were deducing from an initializer list.
4318 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
4319 D << Info.FirstArg << Info.SecondArg;
4320 for (auto R : Ranges)
4321 D << R;
4322 return true;
4323 }
4324
4325 // FIXME: Are there other cases for which a custom diagnostic is more useful
4326 // than the basic "types don't match" diagnostic?
4327
4328 default:
4329 return false;
4330 }
4331}
4332
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004333/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004334///
Richard Smith87d263e2016-12-25 08:05:23 +00004335/// Note that this is done even if the initializer is dependent. (This is
4336/// necessary to support partial ordering of templates using 'auto'.)
4337/// A dependent type will be produced when deducing from a dependent type.
4338///
Richard Smith30482bc2011-02-20 03:19:35 +00004339/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004340/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004341/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004342/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004343/// \param DependentDeductionDepth Set if we should permit deduction in
4344/// dependent cases. This is necessary for template partial ordering with
4345/// 'auto' template parameters. The value specified is the template
4346/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004347Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004348Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4349 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004350 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004351 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4352 if (NonPlaceholder.isInvalid())
4353 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004354 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004355 }
4356
Richard Smith87d263e2016-12-25 08:05:23 +00004357 if (!DependentDeductionDepth &&
4358 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
Richard Smith60437622017-02-09 19:17:44 +00004359 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004360 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004361 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004362 }
4363
Richard Smith87d263e2016-12-25 08:05:23 +00004364 // Find the depth of template parameter to synthesize.
4365 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4366
Richard Smith74aeef52013-04-26 16:15:35 +00004367 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4368 // Since 'decltype(auto)' can only occur at the top of the type, we
4369 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004370 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004371 if (AT->isDecltypeAuto()) {
4372 if (isa<InitListExpr>(Init)) {
4373 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4374 return DAR_FailedAlreadyDiagnosed;
4375 }
4376
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004377 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004378 if (Deduced.isNull())
4379 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004380 // FIXME: Support a non-canonical deduced type for 'auto'.
4381 Deduced = Context.getCanonicalType(Deduced);
Richard Smith60437622017-02-09 19:17:44 +00004382 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004383 if (Result.isNull())
4384 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004385 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004386 } else if (!getLangOpts().CPlusPlus) {
4387 if (isa<InitListExpr>(Init)) {
4388 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4389 return DAR_FailedAlreadyDiagnosed;
4390 }
Richard Smith74aeef52013-04-26 16:15:35 +00004391 }
4392 }
4393
Richard Smith30482bc2011-02-20 03:19:35 +00004394 SourceLocation Loc = Init->getExprLoc();
4395
4396 LocalInstantiationScope InstScope(*this);
4397
4398 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004399 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4400 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004401 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4402 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004403 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4404 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004405
Richard Smith87d263e2016-12-25 08:05:23 +00004406 QualType FuncParam =
Richard Smith60437622017-02-09 19:17:44 +00004407 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
Richard Smith87d263e2016-12-25 08:05:23 +00004408 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004409 assert(!FuncParam.isNull() &&
4410 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004411
4412 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004413 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004414 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004415
Richard Smith87d263e2016-12-25 08:05:23 +00004416 TemplateDeductionInfo Info(Loc, Depth);
4417
4418 // If deduction failed, don't diagnose if the initializer is dependent; it
4419 // might acquire a matching type in the instantiation.
Richard Smithb1efc9b2017-08-30 00:44:08 +00004420 auto DeductionFailed = [&](TemplateDeductionResult TDK,
4421 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
Richard Smith87d263e2016-12-25 08:05:23 +00004422 if (Init->isTypeDependent()) {
Richard Smith60437622017-02-09 19:17:44 +00004423 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith87d263e2016-12-25 08:05:23 +00004424 assert(!Result.isNull() && "substituting DependentTy can't fail");
4425 return DAR_Succeeded;
4426 }
Richard Smithb1efc9b2017-08-30 00:44:08 +00004427 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
4428 return DAR_FailedAlreadyDiagnosed;
Richard Smith87d263e2016-12-25 08:05:23 +00004429 return DAR_Failed;
4430 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004431
Richard Smith707eab62017-01-05 04:08:31 +00004432 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4433
Richard Smith74801c82012-07-08 04:13:07 +00004434 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004435 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004436 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4437 // against that. Such deduction only succeeds if removing cv-qualifiers and
4438 // references results in std::initializer_list<T>.
4439 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4440 return DAR_Failed;
4441
Richard Smithb1efc9b2017-08-30 00:44:08 +00004442 SourceRange DeducedFromInitRange;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004443 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00004444 Expr *Init = InitList->getInit(i);
4445
4446 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4447 *this, TemplateParamsSt.get(), 0, TemplArg, Init,
Richard Smithc92d2062017-01-05 23:02:44 +00004448 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4449 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004450 return DeductionFailed(TDK, {DeducedFromInitRange,
4451 Init->getSourceRange()});
4452
4453 if (DeducedFromInitRange.isInvalid() &&
4454 Deduced[0].getKind() != TemplateArgument::Null)
4455 DeducedFromInitRange = Init->getSourceRange();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004456 }
4457 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004458 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4459 Diag(Loc, diag::err_auto_bitfield);
4460 return DAR_FailedAlreadyDiagnosed;
4461 }
4462
Richard Smithb1efc9b2017-08-30 00:44:08 +00004463 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004464 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004465 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004466 return DeductionFailed(TDK, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004467 }
Richard Smith30482bc2011-02-20 03:19:35 +00004468
Richard Smith87d263e2016-12-25 08:05:23 +00004469 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004470 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smithb1efc9b2017-08-30 00:44:08 +00004471 return DeductionFailed(TDK_Incomplete, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004472
Eli Friedmane4310952012-11-06 23:56:42 +00004473 QualType DeducedType = Deduced[0].getAsType();
4474
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004475 if (InitList) {
4476 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4477 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004478 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004479 }
4480
Richard Smith60437622017-02-09 19:17:44 +00004481 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004482 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004483 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004484
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004485 // Check that the deduced argument type is compatible with the original
4486 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004487 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004488 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004489 assert((bool)InitList == OriginalArg.DecomposedParam &&
4490 "decomposed non-init-list in auto deduction?");
Richard Smithb1efc9b2017-08-30 00:44:08 +00004491 if (auto TDK =
4492 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004493 Result = QualType();
Richard Smithb1efc9b2017-08-30 00:44:08 +00004494 return DeductionFailed(TDK, {});
Richard Smith707eab62017-01-05 04:08:31 +00004495 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004496 }
4497
Sebastian Redl09edce02012-01-23 22:09:39 +00004498 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004499}
4500
Simon Pilgrim728134c2016-08-12 11:43:57 +00004501QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004502 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004503 if (TypeToReplaceAuto->isDependentType())
4504 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004505 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004506 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004507}
4508
Richard Smith60437622017-02-09 19:17:44 +00004509TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4510 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004511 if (TypeToReplaceAuto->isDependentType())
4512 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004513 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004514 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004515}
4516
Richard Smith33c33c32017-02-04 01:28:01 +00004517QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4518 QualType TypeToReplaceAuto) {
Richard Smith60437622017-02-09 19:17:44 +00004519 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4520 /*UseTypeSugar*/ false)
Richard Smith33c33c32017-02-04 01:28:01 +00004521 .TransformType(TypeWithAuto);
4522}
4523
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004524void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4525 if (isa<InitListExpr>(Init))
4526 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004527 VDecl->isInitCapture()
4528 ? diag::err_init_capture_deduction_failure_from_init_list
4529 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004530 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4531 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004532 Diag(VDecl->getLocation(),
4533 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4534 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004535 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4536 << Init->getSourceRange();
4537}
4538
Richard Smith2a7d4812013-05-04 07:00:32 +00004539bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4540 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004541 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004542
Richard Smith50e291e2018-01-02 23:52:42 +00004543 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
4544 // within the return type from the call operator's type.
4545 if (isLambdaConversionOperator(FD)) {
4546 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
4547 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
4548
4549 // For a generic lambda, instantiate the call operator if needed.
4550 if (auto *Args = FD->getTemplateSpecializationArgs()) {
4551 CallOp = InstantiateFunctionDeclaration(
4552 CallOp->getDescribedFunctionTemplate(), Args, Loc);
4553 if (!CallOp || CallOp->isInvalidDecl())
4554 return true;
4555
4556 // We might need to deduce the return type by instantiating the definition
4557 // of the operator() function.
4558 if (CallOp->getReturnType()->isUndeducedType())
4559 InstantiateFunctionDefinition(Loc, CallOp);
4560 }
4561
4562 if (CallOp->isInvalidDecl())
4563 return true;
4564 assert(!CallOp->getReturnType()->isUndeducedType() &&
4565 "failed to deduce lambda return type");
4566
4567 // Build the new return type from scratch.
4568 QualType RetType = getLambdaConversionFunctionResultType(
4569 CallOp->getType()->castAs<FunctionProtoType>());
4570 if (FD->getReturnType()->getAs<PointerType>())
4571 RetType = Context.getPointerType(RetType);
4572 else {
4573 assert(FD->getReturnType()->getAs<BlockPointerType>());
4574 RetType = Context.getBlockPointerType(RetType);
4575 }
4576 Context.adjustDeducedFunctionResultType(FD, RetType);
4577 return false;
4578 }
4579
Richard Smith2a7d4812013-05-04 07:00:32 +00004580 if (FD->getTemplateInstantiationPattern())
4581 InstantiateFunctionDefinition(Loc, FD);
4582
Alp Toker314cc812014-01-25 16:55:45 +00004583 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004584 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4585 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4586 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4587 }
4588
4589 return StillUndeduced;
4590}
4591
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004592/// If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004593static void
4594AddImplicitObjectParameterType(ASTContext &Context,
4595 CXXMethodDecl *Method,
4596 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004597 // C++11 [temp.func.order]p3:
4598 // [...] The new parameter is of type "reference to cv A," where cv are
4599 // the cv-qualifiers of the function template (if any) and A is
4600 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004601 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004602 // The standard doesn't say explicitly, but we pick the appropriate kind of
4603 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004604 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4605 ArgTy = Context.getQualifiedType(ArgTy,
4606 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004607 if (Method->getRefQualifier() == RQ_RValue)
4608 ArgTy = Context.getRValueReferenceType(ArgTy);
4609 else
4610 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004611 ArgTypes.push_back(ArgTy);
4612}
4613
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004614/// Determine whether the function template \p FT1 is at least as
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004615/// specialized as \p FT2.
4616static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004617 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004618 FunctionTemplateDecl *FT1,
4619 FunctionTemplateDecl *FT2,
4620 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004621 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004622 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004624 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4625 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004627 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4628 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004629 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004630 Deduced.resize(TemplateParams->size());
4631
4632 // C++0x [temp.deduct.partial]p3:
4633 // The types used to determine the ordering depend on the context in which
4634 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004635 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004636 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004637 switch (TPOC) {
4638 case TPOC_Call: {
4639 // - In the context of a function call, the function parameter types are
4640 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004641 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4642 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004643
Eli Friedman3b5774a2012-09-19 23:27:04 +00004644 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004645 // [...] If only one of the function templates is a non-static
4646 // member, that function template is considered to have a new
4647 // first parameter inserted in its function parameter list. The
4648 // new parameter is of type "reference to cv A," where cv are
4649 // the cv-qualifiers of the function template (if any) and A is
4650 // the class of which the function template is a member.
4651 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004652 // Note that we interpret this to mean "if one of the function
4653 // templates is a non-static member and the other is a non-member";
4654 // otherwise, the ordering rules for static functions against non-static
4655 // functions don't make any sense.
4656 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004657 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4658 // it as wording was broken prior to it.
Richard Smithf0393bf2017-02-16 04:22:56 +00004659 SmallVector<QualType, 4> Args1;
4660
Richard Smithe5b52202013-09-11 00:52:39 +00004661 unsigned NumComparedArguments = NumCallArguments1;
4662
4663 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004664 // Compare 'this' from Method1 against first parameter from Method2.
4665 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4666 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004667 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004668 // Compare 'this' from Method2 against first parameter from Method1.
4669 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004670 }
4671
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004672 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004673 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004674 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004675 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676
Douglas Gregorb837ea42011-01-11 17:34:58 +00004677 // C++ [temp.func.order]p5:
4678 // The presence of unused ellipsis and default arguments has no effect on
4679 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004680 if (Args1.size() > NumComparedArguments)
4681 Args1.resize(NumComparedArguments);
4682 if (Args2.size() > NumComparedArguments)
4683 Args2.resize(NumComparedArguments);
Richard Smithf0393bf2017-02-16 04:22:56 +00004684 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4685 Args1.data(), Args1.size(), Info, Deduced,
4686 TDF_None, /*PartialOrdering=*/true))
4687 return false;
4688
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004689 break;
4690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004691
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004692 case TPOC_Conversion:
4693 // - In the context of a call to a conversion operator, the return types
4694 // of the conversion function templates are used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004695 if (DeduceTemplateArgumentsByTypeMatch(
4696 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4697 Info, Deduced, TDF_None,
4698 /*PartialOrdering=*/true))
4699 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004700 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004702 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004703 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004704 // is used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004705 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4706 FD2->getType(), FD1->getType(),
4707 Info, Deduced, TDF_None,
4708 /*PartialOrdering=*/true))
4709 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004710 break;
4711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004712
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004713 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004714 // In most cases, all template parameters must have values in order for
4715 // deduction to succeed, but for partial ordering purposes a template
4716 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004717 // types being used for partial ordering. [ Note: a template parameter used
4718 // in a non-deduced context is considered used. -end note]
4719 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4720 for (; ArgIdx != NumArgs; ++ArgIdx)
4721 if (Deduced[ArgIdx].isNull())
4722 break;
4723
Richard Smithf0393bf2017-02-16 04:22:56 +00004724 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4725 // to substitute the deduced arguments back into the template and check that
4726 // we get the right type.
Richard Smithcf824862016-12-30 04:32:02 +00004727
Richard Smithf0393bf2017-02-16 04:22:56 +00004728 if (ArgIdx == NumArgs) {
4729 // All template arguments were deduced. FT1 is at least as specialized
4730 // as FT2.
4731 return true;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004732 }
4733
Richard Smithf0393bf2017-02-16 04:22:56 +00004734 // Figure out which template parameters were used.
4735 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4736 switch (TPOC) {
4737 case TPOC_Call:
4738 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4739 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4740 TemplateParams->getDepth(),
4741 UsedParameters);
4742 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743
Richard Smithf0393bf2017-02-16 04:22:56 +00004744 case TPOC_Conversion:
4745 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4746 TemplateParams->getDepth(), UsedParameters);
4747 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748
Richard Smithf0393bf2017-02-16 04:22:56 +00004749 case TPOC_Other:
4750 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4751 TemplateParams->getDepth(),
4752 UsedParameters);
4753 break;
Richard Smith86a1b132017-02-16 03:49:44 +00004754 }
4755
Richard Smithf0393bf2017-02-16 04:22:56 +00004756 for (; ArgIdx != NumArgs; ++ArgIdx)
4757 // If this argument had no value deduced but was used in one of the types
4758 // used for partial ordering, then deduction fails.
4759 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4760 return false;
4761
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004762 return true;
4763}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004765/// Determine whether this a function template whose parameter-type-list
Douglas Gregorcef1a032011-01-16 16:03:23 +00004766/// ends with a function parameter pack.
4767static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4768 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4769 unsigned NumParams = Function->getNumParams();
4770 if (NumParams == 0)
4771 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772
Douglas Gregorcef1a032011-01-16 16:03:23 +00004773 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4774 if (!Last->isParameterPack())
4775 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776
Douglas Gregorcef1a032011-01-16 16:03:23 +00004777 // Make sure that no previous parameter is a parameter pack.
4778 while (--NumParams > 0) {
4779 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4780 return false;
4781 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782
Douglas Gregorcef1a032011-01-16 16:03:23 +00004783 return true;
4784}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004785
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004786/// Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004787/// to the rules of function template partial ordering (C++ [temp.func.order]).
4788///
4789/// \param FT1 the first function template
4790///
4791/// \param FT2 the second function template
4792///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004793/// \param TPOC the context in which we are performing partial ordering of
4794/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004795///
Richard Smithe5b52202013-09-11 00:52:39 +00004796/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4797/// only when \c TPOC is \c TPOC_Call.
4798///
4799/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4800/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004801///
Douglas Gregorbe999392009-09-15 16:23:51 +00004802/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004803/// template is more specialized, returns NULL.
4804FunctionTemplateDecl *
4805Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4806 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004807 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004808 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004809 unsigned NumCallArguments1,
4810 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004812 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004813 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004814 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004815
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004816 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004817 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004818
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004819 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004820 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004821
Douglas Gregorcef1a032011-01-16 16:03:23 +00004822 // FIXME: This mimics what GCC implements, but doesn't match up with the
4823 // proposed resolution for core issue 692. This area needs to be sorted out,
4824 // but for now we attempt to maintain compatibility.
4825 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4826 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4827 if (Variadic1 != Variadic2)
4828 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829
Craig Topperc3ec1492014-05-26 06:22:03 +00004830 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004831}
Douglas Gregor9b146582009-07-08 20:55:45 +00004832
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004833/// Determine if the two templates are equivalent.
Douglas Gregor450f00842009-09-25 18:43:00 +00004834static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4835 if (T1 == T2)
4836 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004837
Douglas Gregor450f00842009-09-25 18:43:00 +00004838 if (!T1 || !T2)
4839 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004840
Douglas Gregor450f00842009-09-25 18:43:00 +00004841 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4842}
4843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004844/// Retrieve the most specialized of the given function template
Douglas Gregor450f00842009-09-25 18:43:00 +00004845/// specializations.
4846///
John McCall58cc69d2010-01-27 01:50:18 +00004847/// \param SpecBegin the start iterator of the function template
4848/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004849///
John McCall58cc69d2010-01-27 01:50:18 +00004850/// \param SpecEnd the end iterator of the function template
4851/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004852///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004853/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004854/// diagnostic should occur.
4855///
4856/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4857/// no matching candidates.
4858///
4859/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4860/// occurs.
4861///
4862/// \param CandidateDiag partial diagnostic used for each function template
4863/// specialization that is a candidate in the ambiguous ordering. One parameter
4864/// in this diagnostic should be unbound, which will correspond to the string
4865/// describing the template arguments for the function template specialization.
4866///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004867/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004868/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004869UnresolvedSetIterator Sema::getMostSpecialized(
4870 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4871 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004872 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4873 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4874 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004875 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004876 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004877 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004878 FailedCandidates.NoteCandidates(*this, Loc);
4879 }
John McCall58cc69d2010-01-27 01:50:18 +00004880 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004882
4883 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004884 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004885
Douglas Gregor450f00842009-09-25 18:43:00 +00004886 // Find the function template that is better than all of the templates it
4887 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004888 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004890 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004891 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004892 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4893 FunctionTemplateDecl *Challenger
4894 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004895 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004896 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004897 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004898 Challenger)) {
4899 Best = I;
4900 BestTemplate = Challenger;
4901 }
4902 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903
Douglas Gregor450f00842009-09-25 18:43:00 +00004904 // Make sure that the "best" function template is more specialized than all
4905 // of the others.
4906 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004907 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4908 FunctionTemplateDecl *Challenger
4909 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004910 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004911 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004912 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004913 BestTemplate)) {
4914 Ambiguous = true;
4915 break;
4916 }
4917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918
Douglas Gregor450f00842009-09-25 18:43:00 +00004919 if (!Ambiguous) {
4920 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004921 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004923
Douglas Gregor450f00842009-09-25 18:43:00 +00004924 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004925 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004926 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004927
Richard Smithb875c432013-05-04 01:51:08 +00004928 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004929 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4930 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004931 const auto *FD = cast<FunctionDecl>(*I);
4932 PD << FD << getTemplateArgumentBindingsText(
4933 FD->getPrimaryTemplate()->getTemplateParameters(),
4934 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004935 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004936 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004937 Diag((*I)->getLocation(), PD);
4938 }
Richard Smithb875c432013-05-04 01:51:08 +00004939 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940
John McCall58cc69d2010-01-27 01:50:18 +00004941 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004942}
4943
Richard Smith0da6dc42016-12-24 16:40:51 +00004944/// Determine whether one partial specialization, P1, is at least as
4945/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004946///
Richard Smith26b86ea2016-12-31 21:41:23 +00004947/// \tparam TemplateLikeDecl The kind of P2, which must be a
4948/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004949/// \param T1 The injected-class-name of P1 (faked for a variable template).
4950/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004951template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004952static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004953 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004954 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004955 // C++ [temp.class.order]p1:
4956 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004957 // specialized as the second if, given the following rewrite to two
4958 // function templates, the first function template is at least as
4959 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004960 // templates (14.6.6.2):
4961 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004962 // first partial specialization and has a single function parameter
4963 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004964 // arguments of the first partial specialization, and
4965 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004966 // second partial specialization and has a single function parameter
4967 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004968 // arguments of the second partial specialization.
4969 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004970 // Rather than synthesize function templates, we merely perform the
4971 // equivalent partial ordering by performing deduction directly on
4972 // the template arguments of the class template partial
4973 // specializations. This computation is slightly simpler than the
4974 // general problem of function template partial ordering, because
4975 // class template partial specializations are more constrained. We
4976 // know that every template parameter is deducible from the class
4977 // template partial specialization's template arguments, for
4978 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004979 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004980
Richard Smith0da6dc42016-12-24 16:40:51 +00004981 // Determine whether P1 is at least as specialized as P2.
4982 Deduced.resize(P2->getTemplateParameters()->size());
4983 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4984 T2, T1, Info, Deduced, TDF_None,
4985 /*PartialOrdering=*/true))
4986 return false;
4987
4988 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4989 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004990 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4991 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004992 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4993 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004994 S, P2, /*PartialOrdering=*/true,
4995 TemplateArgumentList(TemplateArgumentList::OnStack,
4996 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004997 Deduced, Info))
4998 return false;
4999
5000 return true;
5001}
5002
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005003/// Returns the more specialized class template partial specialization
Richard Smith0da6dc42016-12-24 16:40:51 +00005004/// according to the rules of partial ordering of class template partial
5005/// specializations (C++ [temp.class.order]).
5006///
5007/// \param PS1 the first class template partial specialization
5008///
5009/// \param PS2 the second class template partial specialization
5010///
5011/// \returns the more specialized class template partial specialization. If
5012/// neither partial specialization is more specialized, returns NULL.
5013ClassTemplatePartialSpecializationDecl *
5014Sema::getMoreSpecializedPartialSpecialization(
5015 ClassTemplatePartialSpecializationDecl *PS1,
5016 ClassTemplatePartialSpecializationDecl *PS2,
5017 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00005018 QualType PT1 = PS1->getInjectedSpecializationType();
5019 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005020
Richard Smith0e617ec2016-12-27 07:56:27 +00005021 TemplateDeductionInfo Info(Loc);
5022 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5023 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005024
5025 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00005026 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005027
5028 return Better1 ? PS1 : PS2;
5029}
5030
Richard Smith0e617ec2016-12-27 07:56:27 +00005031bool Sema::isMoreSpecializedThanPrimary(
5032 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5033 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
5034 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
5035 QualType PartialT = Spec->getInjectedSpecializationType();
5036 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5037 return false;
5038 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5039 Info.clearSFINAEDiagnostic();
5040 return false;
5041 }
5042 return true;
5043}
5044
Larisse Voufo39a1e502013-08-06 01:03:05 +00005045VarTemplatePartialSpecializationDecl *
5046Sema::getMoreSpecializedPartialSpecialization(
5047 VarTemplatePartialSpecializationDecl *PS1,
5048 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00005049 // Pretend the variable template specializations are class template
5050 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00005051 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00005052 "the partial specializations being compared should specialize"
5053 " the same template.");
5054 TemplateName Name(PS1->getSpecializedTemplate());
5055 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5056 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00005057 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005058 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00005059 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005060
Richard Smith0e617ec2016-12-27 07:56:27 +00005061 TemplateDeductionInfo Info(Loc);
5062 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5063 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005064
Douglas Gregorbe999392009-09-15 16:23:51 +00005065 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00005066 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
Richard Smith0da6dc42016-12-24 16:40:51 +00005068 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00005069}
5070
Richard Smith0e617ec2016-12-27 07:56:27 +00005071bool Sema::isMoreSpecializedThanPrimary(
5072 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5073 TemplateDecl *Primary = Spec->getSpecializedTemplate();
5074 // FIXME: Cache the injected template arguments rather than recomputing
5075 // them for each partial specialization.
5076 SmallVector<TemplateArgument, 8> PrimaryArgs;
5077 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
5078 PrimaryArgs);
5079
5080 TemplateName CanonTemplate =
5081 Context.getCanonicalTemplateName(TemplateName(Primary));
5082 QualType PrimaryT = Context.getTemplateSpecializationType(
5083 CanonTemplate, PrimaryArgs);
5084 QualType PartialT = Context.getTemplateSpecializationType(
5085 CanonTemplate, Spec->getTemplateArgs().asArray());
5086 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5087 return false;
5088 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5089 Info.clearSFINAEDiagnostic();
5090 return false;
5091 }
5092 return true;
5093}
5094
Richard Smith26b86ea2016-12-31 21:41:23 +00005095bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5096 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5097 // C++1z [temp.arg.template]p4: (DR 150)
5098 // A template template-parameter P is at least as specialized as a
5099 // template template-argument A if, given the following rewrite to two
5100 // function templates...
5101
5102 // Rather than synthesize function templates, we merely perform the
5103 // equivalent partial ordering by performing deduction directly on
5104 // the template parameter lists of the template template parameters.
5105 //
5106 // Given an invented class template X with the template parameter list of
5107 // A (including default arguments):
5108 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5109 TemplateParameterList *A = AArg->getTemplateParameters();
5110
5111 // - Each function template has a single function parameter whose type is
5112 // a specialization of X with template arguments corresponding to the
5113 // template parameters from the respective function template
5114 SmallVector<TemplateArgument, 8> AArgs;
5115 Context.getInjectedTemplateArgs(A, AArgs);
5116
5117 // Check P's arguments against A's parameter list. This will fill in default
5118 // template arguments as needed. AArgs are already correct by construction.
5119 // We can't just use CheckTemplateIdType because that will expand alias
5120 // templates.
5121 SmallVector<TemplateArgument, 4> PArgs;
5122 {
5123 SFINAETrap Trap(*this);
5124
5125 Context.getInjectedTemplateArgs(P, PArgs);
5126 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
5127 for (unsigned I = 0, N = P->size(); I != N; ++I) {
5128 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5129 // expansions, to form an "as written" argument list.
5130 TemplateArgument Arg = PArgs[I];
5131 if (Arg.getKind() == TemplateArgument::Pack) {
5132 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
5133 Arg = *Arg.pack_begin();
5134 }
5135 PArgList.addArgument(getTrivialTemplateArgumentLoc(
5136 Arg, QualType(), P->getParam(I)->getLocation()));
5137 }
5138 PArgs.clear();
5139
5140 // C++1z [temp.arg.template]p3:
5141 // If the rewrite produces an invalid type, then P is not at least as
5142 // specialized as A.
5143 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
5144 Trap.hasErrorOccurred())
5145 return false;
5146 }
5147
5148 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
5149 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
5150
Richard Smith26b86ea2016-12-31 21:41:23 +00005151 // ... the function template corresponding to P is at least as specialized
5152 // as the function template corresponding to A according to the partial
5153 // ordering rules for function templates.
5154 TemplateDeductionInfo Info(Loc, A->getDepth());
5155 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5156}
5157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005158/// Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005159/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00005160static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005161MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005162 const Expr *E,
5163 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005164 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005165 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005166 // We can deduce from a pack expansion.
5167 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5168 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005169
Richard Smith34349002012-07-09 03:07:20 +00005170 // Skip through any implicit casts we added while type-checking, and any
5171 // substitutions performed by template alias expansion.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00005172 while (true) {
Richard Smith34349002012-07-09 03:07:20 +00005173 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
5174 E = ICE->getSubExpr();
5175 else if (const SubstNonTypeTemplateParmExpr *Subst =
5176 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
5177 E = Subst->getReplacement();
5178 else
5179 break;
5180 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005181
5182 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005183 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005184 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00005185 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00005186 return;
5187
Mike Stump11289f42009-09-09 15:08:12 +00005188 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00005189 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5190 if (!NTTP)
5191 return;
5192
Douglas Gregor21610382009-10-29 00:04:11 +00005193 if (NTTP->getDepth() == Depth)
5194 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00005195
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005196 // In C++17 mode, additional arguments may be deduced from the type of a
Richard Smith5f274382016-09-28 23:55:27 +00005197 // non-type argument.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005198 if (Ctx.getLangOpts().CPlusPlus17)
Richard Smith5f274382016-09-28 23:55:27 +00005199 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005200}
5201
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005202/// Mark the template parameters that are used by the given
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005203/// nested name specifier.
5204static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005205MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005206 NestedNameSpecifier *NNS,
5207 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005208 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005209 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005210 if (!NNS)
5211 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005213 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005214 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005215 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005216 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005217}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005218
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005219/// Mark the template parameters that are used by the given
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005220/// template name.
5221static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005222MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005223 TemplateName Name,
5224 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005225 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005226 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005227 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5228 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00005229 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5230 if (TTP->getDepth() == Depth)
5231 Used[TTP->getIndex()] = true;
5232 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005233 return;
5234 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005235
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005236 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005237 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005238 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005239 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005240 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005241 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005242}
5243
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005244/// Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005245/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005246static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005247MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005248 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005249 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005250 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005251 if (T.isNull())
5252 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005253
Douglas Gregor91772d12009-06-13 00:26:55 +00005254 // Non-dependent types have nothing deducible
5255 if (!T->isDependentType())
5256 return;
5257
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005258 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00005259 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005260 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005261 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005262 cast<PointerType>(T)->getPointeeType(),
5263 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005264 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005265 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005266 break;
5267
5268 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005269 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005270 cast<BlockPointerType>(T)->getPointeeType(),
5271 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005272 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005273 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005274 break;
5275
5276 case Type::LValueReference:
5277 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005278 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005279 cast<ReferenceType>(T)->getPointeeType(),
5280 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005281 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005282 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005283 break;
5284
5285 case Type::MemberPointer: {
5286 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005287 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005288 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005289 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005290 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005291 break;
5292 }
5293
5294 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005295 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005296 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00005297 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005298 // Fall through to check the element type
Galina Kistanova33399112017-06-03 06:35:06 +00005299 LLVM_FALLTHROUGH;
Douglas Gregor91772d12009-06-13 00:26:55 +00005300
5301 case Type::ConstantArray:
5302 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005303 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005304 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005305 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005306 break;
5307
5308 case Type::Vector:
5309 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005310 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005311 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005312 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005313 break;
5314
Erich Keanef702b022018-07-13 19:46:04 +00005315 case Type::DependentVector: {
5316 const auto *VecType = cast<DependentVectorType>(T);
5317 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5318 Depth, Used);
5319 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
5320 Used);
5321 break;
5322 }
Douglas Gregor758a8692009-06-17 21:51:59 +00005323 case Type::DependentSizedExtVector: {
5324 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005325 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005326 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005327 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005328 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005329 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005330 break;
5331 }
5332
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005333 case Type::DependentAddressSpace: {
5334 const DependentAddressSpaceType *DependentASType =
5335 cast<DependentAddressSpaceType>(T);
5336 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
5337 OnlyDeduced, Depth, Used);
5338 MarkUsedTemplateParameters(Ctx,
5339 DependentASType->getAddrSpaceExpr(),
5340 OnlyDeduced, Depth, Used);
5341 break;
5342 }
5343
Douglas Gregor91772d12009-06-13 00:26:55 +00005344 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005345 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005346 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5347 Used);
Richard Smithc379d1a2018-07-12 23:32:39 +00005348 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
5349 // C++17 [temp.deduct.type]p5:
5350 // The non-deduced contexts are: [...]
5351 // -- A function parameter pack that does not occur at the end of the
5352 // parameter-declaration-list.
5353 if (!OnlyDeduced || I + 1 == N ||
5354 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
5355 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
5356 Depth, Used);
5357 } else {
5358 // FIXME: C++17 [temp.deduct.call]p1:
5359 // When a function parameter pack appears in a non-deduced context,
5360 // the type of that pack is never deduced.
5361 //
5362 // We should also track a set of "never deduced" parameters, and
5363 // subtract that from the list of deduced parameters after marking.
5364 }
5365 }
Richard Smithcd198152017-06-07 21:46:22 +00005366 if (auto *E = Proto->getNoexceptExpr())
5367 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005368 break;
5369 }
5370
Douglas Gregor21610382009-10-29 00:04:11 +00005371 case Type::TemplateTypeParm: {
5372 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5373 if (TTP->getDepth() == Depth)
5374 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005375 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005376 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005377
Douglas Gregorfb322d82011-01-14 05:11:40 +00005378 case Type::SubstTemplateTypeParmPack: {
5379 const SubstTemplateTypeParmPackType *Subst
5380 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005381 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005382 QualType(Subst->getReplacedParameter(), 0),
5383 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005384 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005385 OnlyDeduced, Depth, Used);
5386 break;
5387 }
5388
John McCall2408e322010-04-27 00:57:59 +00005389 case Type::InjectedClassName:
5390 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005391 LLVM_FALLTHROUGH;
John McCall2408e322010-04-27 00:57:59 +00005392
Douglas Gregor91772d12009-06-13 00:26:55 +00005393 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005394 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005395 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005396 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005397 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398
Douglas Gregord0ad2942010-12-23 01:24:45 +00005399 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005400 // If the template argument list of P contains a pack expansion that is
5401 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005402 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005403 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005404 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005405 break;
5406
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005407 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005408 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005409 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005410 break;
5411 }
5412
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005413 case Type::Complex:
5414 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005415 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005416 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005417 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005418 break;
5419
Eli Friedman0dfb8892011-10-06 23:00:33 +00005420 case Type::Atomic:
5421 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005422 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005423 cast<AtomicType>(T)->getValueType(),
5424 OnlyDeduced, Depth, Used);
5425 break;
5426
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005427 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005428 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005429 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005430 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005431 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005432 break;
5433
John McCallc392f372010-06-11 00:33:02 +00005434 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005435 // C++14 [temp.deduct.type]p5:
5436 // The non-deduced contexts are:
5437 // -- The nested-name-specifier of a type that was specified using a
5438 // qualified-id
5439 //
5440 // C++14 [temp.deduct.type]p6:
5441 // When a type name is specified in a way that includes a non-deduced
5442 // context, all of the types that comprise that type name are also
5443 // non-deduced.
5444 if (OnlyDeduced)
5445 break;
5446
John McCallc392f372010-06-11 00:33:02 +00005447 const DependentTemplateSpecializationType *Spec
5448 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005449
Richard Smith50d5b972015-12-30 20:56:05 +00005450 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5451 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005452
John McCallc392f372010-06-11 00:33:02 +00005453 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005454 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005455 Used);
5456 break;
5457 }
5458
John McCallbd8d9bd2010-03-01 23:49:17 +00005459 case Type::TypeOf:
5460 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005461 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005462 cast<TypeOfType>(T)->getUnderlyingType(),
5463 OnlyDeduced, Depth, Used);
5464 break;
5465
5466 case Type::TypeOfExpr:
5467 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005468 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005469 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5470 OnlyDeduced, Depth, Used);
5471 break;
5472
5473 case Type::Decltype:
5474 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005475 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005476 cast<DecltypeType>(T)->getUnderlyingExpr(),
5477 OnlyDeduced, Depth, Used);
5478 break;
5479
Alexis Hunte852b102011-05-24 22:41:36 +00005480 case Type::UnaryTransform:
5481 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005482 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005483 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005484 OnlyDeduced, Depth, Used);
5485 break;
5486
Douglas Gregord2fa7662010-12-20 02:24:11 +00005487 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005488 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005489 cast<PackExpansionType>(T)->getPattern(),
5490 OnlyDeduced, Depth, Used);
5491 break;
5492
Richard Smith30482bc2011-02-20 03:19:35 +00005493 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00005494 case Type::DeducedTemplateSpecialization:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005495 MarkUsedTemplateParameters(Ctx,
Richard Smith600b5262017-01-26 20:40:47 +00005496 cast<DeducedType>(T)->getDeducedType(),
Richard Smith30482bc2011-02-20 03:19:35 +00005497 OnlyDeduced, Depth, Used);
Adrian Prantl4b490852017-12-19 22:21:48 +00005498 break;
Richard Smith30482bc2011-02-20 03:19:35 +00005499
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005500 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005501 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005502 case Type::VariableArray:
5503 case Type::FunctionNoProto:
5504 case Type::Record:
5505 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005506 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005507 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005508 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005509 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005510 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005511#define TYPE(Class, Base)
5512#define ABSTRACT_TYPE(Class, Base)
5513#define DEPENDENT_TYPE(Class, Base)
5514#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5515#include "clang/AST/TypeNodes.def"
5516 break;
5517 }
5518}
5519
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005520/// Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005521/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005522static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005523MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005524 const TemplateArgument &TemplateArg,
5525 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005526 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005527 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005528 switch (TemplateArg.getKind()) {
5529 case TemplateArgument::Null:
5530 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005531 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005532 break;
Mike Stump11289f42009-09-09 15:08:12 +00005533
Eli Friedmanb826a002012-09-26 02:36:12 +00005534 case TemplateArgument::NullPtr:
5535 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5536 Depth, Used);
5537 break;
5538
Douglas Gregor91772d12009-06-13 00:26:55 +00005539 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005540 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005541 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005542 break;
5543
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005544 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005545 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005546 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005547 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005548 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005549 break;
5550
5551 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005552 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005553 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005554 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555
Anders Carlssonbc343912009-06-15 17:04:53 +00005556 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005557 for (const auto &P : TemplateArg.pack_elements())
5558 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005559 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005560 }
5561}
5562
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005563/// Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005564/// template argument list.
5565///
5566/// \param TemplateArgs the template argument list from which template
5567/// parameters will be deduced.
5568///
James Dennett41725122012-06-22 10:16:05 +00005569/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005570/// to indicate when the corresponding template parameter will be
5571/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005572void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005573Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005574 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005575 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005576 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577 // If the template argument list of P contains a pack expansion that is not
5578 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005579 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005580 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005581 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005582 return;
5583
Douglas Gregor91772d12009-06-13 00:26:55 +00005584 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005585 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005586 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005587}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005588
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005589/// Marks all of the template parameters that will be deduced by a
Douglas Gregorce23bae2009-09-18 23:21:38 +00005590/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005591void Sema::MarkDeducedTemplateParameters(
5592 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5593 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005594 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005595 = FunctionTemplate->getTemplateParameters();
5596 Deduced.clear();
5597 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005598
Douglas Gregorce23bae2009-09-18 23:21:38 +00005599 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5600 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005601 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005602 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005603}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005604
Richard Smithf0393bf2017-02-16 04:22:56 +00005605bool hasDeducibleTemplateParameters(Sema &S,
5606 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregore65aacb2011-06-16 16:50:48 +00005607 QualType T) {
5608 if (!T->isDependentType())
5609 return false;
5610
Richard Smithf0393bf2017-02-16 04:22:56 +00005611 TemplateParameterList *TemplateParams
5612 = FunctionTemplate->getTemplateParameters();
5613 llvm::SmallBitVector Deduced(TemplateParams->size());
5614 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5615 Deduced);
Douglas Gregore65aacb2011-06-16 16:50:48 +00005616
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005617 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005618}