blob: 5c2fde43a6830a34da3ca56759e41d0c09c01c49 [file] [log] [blame]
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
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.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
John McCall19c1bfd2010-08-25 05:32:35 +000013#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000015#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000016#include "clang/AST/ASTLambda.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/StmtVisitor.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000025#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000026#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000027
28namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000029 using namespace sema;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000052 TDF_SkipNonDependent = 0x08,
53 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000054 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000055 TDF_TopLevelParameterTypeList = 0x10,
56 /// \brief Within template argument deduction from overload resolution per
57 /// C++ [over.over] allow matching function types that are compatible in
58 /// terms of noreturn and default calling convention adjustments.
59 TDF_InOverloadResolution = 0x20
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000060 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000061}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000062
Douglas Gregor55ca8f62009-06-04 00:03:07 +000063using namespace clang;
64
Douglas Gregor0a29a052010-03-26 05:50:28 +000065/// \brief Compare two APSInts, extending and switching the sign as
66/// necessary to compare their values regardless of underlying type.
67static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
68 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000069 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000070 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000071 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000072
73 // If there is a signedness mismatch, correct it.
74 if (X.isSigned() != Y.isSigned()) {
75 // If the signed value is negative, then the values cannot be the same.
76 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
77 return false;
78
79 Y.setIsSigned(true);
80 X.setIsSigned(true);
81 }
82
83 return X == Y;
84}
85
Douglas Gregor181aa4a2009-06-12 18:26:56 +000086static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000087DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000088 TemplateParameterList *TemplateParams,
89 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000090 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000091 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000092 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000093
Douglas Gregor7baabef2010-12-22 18:17:10 +000094static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +000095DeduceTemplateArgumentsByTypeMatch(Sema &S,
96 TemplateParameterList *TemplateParams,
97 QualType Param,
98 QualType Arg,
99 TemplateDeductionInfo &Info,
100 SmallVectorImpl<DeducedTemplateArgument> &
101 Deduced,
102 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000103 bool PartialOrdering = false,
104 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000105
106static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000107DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000108 ArrayRef<TemplateArgument> Params,
109 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000110 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000111 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
112 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000113
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000114/// \brief If the given expression is of a form that permits the deduction
115/// of a non-type template parameter, return the declaration of that
116/// non-type template parameter.
117static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000118 // If we are within an alias template, the expression may have undergone
119 // any number of parameter substitutions already.
120 while (1) {
121 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
122 E = IC->getSubExpr();
123 else if (SubstNonTypeTemplateParmExpr *Subst =
124 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
125 E = Subst->getReplacement();
126 else
127 break;
128 }
Mike Stump11289f42009-09-09 15:08:12 +0000129
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000130 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
131 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000132
Craig Topperc3ec1492014-05-26 06:22:03 +0000133 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000134}
135
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000136/// \brief Determine whether two declaration pointers refer to the same
137/// declaration.
138static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000139 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
140 X = NX->getUnderlyingDecl();
141 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
142 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000143
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000144 return X->getCanonicalDecl() == Y->getCanonicalDecl();
145}
146
147/// \brief Verify that the given, deduced template arguments are compatible.
148///
149/// \returns The deduced template argument, or a NULL template argument if
150/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000151static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000152checkDeducedTemplateArguments(ASTContext &Context,
153 const DeducedTemplateArgument &X,
154 const DeducedTemplateArgument &Y) {
155 // We have no deduction for one or both of the arguments; they're compatible.
156 if (X.isNull())
157 return Y;
158 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000159 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000160
Richard Smith593d6a12016-12-23 01:30:39 +0000161 // If we have two non-type template argument values deduced for the same
162 // parameter, they must both match the type of the parameter, and thus must
163 // match each other's type. As we're only keeping one of them, we must check
164 // for that now. The exception is that if either was deduced from an array
165 // bound, the type is permitted to differ.
166 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
167 QualType XType = X.getNonTypeTemplateArgumentType();
168 if (!XType.isNull()) {
169 QualType YType = Y.getNonTypeTemplateArgumentType();
170 if (YType.isNull() || !Context.hasSameType(XType, YType))
171 return DeducedTemplateArgument();
172 }
173 }
174
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000175 switch (X.getKind()) {
176 case TemplateArgument::Null:
177 llvm_unreachable("Non-deduced template arguments handled above");
178
179 case TemplateArgument::Type:
180 // If two template type arguments have the same type, they're compatible.
181 if (Y.getKind() == TemplateArgument::Type &&
182 Context.hasSameType(X.getAsType(), Y.getAsType()))
183 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184
Richard Smith5f274382016-09-28 23:55:27 +0000185 // If one of the two arguments was deduced from an array bound, the other
186 // supersedes it.
187 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
188 return X.wasDeducedFromArrayBound() ? Y : X;
189
190 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000191 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000192
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000193 case TemplateArgument::Integral:
194 // If we deduced a constant in one case and either a dependent expression or
195 // declaration in another case, keep the integral constant.
196 // If both are integral constants with the same value, keep that value.
197 if (Y.getKind() == TemplateArgument::Expression ||
198 Y.getKind() == TemplateArgument::Declaration ||
199 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000200 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000201 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000202
203 // All other combinations are incompatible.
204 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000205
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000206 case TemplateArgument::Template:
207 if (Y.getKind() == TemplateArgument::Template &&
208 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
209 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000210
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000211 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000213
214 case TemplateArgument::TemplateExpansion:
215 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000216 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000217 Y.getAsTemplateOrTemplatePattern()))
218 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000220 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000222
Richard Smith593d6a12016-12-23 01:30:39 +0000223 case TemplateArgument::Expression: {
224 if (Y.getKind() != TemplateArgument::Expression)
225 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000226
Richard Smith593d6a12016-12-23 01:30:39 +0000227 // Compare the expressions for equality
228 llvm::FoldingSetNodeID ID1, ID2;
229 X.getAsExpr()->Profile(ID1, Context, true);
230 Y.getAsExpr()->Profile(ID2, Context, true);
231 if (ID1 == ID2)
232 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000233
Richard Smith593d6a12016-12-23 01:30:39 +0000234 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000235 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000238 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000239 assert(!X.wasDeducedFromArrayBound());
240
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000241 // If we deduced a declaration and a dependent expression, keep the
242 // declaration.
243 if (Y.getKind() == TemplateArgument::Expression)
244 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000245
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000246 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000247 // integral constant and whichever type did not come from an array
248 // bound.
249 if (Y.getKind() == TemplateArgument::Integral) {
250 if (Y.wasDeducedFromArrayBound())
251 return TemplateArgument(Context, Y.getAsIntegral(),
252 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000253 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000256 // If we deduced two declarations, make sure they they refer to the
257 // same declaration.
258 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000259 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000260 return X;
261
262 // All other combinations are incompatible.
263 return DeducedTemplateArgument();
264
265 case TemplateArgument::NullPtr:
266 // If we deduced a null pointer and a dependent expression, keep the
267 // null pointer.
268 if (Y.getKind() == TemplateArgument::Expression)
269 return X;
270
271 // If we deduced a null pointer and an integral constant, keep the
272 // integral constant.
273 if (Y.getKind() == TemplateArgument::Integral)
274 return Y;
275
Richard Smith593d6a12016-12-23 01:30:39 +0000276 // If we deduced two null pointers, they are the same.
277 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000278 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000280 // All other combinations are incompatible.
281 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000283 case TemplateArgument::Pack:
284 if (Y.getKind() != TemplateArgument::Pack ||
285 X.pack_size() != Y.pack_size())
286 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
288 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000289 XAEnd = X.pack_end(),
290 YA = Y.pack_begin();
291 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000292 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000293 if (checkDeducedTemplateArguments(Context,
294 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000295 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
296 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000297 return DeducedTemplateArgument();
298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000299
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000300 return X;
301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000302
David Blaikiee4d798f2012-01-20 21:50:17 +0000303 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000304}
305
Mike Stump11289f42009-09-09 15:08:12 +0000306/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000307/// from the given integral constant.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000308static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000309 Sema &S, TemplateParameterList *TemplateParams,
310 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000311 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
312 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000313 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000314 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000315
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000316 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
317 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000318 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000319 Deduced[NTTP->getIndex()],
320 NewDeduced);
321 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000322 Info.Param = NTTP;
323 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000324 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000325 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000328 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000329 return S.getLangOpts().CPlusPlus1z
330 ? DeduceTemplateArgumentsByTypeMatch(
331 S, TemplateParams, NTTP->getType(), ValueType, Info, Deduced,
332 TDF_ParamWithReferenceType | TDF_SkipNonDependent,
333 /*PartialOrdering=*/false,
334 /*ArrayBound=*/DeducedFromArrayBound)
335 : Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000336}
337
Mike Stump11289f42009-09-09 15:08:12 +0000338/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000339/// from the given null pointer template argument type.
340static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000341 Sema &S, TemplateParameterList *TemplateParams,
342 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000343 TemplateDeductionInfo &Info,
344 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
345 Expr *Value =
346 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
347 S.Context.NullPtrTy, NTTP->getLocation()),
348 NullPtrType, CK_NullToPointer)
349 .get();
350 DeducedTemplateArgument NewDeduced(Value);
351 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
352 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
353
354 if (Result.isNull()) {
355 Info.Param = NTTP;
356 Info.FirstArg = Deduced[NTTP->getIndex()];
357 Info.SecondArg = NewDeduced;
358 return Sema::TDK_Inconsistent;
359 }
360
361 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000362 return S.getLangOpts().CPlusPlus1z
363 ? DeduceTemplateArgumentsByTypeMatch(
364 S, TemplateParams, NTTP->getType(), Value->getType(), Info,
365 Deduced, TDF_ParamWithReferenceType | TDF_SkipNonDependent)
366 : Sema::TDK_Success;
Richard Smith38175a22016-09-28 22:08:38 +0000367}
368
369/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000370/// from the given type- or value-dependent expression.
371///
372/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000373static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000374DeduceNonTypeTemplateArgument(Sema &S,
Richard Smith5f274382016-09-28 23:55:27 +0000375 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000376 NonTypeTemplateParmDecl *NTTP,
377 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000378 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000379 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000380 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000381 "Cannot deduce non-type template argument with depth > 0");
382 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
383 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000384
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000385 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
387 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000388 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000390 if (Result.isNull()) {
391 Info.Param = NTTP;
392 Info.FirstArg = Deduced[NTTP->getIndex()];
393 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000396
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000397 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000398 return S.getLangOpts().CPlusPlus1z
399 ? DeduceTemplateArgumentsByTypeMatch(
400 S, TemplateParams, NTTP->getType(), Value->getType(), Info,
401 Deduced, TDF_ParamWithReferenceType | TDF_SkipNonDependent)
402 : Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000403}
404
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000405/// \brief Deduce the value of the given non-type template parameter
406/// from the given declaration.
407///
408/// \returns true if deduction succeeded, false otherwise.
409static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000410DeduceNonTypeTemplateArgument(Sema &S,
Richard Smith5f274382016-09-28 23:55:27 +0000411 TemplateParameterList *TemplateParams,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000412 NonTypeTemplateParmDecl *NTTP,
Richard Smith5f274382016-09-28 23:55:27 +0000413 ValueDecl *D, QualType T,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000414 TemplateDeductionInfo &Info,
415 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000416 assert(NTTP->getDepth() == 0 &&
417 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418
Craig Topperc3ec1492014-05-26 06:22:03 +0000419 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000420 TemplateArgument New(D, T);
Eli Friedmanb826a002012-09-26 02:36:12 +0000421 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000422 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000423 Deduced[NTTP->getIndex()],
424 NewDeduced);
425 if (Result.isNull()) {
426 Info.Param = NTTP;
427 Info.FirstArg = Deduced[NTTP->getIndex()];
428 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000429 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000431
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000432 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000433 return S.getLangOpts().CPlusPlus1z
434 ? DeduceTemplateArgumentsByTypeMatch(
435 S, TemplateParams, NTTP->getType(), T, Info, Deduced,
436 TDF_ParamWithReferenceType | TDF_SkipNonDependent)
437 : Sema::TDK_Success;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000438}
439
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000440static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000441DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000442 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000443 TemplateName Param,
444 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000445 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000446 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000447 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000448 if (!ParamDecl) {
449 // The parameter type is dependent and is not a template template parameter,
450 // so there is nothing that we can deduce.
451 return Sema::TDK_Success;
452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453
Douglas Gregoradee3e32009-11-11 23:06:43 +0000454 if (TemplateTemplateParmDecl *TempParam
455 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000456 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000457 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000458 Deduced[TempParam->getIndex()],
459 NewDeduced);
460 if (Result.isNull()) {
461 Info.Param = TempParam;
462 Info.FirstArg = Deduced[TempParam->getIndex()];
463 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000464 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000466
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000467 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
Douglas Gregoradee3e32009-11-11 23:06:43 +0000471 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000472 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000473 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000474
Douglas Gregoradee3e32009-11-11 23:06:43 +0000475 // Mismatch of non-dependent template parameter to argument.
476 Info.FirstArg = TemplateArgument(Param);
477 Info.SecondArg = TemplateArgument(Arg);
478 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000479}
480
Mike Stump11289f42009-09-09 15:08:12 +0000481/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000482/// type (which is a template-id) with the template argument type.
483///
Chandler Carruthc1263112010-02-07 21:33:28 +0000484/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000485///
486/// \param TemplateParams the template parameters that we are deducing
487///
488/// \param Param the parameter type
489///
490/// \param Arg the argument type
491///
492/// \param Info information about the template argument deduction itself
493///
494/// \param Deduced the deduced template arguments
495///
496/// \returns the result of template argument deduction so far. Note that a
497/// "success" result means that template argument deduction has not yet failed,
498/// but it may still fail, later, for other reasons.
499static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000500DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000501 TemplateParameterList *TemplateParams,
502 const TemplateSpecializationType *Param,
503 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000504 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000505 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000506 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000507
Douglas Gregore81f3e72009-07-07 23:09:34 +0000508 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000510 = dyn_cast<TemplateSpecializationType>(Arg)) {
511 // Perform template argument deduction for the template name.
512 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000513 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000514 Param->getTemplateName(),
515 SpecArg->getTemplateName(),
516 Info, Deduced))
517 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000518
Mike Stump11289f42009-09-09 15:08:12 +0000519
Douglas Gregore81f3e72009-07-07 23:09:34 +0000520 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000521 // argument. Ignore any missing/extra arguments, since they could be
522 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000523 return DeduceTemplateArguments(S, TemplateParams,
524 Param->template_arguments(),
525 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000526 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000527 }
Mike Stump11289f42009-09-09 15:08:12 +0000528
Douglas Gregore81f3e72009-07-07 23:09:34 +0000529 // If the argument type is a class template specialization, we
530 // perform template argument deduction using its template
531 // arguments.
532 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000533 if (!RecordArg) {
534 Info.FirstArg = TemplateArgument(QualType(Param, 0));
535 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000536 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000537 }
Mike Stump11289f42009-09-09 15:08:12 +0000538
539 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000540 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000541 if (!SpecArg) {
542 Info.FirstArg = TemplateArgument(QualType(Param, 0));
543 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000544 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000545 }
Mike Stump11289f42009-09-09 15:08:12 +0000546
Douglas Gregore81f3e72009-07-07 23:09:34 +0000547 // Perform template argument deduction for the template name.
548 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000549 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000550 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000551 Param->getTemplateName(),
552 TemplateName(SpecArg->getSpecializedTemplate()),
553 Info, Deduced))
554 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000555
Douglas Gregor7baabef2010-12-22 18:17:10 +0000556 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000557 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
558 SpecArg->getTemplateArgs().asArray(), Info,
559 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000560}
561
John McCall08569062010-08-28 22:14:41 +0000562/// \brief Determines whether the given type is an opaque type that
563/// might be more qualified when instantiated.
564static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
565 switch (T->getTypeClass()) {
566 case Type::TypeOfExpr:
567 case Type::TypeOf:
568 case Type::DependentName:
569 case Type::Decltype:
570 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000571 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000572 return true;
573
574 case Type::ConstantArray:
575 case Type::IncompleteArray:
576 case Type::VariableArray:
577 case Type::DependentSizedArray:
578 return IsPossiblyOpaquelyQualifiedType(
579 cast<ArrayType>(T)->getElementType());
580
581 default:
582 return false;
583 }
584}
585
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000586/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000588getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000589 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
590 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregor5499af42011-01-05 23:12:31 +0000592 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
593 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594
Douglas Gregor5499af42011-01-05 23:12:31 +0000595 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
596 return std::make_pair(TTP->getDepth(), TTP->getIndex());
597}
598
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000599/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000601getDepthAndIndex(UnexpandedParameterPack UPP) {
602 if (const TemplateTypeParmType *TTP
603 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
604 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000606 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
607}
608
Douglas Gregor5499af42011-01-05 23:12:31 +0000609/// \brief Helper function to build a TemplateParameter when we don't
610/// know its type statically.
611static TemplateParameter makeTemplateParameter(Decl *D) {
612 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
613 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000614 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000615 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor5499af42011-01-05 23:12:31 +0000617 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
618}
619
Richard Smith0a80d572014-05-29 01:12:14 +0000620/// A pack that we're currently deducing.
621struct clang::DeducedPack {
622 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000623
Richard Smith0a80d572014-05-29 01:12:14 +0000624 // The index of the pack.
625 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Richard Smith0a80d572014-05-29 01:12:14 +0000627 // The old value of the pack before we started deducing it.
628 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000629
Richard Smith0a80d572014-05-29 01:12:14 +0000630 // A deferred value of this pack from an inner deduction, that couldn't be
631 // deduced because this deduction hadn't happened yet.
632 DeducedTemplateArgument DeferredDeduction;
633
634 // The new value of the pack.
635 SmallVector<DeducedTemplateArgument, 4> New;
636
637 // The outer deduction for this pack, if any.
638 DeducedPack *Outer;
639};
640
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000641namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000642/// A scope in which we're performing pack deduction.
643class PackDeductionScope {
644public:
645 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
646 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
647 TemplateDeductionInfo &Info, TemplateArgument Pattern)
648 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
649 // Compute the set of template parameter indices that correspond to
650 // parameter packs expanded by the pack expansion.
651 {
652 llvm::SmallBitVector SawIndices(TemplateParams->size());
653 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
654 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
655 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
656 unsigned Depth, Index;
657 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
658 if (Depth == 0 && !SawIndices[Index]) {
659 SawIndices[Index] = true;
660
661 // Save the deduced template argument for the parameter pack expanded
662 // by this pack expansion, then clear out the deduction.
663 DeducedPack Pack(Index);
664 Pack.Saved = Deduced[Index];
665 Deduced[Index] = TemplateArgument();
666
667 Packs.push_back(Pack);
668 }
669 }
670 }
671 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
672
673 for (auto &Pack : Packs) {
674 if (Info.PendingDeducedPacks.size() > Pack.Index)
675 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
676 else
677 Info.PendingDeducedPacks.resize(Pack.Index + 1);
678 Info.PendingDeducedPacks[Pack.Index] = &Pack;
679
680 if (S.CurrentInstantiationScope) {
681 // If the template argument pack was explicitly specified, add that to
682 // the set of deduced arguments.
683 const TemplateArgument *ExplicitArgs;
684 unsigned NumExplicitArgs;
685 NamedDecl *PartiallySubstitutedPack =
686 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
687 &ExplicitArgs, &NumExplicitArgs);
688 if (PartiallySubstitutedPack &&
689 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
690 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
691 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000692 }
693 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000694
Richard Smith0a80d572014-05-29 01:12:14 +0000695 ~PackDeductionScope() {
696 for (auto &Pack : Packs)
697 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000698 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
Richard Smith0a80d572014-05-29 01:12:14 +0000700 /// Move to deducing the next element in each pack that is being deduced.
701 void nextPackElement() {
702 // Capture the deduced template arguments for each parameter pack expanded
703 // by this pack expansion, add them to the list of arguments we've deduced
704 // for that pack, then clear out the deduced argument.
705 for (auto &Pack : Packs) {
706 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
707 if (!DeducedArg.isNull()) {
708 Pack.New.push_back(DeducedArg);
709 DeducedArg = DeducedTemplateArgument();
710 }
711 }
712 }
713
714 /// \brief Finish template argument deduction for a set of argument packs,
715 /// producing the argument packs and checking for consistency with prior
716 /// deductions.
717 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
718 // Build argument packs for each of the parameter packs expanded by this
719 // pack expansion.
720 for (auto &Pack : Packs) {
721 // Put back the old value for this pack.
722 Deduced[Pack.Index] = Pack.Saved;
723
724 // Build or find a new value for this pack.
725 DeducedTemplateArgument NewPack;
726 if (HasAnyArguments && Pack.New.empty()) {
727 if (Pack.DeferredDeduction.isNull()) {
728 // We were not able to deduce anything for this parameter pack
729 // (because it only appeared in non-deduced contexts), so just
730 // restore the saved argument pack.
731 continue;
732 }
733
734 NewPack = Pack.DeferredDeduction;
735 Pack.DeferredDeduction = TemplateArgument();
736 } else if (Pack.New.empty()) {
737 // If we deduced an empty argument pack, create it now.
738 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
739 } else {
740 TemplateArgument *ArgumentPack =
741 new (S.Context) TemplateArgument[Pack.New.size()];
742 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
743 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000744 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000745 Pack.New[0].wasDeducedFromArrayBound());
746 }
747
748 // Pick where we're going to put the merged pack.
749 DeducedTemplateArgument *Loc;
750 if (Pack.Outer) {
751 if (Pack.Outer->DeferredDeduction.isNull()) {
752 // Defer checking this pack until we have a complete pack to compare
753 // it against.
754 Pack.Outer->DeferredDeduction = NewPack;
755 continue;
756 }
757 Loc = &Pack.Outer->DeferredDeduction;
758 } else {
759 Loc = &Deduced[Pack.Index];
760 }
761
762 // Check the new pack matches any previous value.
763 DeducedTemplateArgument OldPack = *Loc;
764 DeducedTemplateArgument Result =
765 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
766
767 // If we deferred a deduction of this pack, check that one now too.
768 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
769 OldPack = Result;
770 NewPack = Pack.DeferredDeduction;
771 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
772 }
773
774 if (Result.isNull()) {
775 Info.Param =
776 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
777 Info.FirstArg = OldPack;
778 Info.SecondArg = NewPack;
779 return Sema::TDK_Inconsistent;
780 }
781
782 *Loc = Result;
783 }
784
785 return Sema::TDK_Success;
786 }
787
788private:
789 Sema &S;
790 TemplateParameterList *TemplateParams;
791 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
792 TemplateDeductionInfo &Info;
793
794 SmallVector<DeducedPack, 2> Packs;
795};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000796} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000797
Douglas Gregor5499af42011-01-05 23:12:31 +0000798/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799/// types to the list of argument types, as in the parameter-type-lists of
800/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000801///
802/// \param S The semantic analysis object within which we are deducing
803///
804/// \param TemplateParams The template parameters that we are deducing
805///
806/// \param Params The list of parameter types
807///
808/// \param NumParams The number of types in \c Params
809///
810/// \param Args The list of argument types
811///
812/// \param NumArgs The number of types in \c Args
813///
814/// \param Info information about the template argument deduction itself
815///
816/// \param Deduced the deduced template arguments
817///
818/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
819/// how template argument deduction is performed.
820///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000821/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000823/// (C++0x [temp.deduct.partial]).
824///
Douglas Gregor5499af42011-01-05 23:12:31 +0000825/// \returns the result of template argument deduction so far. Note that a
826/// "success" result means that template argument deduction has not yet failed,
827/// but it may still fail, later, for other reasons.
828static Sema::TemplateDeductionResult
829DeduceTemplateArguments(Sema &S,
830 TemplateParameterList *TemplateParams,
831 const QualType *Params, unsigned NumParams,
832 const QualType *Args, unsigned NumArgs,
833 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000834 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000835 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000836 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000837 // Fast-path check to see if we have too many/too few arguments.
838 if (NumParams != NumArgs &&
839 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
840 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000841 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844 // Similarly, if P has a form that contains (T), then each parameter type
845 // Pi of the respective parameter-type- list of P is compared with the
846 // corresponding parameter type Ai of the corresponding parameter-type-list
847 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000848 unsigned ArgIdx = 0, ParamIdx = 0;
849 for (; ParamIdx != NumParams; ++ParamIdx) {
850 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000852 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
853 if (!Expansion) {
854 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855
Douglas Gregor5499af42011-01-05 23:12:31 +0000856 // Make sure we have an argument.
857 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000858 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000860 if (isa<PackExpansionType>(Args[ArgIdx])) {
861 // C++0x [temp.deduct.type]p22:
862 // If the original function parameter associated with A is a function
863 // parameter pack and the function parameter associated with P is not
864 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000865 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor5499af42011-01-05 23:12:31 +0000868 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000869 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
870 Params[ParamIdx], Args[ArgIdx],
871 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000872 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000873 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874
Douglas Gregor5499af42011-01-05 23:12:31 +0000875 ++ArgIdx;
876 continue;
877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000879 // C++0x [temp.deduct.type]p5:
880 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000882 // parameter-declaration-clause.
883 if (ParamIdx + 1 < NumParams)
884 return Sema::TDK_Success;
885
Douglas Gregor5499af42011-01-05 23:12:31 +0000886 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000888 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000890 // comparison deduces template arguments for subsequent positions in the
891 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000892
Douglas Gregor5499af42011-01-05 23:12:31 +0000893 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000894 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000895
Douglas Gregor5499af42011-01-05 23:12:31 +0000896 bool HasAnyArguments = false;
897 for (; ArgIdx < NumArgs; ++ArgIdx) {
898 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000899
Douglas Gregor5499af42011-01-05 23:12:31 +0000900 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000902 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
903 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000904 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000905 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000906
Richard Smith0a80d572014-05-29 01:12:14 +0000907 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909
Douglas Gregor5499af42011-01-05 23:12:31 +0000910 // Build argument packs for each of the parameter packs expanded by this
911 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000912 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000914 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000915
Douglas Gregor5499af42011-01-05 23:12:31 +0000916 // Make sure we don't have any extra arguments.
917 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000918 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000919
Douglas Gregor5499af42011-01-05 23:12:31 +0000920 return Sema::TDK_Success;
921}
922
Douglas Gregor1d684c22011-04-28 00:56:09 +0000923/// \brief Determine whether the parameter has qualifiers that are either
924/// inconsistent with or a superset of the argument's qualifiers.
925static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
926 QualType ArgType) {
927 Qualifiers ParamQs = ParamType.getQualifiers();
928 Qualifiers ArgQs = ArgType.getQualifiers();
929
930 if (ParamQs == ArgQs)
931 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000932
Douglas Gregor1d684c22011-04-28 00:56:09 +0000933 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000934 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000935 ParamQs.hasObjCGCAttr())
936 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000937
Douglas Gregor1d684c22011-04-28 00:56:09 +0000938 // Mismatched (but not missing) address spaces.
939 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
940 ParamQs.hasAddressSpace())
941 return true;
942
John McCall31168b02011-06-15 23:02:42 +0000943 // Mismatched (but not missing) Objective-C lifetime qualifiers.
944 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
945 ParamQs.hasObjCLifetime())
946 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000947
Douglas Gregor1d684c22011-04-28 00:56:09 +0000948 // CVR qualifier superset.
949 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
950 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
951 == ParamQs.getCVRQualifiers());
952}
953
Douglas Gregor19a41f12013-04-17 08:45:07 +0000954/// \brief Compare types for equality with respect to possibly compatible
955/// function types (noreturn adjustment, implicit calling conventions). If any
956/// of parameter and argument is not a function, just perform type comparison.
957///
958/// \param Param the template parameter type.
959///
960/// \param Arg the argument type.
961bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
962 CanQualType Arg) {
963 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
964 *ArgFunction = Arg->getAs<FunctionType>();
965
966 // Just compare if not functions.
967 if (!ParamFunction || !ArgFunction)
968 return Param == Arg;
969
Richard Smith3c4f8d22016-10-16 17:54:23 +0000970 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000971 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000972 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000973 return Arg == Context.getCanonicalType(AdjustedParam);
974
975 // FIXME: Compatible calling conventions.
976
977 return Param == Arg;
978}
979
Douglas Gregorcceb9752009-06-26 18:27:22 +0000980/// \brief Deduce the template arguments by comparing the parameter type and
981/// the argument type (C++ [temp.deduct.type]).
982///
Chandler Carruthc1263112010-02-07 21:33:28 +0000983/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000984///
985/// \param TemplateParams the template parameters that we are deducing
986///
987/// \param ParamIn the parameter type
988///
989/// \param ArgIn the argument type
990///
991/// \param Info information about the template argument deduction itself
992///
993/// \param Deduced the deduced template arguments
994///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000995/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000996/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000997///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000998/// \param PartialOrdering Whether we're performing template argument deduction
999/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1000///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001001/// \returns the result of template argument deduction so far. Note that a
1002/// "success" result means that template argument deduction has not yet failed,
1003/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001004static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001005DeduceTemplateArgumentsByTypeMatch(Sema &S,
1006 TemplateParameterList *TemplateParams,
1007 QualType ParamIn, QualType ArgIn,
1008 TemplateDeductionInfo &Info,
1009 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1010 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001011 bool PartialOrdering,
1012 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001013 // We only want to look at the canonical types, since typedefs and
1014 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001015 QualType Param = S.Context.getCanonicalType(ParamIn);
1016 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001017
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001018 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001020 if (const PackExpansionType *ArgExpansion
1021 = dyn_cast<PackExpansionType>(Arg))
1022 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001023
Douglas Gregorb837ea42011-01-11 17:34:58 +00001024 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001025 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026 // Before the partial ordering is done, certain transformations are
1027 // performed on the types used for partial ordering:
1028 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001029 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1030 if (ParamRef)
1031 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001032
Douglas Gregorb837ea42011-01-11 17:34:58 +00001033 // - If A is a reference type, A is replaced by the type referred to.
1034 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1035 if (ArgRef)
1036 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037
Richard Smithed563c22015-02-20 04:45:22 +00001038 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1039 // C++11 [temp.deduct.partial]p9:
1040 // If, for a given type, deduction succeeds in both directions (i.e.,
1041 // the types are identical after the transformations above) and both
1042 // P and A were reference types [...]:
1043 // - if [one type] was an lvalue reference and [the other type] was
1044 // not, [the other type] is not considered to be at least as
1045 // specialized as [the first type]
1046 // - if [one type] is more cv-qualified than [the other type],
1047 // [the other type] is not considered to be at least as specialized
1048 // as [the first type]
1049 // Objective-C ARC adds:
1050 // - [one type] has non-trivial lifetime, [the other type] has
1051 // __unsafe_unretained lifetime, and the types are otherwise
1052 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001053 //
Richard Smithed563c22015-02-20 04:45:22 +00001054 // A is "considered to be at least as specialized" as P iff deduction
1055 // succeeds, so we model this as a deduction failure. Note that
1056 // [the first type] is P and [the other type] is A here; the standard
1057 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001058 Qualifiers ParamQuals = Param.getQualifiers();
1059 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001060 if ((ParamRef->isLValueReferenceType() &&
1061 !ArgRef->isLValueReferenceType()) ||
1062 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1063 (ParamQuals.hasNonTrivialObjCLifetime() &&
1064 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1065 ParamQuals.withoutObjCLifetime() ==
1066 ArgQuals.withoutObjCLifetime())) {
1067 Info.FirstArg = TemplateArgument(ParamIn);
1068 Info.SecondArg = TemplateArgument(ArgIn);
1069 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001070 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001071 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072
Richard Smithed563c22015-02-20 04:45:22 +00001073 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001074 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001075 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001076 // version of P.
1077 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001078 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001079 // version of A.
1080 Arg = Arg.getUnqualifiedType();
1081 } else {
1082 // C++0x [temp.deduct.call]p4 bullet 1:
1083 // - If the original P is a reference type, the deduced A (i.e., the type
1084 // referred to by the reference) can be more cv-qualified than the
1085 // transformed A.
1086 if (TDF & TDF_ParamWithReferenceType) {
1087 Qualifiers Quals;
1088 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1089 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001090 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001091 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093
Douglas Gregor85f240c2011-01-25 17:19:08 +00001094 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1095 // C++0x [temp.deduct.type]p10:
1096 // If P and A are function types that originated from deduction when
1097 // taking the address of a function template (14.8.2.2) or when deducing
1098 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001099 // Ai are parameters of the top-level parameter-type-list of P and A,
1100 // respectively, Pi is adjusted if it is an rvalue reference to a
1101 // cv-unqualified template parameter and Ai is an lvalue reference, in
1102 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001103 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1104 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001105 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001106 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107
Douglas Gregor85f240c2011-01-25 17:19:08 +00001108 if (const RValueReferenceType *ParamRef
1109 = Param->getAs<RValueReferenceType>()) {
1110 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1111 !ParamRef->getPointeeType().getQualifiers())
1112 if (Arg->isLValueReferenceType())
1113 Param = ParamRef->getPointeeType();
1114 }
1115 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001117
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001118 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001119 // A template type argument T, a template template argument TT or a
1120 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001121 // the following forms:
1122 //
1123 // T
1124 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001125 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001126 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001127 // Just skip any attempts to deduce from a placeholder type.
1128 if (Arg->isPlaceholderType())
1129 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001130
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001131 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001132 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001133
Douglas Gregor60454822009-07-22 20:02:25 +00001134 // If the argument type is an array type, move the qualifiers up to the
1135 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001136 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001137 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001138 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001139 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001140 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001141 RecanonicalizeArg = true;
1142 }
1143 }
Mike Stump11289f42009-09-09 15:08:12 +00001144
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001145 // The argument type can not be less qualified than the parameter
1146 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001147 if (!(TDF & TDF_IgnoreQualifiers) &&
1148 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001149 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001150 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001151 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001152 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001153 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001154
1155 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001156 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001157 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001158
Douglas Gregor1d684c22011-04-28 00:56:09 +00001159 // Remove any qualifiers on the parameter from the deduced type.
1160 // We checked the qualifiers for consistency above.
1161 Qualifiers DeducedQs = DeducedType.getQualifiers();
1162 Qualifiers ParamQs = Param.getQualifiers();
1163 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1164 if (ParamQs.hasObjCGCAttr())
1165 DeducedQs.removeObjCGCAttr();
1166 if (ParamQs.hasAddressSpace())
1167 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001168 if (ParamQs.hasObjCLifetime())
1169 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001170
Douglas Gregore46db902011-06-17 22:11:49 +00001171 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001172 // If template deduction would produce a lifetime qualifier on a type
1173 // that is not a lifetime type, template argument deduction fails.
1174 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1175 !DeducedType->isDependentType()) {
1176 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1177 Info.FirstArg = TemplateArgument(Param);
1178 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001179 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001180 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001181
Douglas Gregora4f2b432011-07-26 14:53:44 +00001182 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001183 // If template deduction would produce an argument type with lifetime type
1184 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001185 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001186 DeducedType->isObjCLifetimeType() &&
1187 !DeducedQs.hasObjCLifetime())
1188 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001189
Douglas Gregor1d684c22011-04-28 00:56:09 +00001190 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1191 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001192
Douglas Gregord6605db2009-07-22 21:30:48 +00001193 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001194 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001195
Richard Smith5f274382016-09-28 23:55:27 +00001196 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001197 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001198 Deduced[Index],
1199 NewDeduced);
1200 if (Result.isNull()) {
1201 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1202 Info.FirstArg = Deduced[Index];
1203 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001204 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001206
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001207 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001208 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001209 }
1210
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001211 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001212 Info.FirstArg = TemplateArgument(ParamIn);
1213 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001214
Douglas Gregorfb322d82011-01-14 05:11:40 +00001215 // If the parameter is an already-substituted template parameter
1216 // pack, do nothing: we don't know which of its arguments to look
1217 // at, so we have to wait until all of the parameter packs in this
1218 // expansion have arguments.
1219 if (isa<SubstTemplateTypeParmPackType>(Param))
1220 return Sema::TDK_Success;
1221
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001222 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001223 CanQualType CanParam = S.Context.getCanonicalType(Param);
1224 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001225 if (!(TDF & TDF_IgnoreQualifiers)) {
1226 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001227 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001228 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001229 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001230 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001231 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001232 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001233
Douglas Gregor194ea692012-03-11 03:29:50 +00001234 // If the parameter type is not dependent, there is nothing to deduce.
1235 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001236 if (!(TDF & TDF_SkipNonDependent)) {
1237 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1238 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1239 Param != Arg;
1240 if (NonDeduced) {
1241 return Sema::TDK_NonDeducedMismatch;
1242 }
1243 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001244 return Sema::TDK_Success;
1245 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001246 } else if (!Param->isDependentType()) {
1247 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1248 ArgUnqualType = CanArg.getUnqualifiedType();
1249 bool Success = (TDF & TDF_InOverloadResolution)?
1250 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1251 ArgUnqualType) :
1252 ParamUnqualType == ArgUnqualType;
1253 if (Success)
1254 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001255 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001256
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001257 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001258 // Non-canonical types cannot appear here.
1259#define NON_CANONICAL_TYPE(Class, Base) \
1260 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1261#define TYPE(Class, Base)
1262#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001263
Douglas Gregor39c02722011-06-15 16:02:29 +00001264 case Type::TemplateTypeParm:
1265 case Type::SubstTemplateTypeParmPack:
1266 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001267
1268 // These types cannot be dependent, so simply check whether the types are
1269 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001270 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001271 case Type::VariableArray:
1272 case Type::Vector:
1273 case Type::FunctionNoProto:
1274 case Type::Record:
1275 case Type::Enum:
1276 case Type::ObjCObject:
1277 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001278 case Type::ObjCObjectPointer: {
1279 if (TDF & TDF_SkipNonDependent)
1280 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001281
Douglas Gregor194ea692012-03-11 03:29:50 +00001282 if (TDF & TDF_IgnoreQualifiers) {
1283 Param = Param.getUnqualifiedType();
1284 Arg = Arg.getUnqualifiedType();
1285 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001286
Douglas Gregor194ea692012-03-11 03:29:50 +00001287 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1288 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001289
1290 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001291 case Type::Complex:
1292 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001293 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1294 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001295 ComplexArg->getElementType(),
1296 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001297
1298 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001299
1300 // _Atomic T [extension]
1301 case Type::Atomic:
1302 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001303 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001304 cast<AtomicType>(Param)->getValueType(),
1305 AtomicArg->getValueType(),
1306 Info, Deduced, TDF);
1307
1308 return Sema::TDK_NonDeducedMismatch;
1309
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001310 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001311 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001312 QualType PointeeType;
1313 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1314 PointeeType = PointerArg->getPointeeType();
1315 } else if (const ObjCObjectPointerType *PointerArg
1316 = Arg->getAs<ObjCObjectPointerType>()) {
1317 PointeeType = PointerArg->getPointeeType();
1318 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001319 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001320 }
Mike Stump11289f42009-09-09 15:08:12 +00001321
Douglas Gregorfc516c92009-06-26 23:27:24 +00001322 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001323 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1324 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001325 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001326 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001329 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001330 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001331 const LValueReferenceType *ReferenceArg =
1332 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001333 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001334 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001336 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001337 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001338 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001339 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001340
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001341 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001342 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001343 const RValueReferenceType *ReferenceArg =
1344 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001345 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001346 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001347
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001348 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1349 cast<RValueReferenceType>(Param)->getPointeeType(),
1350 ReferenceArg->getPointeeType(),
1351 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001354 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001355 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001356 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001357 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001358 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001359 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001360
John McCallf7332682010-08-19 00:20:19 +00001361 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001362 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1363 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1364 IncompleteArrayArg->getElementType(),
1365 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001366 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001367
1368 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001369 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001370 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001371 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001372 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001373 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001374
1375 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001376 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001377 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001378 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001379
John McCallf7332682010-08-19 00:20:19 +00001380 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001381 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1382 ConstantArrayParm->getElementType(),
1383 ConstantArrayArg->getElementType(),
1384 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001385 }
1386
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001387 // type [i]
1388 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001389 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001390 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001391 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001392
John McCallf7332682010-08-19 00:20:19 +00001393 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1394
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001395 // Check the element type of the arrays
1396 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001397 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001398 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001399 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1400 DependentArrayParm->getElementType(),
1401 ArrayArg->getElementType(),
1402 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001403 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001404
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001405 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001406 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001407 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1408 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001409 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001410
1411 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001412 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001413 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001414 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001415 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001416 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1417 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001418 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001419 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001420 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001421 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001422 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001423 if (const DependentSizedArrayType *DependentArrayArg
1424 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001425 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001426 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001427 DependentArrayArg->getSizeExpr(),
1428 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001429
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001430 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001431 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001432 }
Mike Stump11289f42009-09-09 15:08:12 +00001433
1434 // type(*)(T)
1435 // T(*)()
1436 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001437 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001438 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001439 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001440 dyn_cast<FunctionProtoType>(Arg);
1441 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001442 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001443
1444 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001445 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001446
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001447 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001448 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001449 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001450 != FunctionProtoArg->getRefQualifier() ||
1451 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001452 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001453
Anders Carlsson2128ec72009-06-08 15:19:08 +00001454 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001455 if (Sema::TemplateDeductionResult Result =
1456 DeduceTemplateArgumentsByTypeMatch(
1457 S, TemplateParams, FunctionProtoParam->getReturnType(),
1458 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001459 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Alp Toker9cacbab2014-01-20 20:26:09 +00001461 return DeduceTemplateArguments(
1462 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1463 FunctionProtoParam->getNumParams(),
1464 FunctionProtoArg->param_type_begin(),
1465 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001466 }
Mike Stump11289f42009-09-09 15:08:12 +00001467
John McCalle78aac42010-03-10 03:28:59 +00001468 case Type::InjectedClassName: {
1469 // Treat a template's injected-class-name as if the template
1470 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001471 Param = cast<InjectedClassNameType>(Param)
1472 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001473 assert(isa<TemplateSpecializationType>(Param) &&
1474 "injected class name is not a template specialization type");
1475 // fall through
1476 }
1477
Douglas Gregor705c9002009-06-26 20:57:09 +00001478 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001479 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001480 // TT<T>
1481 // TT<i>
1482 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001483 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001484 const TemplateSpecializationType *SpecParam =
1485 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001486
Richard Smith9b296e32016-04-25 19:09:05 +00001487 // When Arg cannot be a derived class, we can just try to deduce template
1488 // arguments from the template-id.
1489 const RecordType *RecordT = Arg->getAs<RecordType>();
1490 if (!(TDF & TDF_DerivedClass) || !RecordT)
1491 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1492 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001493
Richard Smith9b296e32016-04-25 19:09:05 +00001494 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1495 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001496
Richard Smith9b296e32016-04-25 19:09:05 +00001497 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1498 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001499
Richard Smith9b296e32016-04-25 19:09:05 +00001500 if (Result == Sema::TDK_Success)
1501 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001502
Richard Smith9b296e32016-04-25 19:09:05 +00001503 // We cannot inspect base classes as part of deduction when the type
1504 // is incomplete, so either instantiate any templates necessary to
1505 // complete the type, or skip over it if it cannot be completed.
1506 if (!S.isCompleteType(Info.getLocation(), Arg))
1507 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001508
Richard Smith9b296e32016-04-25 19:09:05 +00001509 // C++14 [temp.deduct.call] p4b3:
1510 // If P is a class and P has the form simple-template-id, then the
1511 // transformed A can be a derived class of the deduced A. Likewise if
1512 // P is a pointer to a class of the form simple-template-id, the
1513 // transformed A can be a pointer to a derived class pointed to by the
1514 // deduced A.
1515 //
1516 // These alternatives are considered only if type deduction would
1517 // otherwise fail. If they yield more than one possible deduced A, the
1518 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001519
Faisal Vali683b0742016-05-19 02:28:21 +00001520 // Reset the incorrectly deduced argument from above.
1521 Deduced = DeducedOrig;
1522
1523 // Use data recursion to crawl through the list of base classes.
1524 // Visited contains the set of nodes we have already visited, while
1525 // ToVisit is our stack of records that we still need to visit.
1526 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1527 SmallVector<const RecordType *, 8> ToVisit;
1528 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001529 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001530 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001531 while (!ToVisit.empty()) {
1532 // Retrieve the next class in the inheritance hierarchy.
1533 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001534
Faisal Vali683b0742016-05-19 02:28:21 +00001535 // If we have already seen this type, skip it.
1536 if (!Visited.insert(NextT).second)
1537 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001538
Faisal Vali683b0742016-05-19 02:28:21 +00001539 // If this is a base class, try to perform template argument
1540 // deduction from it.
1541 if (NextT != RecordT) {
1542 TemplateDeductionInfo BaseInfo(Info.getLocation());
1543 Sema::TemplateDeductionResult BaseResult =
1544 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1545 QualType(NextT, 0), BaseInfo, Deduced);
1546
1547 // If template argument deduction for this base was successful,
1548 // note that we had some success. Otherwise, ignore any deductions
1549 // from this base class.
1550 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001551 // If we've already seen some success, then deduction fails due to
1552 // an ambiguity (temp.deduct.call p5).
1553 if (Successful)
1554 return Sema::TDK_MiscellaneousDeductionFailure;
1555
Faisal Vali683b0742016-05-19 02:28:21 +00001556 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001557 std::swap(SuccessfulDeduced, Deduced);
1558
Faisal Vali683b0742016-05-19 02:28:21 +00001559 Info.Param = BaseInfo.Param;
1560 Info.FirstArg = BaseInfo.FirstArg;
1561 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001562 }
1563
1564 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001565 }
Mike Stump11289f42009-09-09 15:08:12 +00001566
Faisal Vali683b0742016-05-19 02:28:21 +00001567 // Visit base classes
1568 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1569 for (const auto &Base : Next->bases()) {
1570 assert(Base.getType()->isRecordType() &&
1571 "Base class that isn't a record?");
1572 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1573 }
1574 }
Mike Stump11289f42009-09-09 15:08:12 +00001575
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001576 if (Successful) {
1577 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001578 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001579 }
Richard Smith9b296e32016-04-25 19:09:05 +00001580
Douglas Gregore81f3e72009-07-07 23:09:34 +00001581 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001582 }
1583
Douglas Gregor637d9982009-06-10 23:47:09 +00001584 // T type::*
1585 // T T::*
1586 // T (type::*)()
1587 // type (T::*)()
1588 // type (type::*)(T)
1589 // type (T::*)(T)
1590 // T (type::*)(T)
1591 // T (T::*)()
1592 // T (T::*)(T)
1593 case Type::MemberPointer: {
1594 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1595 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1596 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001597 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001598
David Majnemera381cda2015-11-30 20:34:28 +00001599 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1600 if (ParamPointeeType->isFunctionType())
1601 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1602 /*IsCtorOrDtor=*/false, Info.getLocation());
1603 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1604 if (ArgPointeeType->isFunctionType())
1605 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1606 /*IsCtorOrDtor=*/false, Info.getLocation());
1607
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001608 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001609 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001610 ParamPointeeType,
1611 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001612 Info, Deduced,
1613 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001614 return Result;
1615
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001616 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1617 QualType(MemPtrParam->getClass(), 0),
1618 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001619 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001620 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001621 }
1622
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001623 // (clang extension)
1624 //
Mike Stump11289f42009-09-09 15:08:12 +00001625 // type(^)(T)
1626 // T(^)()
1627 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001628 case Type::BlockPointer: {
1629 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1630 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001631
Anders Carlssona767eee2009-06-12 16:23:10 +00001632 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001633 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001634
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001635 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1636 BlockPtrParam->getPointeeType(),
1637 BlockPtrArg->getPointeeType(),
1638 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001639 }
1640
Douglas Gregor39c02722011-06-15 16:02:29 +00001641 // (clang extension)
1642 //
1643 // T __attribute__(((ext_vector_type(<integral constant>))))
1644 case Type::ExtVector: {
1645 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1646 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1647 // Make sure that the vectors have the same number of elements.
1648 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1649 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001650
Douglas Gregor39c02722011-06-15 16:02:29 +00001651 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001652 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1653 VectorParam->getElementType(),
1654 VectorArg->getElementType(),
1655 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001656 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001657
1658 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001659 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1660 // We can't check the number of elements, since the argument has a
1661 // dependent number of elements. This can only occur during partial
1662 // ordering.
1663
1664 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001665 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1666 VectorParam->getElementType(),
1667 VectorArg->getElementType(),
1668 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001669 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001670
Douglas Gregor39c02722011-06-15 16:02:29 +00001671 return Sema::TDK_NonDeducedMismatch;
1672 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001673
Douglas Gregor39c02722011-06-15 16:02:29 +00001674 // (clang extension)
1675 //
1676 // T __attribute__(((ext_vector_type(N))))
1677 case Type::DependentSizedExtVector: {
1678 const DependentSizedExtVectorType *VectorParam
1679 = cast<DependentSizedExtVectorType>(Param);
1680
1681 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1682 // Perform deduction on the element types.
1683 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001684 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1685 VectorParam->getElementType(),
1686 VectorArg->getElementType(),
1687 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001688 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001689
Douglas Gregor39c02722011-06-15 16:02:29 +00001690 // Perform deduction on the vector size, if we can.
1691 NonTypeTemplateParmDecl *NTTP
1692 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1693 if (!NTTP)
1694 return Sema::TDK_Success;
1695
1696 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1697 ArgSize = VectorArg->getNumElements();
Richard Smith5f274382016-09-28 23:55:27 +00001698 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith593d6a12016-12-23 01:30:39 +00001699 S.Context.IntTy, false, Info,
1700 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001701 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001702
1703 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001704 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1705 // Perform deduction on the element types.
1706 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001707 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1708 VectorParam->getElementType(),
1709 VectorArg->getElementType(),
1710 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001711 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001712
Douglas Gregor39c02722011-06-15 16:02:29 +00001713 // Perform deduction on the vector size, if we can.
1714 NonTypeTemplateParmDecl *NTTP
1715 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1716 if (!NTTP)
1717 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001718
Richard Smith5f274382016-09-28 23:55:27 +00001719 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1720 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001721 Info, Deduced);
1722 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001723
Douglas Gregor39c02722011-06-15 16:02:29 +00001724 return Sema::TDK_NonDeducedMismatch;
1725 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001726
Douglas Gregor637d9982009-06-10 23:47:09 +00001727 case Type::TypeOfExpr:
1728 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001729 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001730 case Type::UnresolvedUsing:
1731 case Type::Decltype:
1732 case Type::UnaryTransform:
1733 case Type::Auto:
1734 case Type::DependentTemplateSpecialization:
1735 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001736 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001737 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001738 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001739 }
1740
David Blaikiee4d798f2012-01-20 21:50:17 +00001741 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001742}
1743
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001744static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001745DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001746 TemplateParameterList *TemplateParams,
1747 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001748 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001749 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001750 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001751 // If the template argument is a pack expansion, perform template argument
1752 // deduction against the pattern of that expansion. This only occurs during
1753 // partial ordering.
1754 if (Arg.isPackExpansion())
1755 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001756
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001757 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001758 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001759 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001760
1761 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001762 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001763 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1764 Param.getAsType(),
1765 Arg.getAsType(),
1766 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001767 Info.FirstArg = Param;
1768 Info.SecondArg = Arg;
1769 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001770
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001771 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001772 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001773 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001774 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001775 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001776 Info.FirstArg = Param;
1777 Info.SecondArg = Arg;
1778 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001779
1780 case TemplateArgument::TemplateExpansion:
1781 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001782
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001783 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001784 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001785 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001786 return Sema::TDK_Success;
1787
1788 Info.FirstArg = Param;
1789 Info.SecondArg = Arg;
1790 return Sema::TDK_NonDeducedMismatch;
1791
1792 case TemplateArgument::NullPtr:
1793 if (Arg.getKind() == TemplateArgument::NullPtr &&
1794 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001795 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001796
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001797 Info.FirstArg = Param;
1798 Info.SecondArg = Arg;
1799 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001800
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001801 case TemplateArgument::Integral:
1802 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001803 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001804 return Sema::TDK_Success;
1805
1806 Info.FirstArg = Param;
1807 Info.SecondArg = Arg;
1808 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001809 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001810
1811 if (Arg.getKind() == TemplateArgument::Expression) {
1812 Info.FirstArg = Param;
1813 Info.SecondArg = Arg;
1814 return Sema::TDK_NonDeducedMismatch;
1815 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001816
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001817 Info.FirstArg = Param;
1818 Info.SecondArg = Arg;
1819 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001820
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001821 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001822 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001823 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1824 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001825 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001826 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001827 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001828 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001829 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001830 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001831 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1832 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001833 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001834 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001835 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1836 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001837 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001838 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1839 Arg.getAsDecl(),
1840 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001841 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001842
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001843 Info.FirstArg = Param;
1844 Info.SecondArg = Arg;
1845 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001846 }
Mike Stump11289f42009-09-09 15:08:12 +00001847
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001848 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001849 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001850 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001851 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001852 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001853 }
Mike Stump11289f42009-09-09 15:08:12 +00001854
David Blaikiee4d798f2012-01-20 21:50:17 +00001855 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001856}
1857
Douglas Gregor7baabef2010-12-22 18:17:10 +00001858/// \brief Determine whether there is a template argument to be used for
1859/// deduction.
1860///
1861/// This routine "expands" argument packs in-place, overriding its input
1862/// parameters so that \c Args[ArgIdx] will be the available template argument.
1863///
1864/// \returns true if there is another template argument (which will be at
1865/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001866static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1867 unsigned &ArgIdx) {
1868 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001869 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001870
Douglas Gregor7baabef2010-12-22 18:17:10 +00001871 const TemplateArgument &Arg = Args[ArgIdx];
1872 if (Arg.getKind() != TemplateArgument::Pack)
1873 return true;
1874
Richard Smith0bda5b52016-12-23 23:46:56 +00001875 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1876 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001877 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001878 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001879}
1880
Douglas Gregord0ad2942010-12-23 01:24:45 +00001881/// \brief Determine whether the given set of template arguments has a pack
1882/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001883static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1884 bool FoundPackExpansion = false;
1885 for (const auto &A : Args) {
1886 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001887 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001888
1889 if (A.getKind() == TemplateArgument::Pack)
1890 return hasPackExpansionBeforeEnd(A.pack_elements());
1891
1892 if (A.isPackExpansion())
1893 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895
Douglas Gregord0ad2942010-12-23 01:24:45 +00001896 return false;
1897}
1898
Douglas Gregor7baabef2010-12-22 18:17:10 +00001899static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001900DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001901 ArrayRef<TemplateArgument> Params,
1902 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001903 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001904 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1905 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001906 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907 // If the template argument list of P contains a pack expansion that is not
1908 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001909 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001910 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001911 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001912
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001913 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914 // If P has a form that contains <T> or <i>, then each argument Pi of the
1915 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001916 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001917 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001918 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001919 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001920 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001921
Douglas Gregor7baabef2010-12-22 18:17:10 +00001922 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001923 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001924 return NumberOfArgumentsMustMatch ? Sema::TDK_TooFewArguments
1925 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001927 if (Args[ArgIdx].isPackExpansion()) {
1928 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1929 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001930 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001933 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001934 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001935 = DeduceTemplateArguments(S, TemplateParams,
1936 Params[ParamIdx], Args[ArgIdx],
1937 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938 return Result;
1939
Douglas Gregor7baabef2010-12-22 18:17:10 +00001940 // Move to the next argument.
1941 ++ArgIdx;
1942 continue;
1943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001945 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001947 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948 // If Pi is a pack expansion, then the pattern of Pi is compared with
1949 // each remaining argument in the template argument list of A. Each
1950 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001951 // template parameter packs expanded by Pi.
1952 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001954 // FIXME: If there are no remaining arguments, we can bail out early
1955 // and set any deduced parameter packs to an empty argument pack.
1956 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957
Richard Smith0a80d572014-05-29 01:12:14 +00001958 // Prepare to deduce the packs within the pattern.
1959 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001960
1961 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001963 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001964 bool HasAnyArguments = false;
Richard Smith0bda5b52016-12-23 23:46:56 +00001965 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001966 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001968 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001970 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1971 Info, Deduced))
1972 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001973
Richard Smith0a80d572014-05-29 01:12:14 +00001974 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001977 // Build argument packs for each of the parameter packs expanded by this
1978 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001979 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Douglas Gregor7baabef2010-12-22 18:17:10 +00001983 return Sema::TDK_Success;
1984}
1985
Mike Stump11289f42009-09-09 15:08:12 +00001986static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001987DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001988 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001989 const TemplateArgumentList &ParamList,
1990 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001991 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001992 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00001993 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
1994 ArgList.asArray(), Info, Deduced, false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001995}
1996
Douglas Gregor705c9002009-06-26 20:57:09 +00001997/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001998static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001999 const TemplateArgument &X,
2000 const TemplateArgument &Y) {
2001 if (X.getKind() != Y.getKind())
2002 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002003
Douglas Gregor705c9002009-06-26 20:57:09 +00002004 switch (X.getKind()) {
2005 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002006 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002007
Douglas Gregor705c9002009-06-26 20:57:09 +00002008 case TemplateArgument::Type:
2009 return Context.getCanonicalType(X.getAsType()) ==
2010 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002011
Douglas Gregor705c9002009-06-26 20:57:09 +00002012 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002013 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002014
2015 case TemplateArgument::NullPtr:
2016 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002018 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002019 case TemplateArgument::TemplateExpansion:
2020 return Context.getCanonicalTemplateName(
2021 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2022 Context.getCanonicalTemplateName(
2023 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024
Douglas Gregor705c9002009-06-26 20:57:09 +00002025 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002026 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00002027
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002028 case TemplateArgument::Expression: {
2029 llvm::FoldingSetNodeID XID, YID;
2030 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002032 return XID == YID;
2033 }
Mike Stump11289f42009-09-09 15:08:12 +00002034
Douglas Gregor705c9002009-06-26 20:57:09 +00002035 case TemplateArgument::Pack:
2036 if (X.pack_size() != Y.pack_size())
2037 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002038
2039 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2040 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002041 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002042 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00002043 if (!isSameTemplateArg(Context, *XP, *YP))
2044 return false;
2045
2046 return true;
2047 }
2048
David Blaikiee4d798f2012-01-20 21:50:17 +00002049 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002050}
2051
Douglas Gregorca4686d2011-01-04 23:35:54 +00002052/// \brief Allocate a TemplateArgumentLoc where all locations have
2053/// been initialized to the given location.
2054///
James Dennett634962f2012-06-14 21:40:34 +00002055/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002056/// location information for.
2057///
2058/// \param NTTPType For a declaration template argument, the type of
2059/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002060/// argument. Can be null if no type sugar is available to add to the
2061/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002062///
2063/// \param Loc The source location to use for the resulting template
2064/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002065TemplateArgumentLoc
2066Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2067 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002068 switch (Arg.getKind()) {
2069 case TemplateArgument::Null:
2070 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071
Douglas Gregorca4686d2011-01-04 23:35:54 +00002072 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002073 return TemplateArgumentLoc(
2074 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075
Douglas Gregorca4686d2011-01-04 23:35:54 +00002076 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002077 if (NTTPType.isNull())
2078 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002079 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2080 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002081 return TemplateArgumentLoc(TemplateArgument(E), E);
2082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083
Eli Friedmanb826a002012-09-26 02:36:12 +00002084 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002085 if (NTTPType.isNull())
2086 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002087 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2088 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002089 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2090 E);
2091 }
2092
Douglas Gregorca4686d2011-01-04 23:35:54 +00002093 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002094 Expr *E =
2095 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002096 return TemplateArgumentLoc(TemplateArgument(E), E);
2097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098
Douglas Gregor9d802122011-03-02 17:09:35 +00002099 case TemplateArgument::Template:
2100 case TemplateArgument::TemplateExpansion: {
2101 NestedNameSpecifierLocBuilder Builder;
2102 TemplateName Template = Arg.getAsTemplate();
2103 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002104 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002105 else if (QualifiedTemplateName *QTN =
2106 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002107 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002108
Douglas Gregor9d802122011-03-02 17:09:35 +00002109 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002110 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002111 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002112
2113 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002114 Loc, Loc);
2115 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002116
Douglas Gregorca4686d2011-01-04 23:35:54 +00002117 case TemplateArgument::Expression:
2118 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
Douglas Gregorca4686d2011-01-04 23:35:54 +00002120 case TemplateArgument::Pack:
2121 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002123
David Blaikiee4d798f2012-01-20 21:50:17 +00002124 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002125}
2126
2127
2128/// \brief Convert the given deduced template argument and add it to the set of
2129/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002130static bool
2131ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2132 DeducedTemplateArgument Arg,
2133 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002134 TemplateDeductionInfo &Info,
2135 bool InFunctionTemplate,
2136 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002137 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2138 unsigned ArgumentPackIndex) {
2139 // Convert the deduced template argument into a template
2140 // argument that we can check, almost as if the user had written
2141 // the template argument explicitly.
2142 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002143 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002144
2145 // Check the template argument, converting it as necessary.
2146 return S.CheckTemplateArgument(
2147 Param, ArgLoc, Template, Template->getLocation(),
2148 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2149 InFunctionTemplate
2150 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2151 : Sema::CTAK_Deduced)
2152 : Sema::CTAK_Specified);
2153 };
2154
Douglas Gregorca4686d2011-01-04 23:35:54 +00002155 if (Arg.getKind() == TemplateArgument::Pack) {
2156 // This is a template argument pack, so check each of its arguments against
2157 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002158 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002159 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002160 // When converting the deduced template argument, append it to the
2161 // general output list. We need to do this so that the template argument
2162 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002163 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002164 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002165 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2166 "deduced nested pack");
2167 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002168 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002169
Douglas Gregor51bc5712011-01-05 20:52:18 +00002170 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002171 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173
Richard Smithdf18ee92016-02-03 20:40:30 +00002174 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002175 // itself, in case that substitution fails.
2176 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002177 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002178 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002179 MultiLevelTemplateArgumentList Args(TemplateArgs);
2180
2181 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2182 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2183 NTTP, Output,
2184 Template->getSourceRange());
2185 if (Inst.isInvalid() ||
2186 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2187 NTTP->getDeclName()).isNull())
2188 return true;
2189 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2190 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2191 TTP, Output,
2192 Template->getSourceRange());
2193 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2194 return true;
2195 }
2196 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002197 }
Richard Smith37acb792016-02-03 20:15:01 +00002198
Douglas Gregorca4686d2011-01-04 23:35:54 +00002199 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002200 Output.push_back(
2201 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002202 return false;
2203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204
Richard Smith37acb792016-02-03 20:15:01 +00002205 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002206}
2207
Richard Smith1f5be4d2016-12-21 01:10:31 +00002208// FIXME: This should not be a template, but
2209// ClassTemplatePartialSpecializationDecl sadly does not derive from
2210// TemplateDecl.
2211template<typename TemplateDeclT>
2212static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2213 Sema &S, TemplateDeclT *Template,
2214 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2215 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2216 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2217 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2218 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2219
2220 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2221 NamedDecl *Param = TemplateParams->getParam(I);
2222
2223 if (!Deduced[I].isNull()) {
2224 if (I < NumAlreadyConverted) {
2225 // We have already fully type-checked and converted this
2226 // argument, because it was explicitly-specified. Just record the
2227 // presence of this argument.
2228 Builder.push_back(Deduced[I]);
2229 // We may have had explicitly-specified template arguments for a
2230 // template parameter pack (that may or may not have been extended
2231 // via additional deduced arguments).
2232 if (Param->isParameterPack() && CurrentInstantiationScope) {
2233 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2234 Param) {
2235 // Forget the partially-substituted pack; its substitution is now
2236 // complete.
2237 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2238 }
2239 }
2240 continue;
2241 }
2242
2243 // We have deduced this argument, so it still needs to be
2244 // checked and converted.
2245 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2246 isa<FunctionTemplateDecl>(Template),
2247 Builder)) {
2248 Info.Param = makeTemplateParameter(Param);
2249 // FIXME: These template arguments are temporary. Free them!
2250 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2251 return Sema::TDK_SubstitutionFailure;
2252 }
2253
2254 continue;
2255 }
2256
2257 // C++0x [temp.arg.explicit]p3:
2258 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2259 // be deduced to an empty sequence of template arguments.
2260 // FIXME: Where did the word "trailing" come from?
2261 if (Param->isTemplateParameterPack()) {
2262 // We may have had explicitly-specified template arguments for this
2263 // template parameter pack. If so, our empty deduction extends the
2264 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2265 const TemplateArgument *ExplicitArgs;
2266 unsigned NumExplicitArgs;
2267 if (CurrentInstantiationScope &&
2268 CurrentInstantiationScope->getPartiallySubstitutedPack(
2269 &ExplicitArgs, &NumExplicitArgs) == Param) {
2270 Builder.push_back(TemplateArgument(
2271 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2272
2273 // Forget the partially-substituted pack; its substitution is now
2274 // complete.
2275 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2276 } else {
2277 // Go through the motions of checking the empty argument pack against
2278 // the parameter pack.
2279 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2280 if (ConvertDeducedTemplateArgument(
2281 S, Param, DeducedPack, Template, Info,
2282 isa<FunctionTemplateDecl>(Template), Builder)) {
2283 Info.Param = makeTemplateParameter(Param);
2284 // FIXME: These template arguments are temporary. Free them!
2285 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2286 return Sema::TDK_SubstitutionFailure;
2287 }
2288 }
2289 continue;
2290 }
2291
2292 // Substitute into the default template argument, if available.
2293 bool HasDefaultArg = false;
2294 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2295 if (!TD) {
2296 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2297 return Sema::TDK_Incomplete;
2298 }
2299
2300 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2301 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2302 HasDefaultArg);
2303
2304 // If there was no default argument, deduction is incomplete.
2305 if (DefArg.getArgument().isNull()) {
2306 Info.Param = makeTemplateParameter(
2307 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2308 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2309 if (PartialOverloading) break;
2310
2311 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2312 : Sema::TDK_Incomplete;
2313 }
2314
2315 // Check whether we can actually use the default argument.
2316 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2317 TD->getSourceRange().getEnd(), 0, Builder,
2318 Sema::CTAK_Specified)) {
2319 Info.Param = makeTemplateParameter(
2320 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2321 // FIXME: These template arguments are temporary. Free them!
2322 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2323 return Sema::TDK_SubstitutionFailure;
2324 }
2325
2326 // If we get here, we successfully used the default template argument.
2327 }
2328
2329 return Sema::TDK_Success;
2330}
2331
Douglas Gregor684268d2010-04-29 06:21:43 +00002332/// Complete template argument deduction for a class template partial
2333/// specialization.
2334static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002335FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002336 ClassTemplatePartialSpecializationDecl *Partial,
2337 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002338 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002339 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002340 // Unevaluated SFINAE context.
2341 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002342 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002343
Douglas Gregor684268d2010-04-29 06:21:43 +00002344 Sema::ContextRAII SavedContext(S, Partial);
2345
2346 // C++ [temp.deduct.type]p2:
2347 // [...] or if any template argument remains neither deduced nor
2348 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002349 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002350 if (auto Result = ConvertDeducedTemplateArguments(S, Partial, Deduced,
2351 Info, Builder))
2352 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002353
Douglas Gregor684268d2010-04-29 06:21:43 +00002354 // Form the template argument list from the deduced template arguments.
2355 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002356 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002357
Douglas Gregor684268d2010-04-29 06:21:43 +00002358 Info.reset(DeducedArgumentList);
2359
2360 // Substitute the deduced template arguments into the template
2361 // arguments of the class template partial specialization, and
2362 // verify that the instantiated template arguments are both valid
2363 // and are equivalent to the template arguments originally provided
2364 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002365 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002366 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002367 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002368 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002369 const TemplateArgumentLoc *PartialTemplateArgs
2370 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002371
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002372 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2373 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002374
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002375 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002376 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2377 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2378 if (ParamIdx >= Partial->getTemplateParameters()->size())
2379 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2380
2381 Decl *Param
2382 = const_cast<NamedDecl *>(
2383 Partial->getTemplateParameters()->getParam(ParamIdx));
2384 Info.Param = makeTemplateParameter(Param);
2385 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2386 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002387 }
2388
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002389 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002390 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002391 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002392 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002393
Douglas Gregorca4686d2011-01-04 23:35:54 +00002394 TemplateParameterList *TemplateParams
2395 = ClassTemplate->getTemplateParameters();
2396 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002397 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002398 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002399 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002400 Info.FirstArg = TemplateArgs[I];
2401 Info.SecondArg = InstArg;
2402 return Sema::TDK_NonDeducedMismatch;
2403 }
2404 }
2405
2406 if (Trap.hasErrorOccurred())
2407 return Sema::TDK_SubstitutionFailure;
2408
2409 return Sema::TDK_Success;
2410}
2411
Douglas Gregor170bc422009-06-12 22:31:52 +00002412/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002413/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002414/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002415Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002416Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002417 const TemplateArgumentList &TemplateArgs,
2418 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002419 if (Partial->isInvalidDecl())
2420 return TDK_Invalid;
2421
Douglas Gregor170bc422009-06-12 22:31:52 +00002422 // C++ [temp.class.spec.match]p2:
2423 // A partial specialization matches a given actual template
2424 // argument list if the template arguments of the partial
2425 // specialization can be deduced from the actual template argument
2426 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002427
2428 // Unevaluated SFINAE context.
2429 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002430 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002431
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002432 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002433 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002434 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002435 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002436 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002437 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002438 TemplateArgs, Info, Deduced))
2439 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002440
Richard Smith80934652012-07-16 01:09:10 +00002441 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002442 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2443 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002444 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002445 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002446
Douglas Gregore1416332009-06-14 08:02:22 +00002447 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002448 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002449
2450 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002451 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002452}
Douglas Gregor91772d12009-06-13 00:26:55 +00002453
Larisse Voufo39a1e502013-08-06 01:03:05 +00002454/// Complete template argument deduction for a variable template partial
2455/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002456/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2457/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2458/// VarTemplate(Partial)SpecializationDecl with a new data
2459/// structure Template(Partial)SpecializationDecl, and
2460/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002461static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2462 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2463 const TemplateArgumentList &TemplateArgs,
2464 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2465 TemplateDeductionInfo &Info) {
2466 // Unevaluated SFINAE context.
2467 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2468 Sema::SFINAETrap Trap(S);
2469
2470 // C++ [temp.deduct.type]p2:
2471 // [...] or if any template argument remains neither deduced nor
2472 // explicitly specified, template argument deduction fails.
2473 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002474 if (auto Result = ConvertDeducedTemplateArguments(S, Partial, Deduced,
2475 Info, Builder))
2476 return Result;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002477
2478 // Form the template argument list from the deduced template arguments.
2479 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
David Majnemer8b622692016-07-03 21:17:51 +00002480 S.Context, Builder);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002481
2482 Info.reset(DeducedArgumentList);
2483
2484 // Substitute the deduced template arguments into the template
2485 // arguments of the class template partial specialization, and
2486 // verify that the instantiated template arguments are both valid
2487 // and are equivalent to the template arguments originally provided
2488 // to the class template.
2489 LocalInstantiationScope InstScope(S);
2490 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002491 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2492 = Partial->getTemplateArgsAsWritten();
2493 const TemplateArgumentLoc *PartialTemplateArgs
2494 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002495
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002496 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2497 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002498
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002499 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002500 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2501 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2502 if (ParamIdx >= Partial->getTemplateParameters()->size())
2503 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2504
2505 Decl *Param = const_cast<NamedDecl *>(
2506 Partial->getTemplateParameters()->getParam(ParamIdx));
2507 Info.Param = makeTemplateParameter(Param);
2508 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2509 return Sema::TDK_SubstitutionFailure;
2510 }
2511 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2512 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2513 false, ConvertedInstArgs))
2514 return Sema::TDK_SubstitutionFailure;
2515
2516 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2517 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2518 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2519 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2520 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2521 Info.FirstArg = TemplateArgs[I];
2522 Info.SecondArg = InstArg;
2523 return Sema::TDK_NonDeducedMismatch;
2524 }
2525 }
2526
2527 if (Trap.hasErrorOccurred())
2528 return Sema::TDK_SubstitutionFailure;
2529
2530 return Sema::TDK_Success;
2531}
2532
2533/// \brief Perform template argument deduction to determine whether
2534/// the given template arguments match the given variable template
2535/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002536/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2537/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2538/// VarTemplate(Partial)SpecializationDecl with a new data
2539/// structure Template(Partial)SpecializationDecl, and
2540/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002541Sema::TemplateDeductionResult
2542Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2543 const TemplateArgumentList &TemplateArgs,
2544 TemplateDeductionInfo &Info) {
2545 if (Partial->isInvalidDecl())
2546 return TDK_Invalid;
2547
2548 // C++ [temp.class.spec.match]p2:
2549 // A partial specialization matches a given actual template
2550 // argument list if the template arguments of the partial
2551 // specialization can be deduced from the actual template argument
2552 // list (14.8.2).
2553
2554 // Unevaluated SFINAE context.
2555 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2556 SFINAETrap Trap(*this);
2557
2558 SmallVector<DeducedTemplateArgument, 4> Deduced;
2559 Deduced.resize(Partial->getTemplateParameters()->size());
2560 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2561 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2562 TemplateArgs, Info, Deduced))
2563 return Result;
2564
2565 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002566 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2567 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002568 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002569 return TDK_InstantiationDepth;
2570
2571 if (Trap.hasErrorOccurred())
2572 return Sema::TDK_SubstitutionFailure;
2573
2574 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2575 Deduced, Info);
2576}
2577
Douglas Gregorfc516c92009-06-26 23:27:24 +00002578/// \brief Determine whether the given type T is a simple-template-id type.
2579static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002580 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002581 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002582 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002583
Douglas Gregorfc516c92009-06-26 23:27:24 +00002584 return false;
2585}
Douglas Gregor9b146582009-07-08 20:55:45 +00002586
2587/// \brief Substitute the explicitly-provided template arguments into the
2588/// given function template according to C++ [temp.arg.explicit].
2589///
2590/// \param FunctionTemplate the function template into which the explicit
2591/// template arguments will be substituted.
2592///
James Dennett634962f2012-06-14 21:40:34 +00002593/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002594/// arguments.
2595///
Mike Stump11289f42009-09-09 15:08:12 +00002596/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002597/// with the converted and checked explicit template arguments.
2598///
Mike Stump11289f42009-09-09 15:08:12 +00002599/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002600/// parameters.
2601///
2602/// \param FunctionType if non-NULL, the result type of the function template
2603/// will also be instantiated and the pointed-to value will be updated with
2604/// the instantiated function type.
2605///
2606/// \param Info if substitution fails for any reason, this object will be
2607/// populated with more information about the failure.
2608///
2609/// \returns TDK_Success if substitution was successful, or some failure
2610/// condition.
2611Sema::TemplateDeductionResult
2612Sema::SubstituteExplicitTemplateArguments(
2613 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002614 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002615 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2616 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002617 QualType *FunctionType,
2618 TemplateDeductionInfo &Info) {
2619 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2620 TemplateParameterList *TemplateParams
2621 = FunctionTemplate->getTemplateParameters();
2622
John McCall6b51f282009-11-23 01:53:49 +00002623 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002624 // No arguments to substitute; just copy over the parameter types and
2625 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002626 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002627 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002628
Douglas Gregor9b146582009-07-08 20:55:45 +00002629 if (FunctionType)
2630 *FunctionType = Function->getType();
2631 return TDK_Success;
2632 }
Mike Stump11289f42009-09-09 15:08:12 +00002633
Eli Friedman77dcc722012-02-08 03:07:05 +00002634 // Unevaluated SFINAE context.
2635 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002636 SFINAETrap Trap(*this);
2637
Douglas Gregor9b146582009-07-08 20:55:45 +00002638 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002639 // Template arguments that are present shall be specified in the
2640 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002641 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002642 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002643 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002644
2645 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002646 // explicitly-specified template arguments against this function template,
2647 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002648 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002649 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2650 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002651 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2652 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002653 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002654 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002655
Douglas Gregor9b146582009-07-08 20:55:45 +00002656 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002657 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002658 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002659 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002660 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002661 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002662 if (Index >= TemplateParams->size())
2663 Index = TemplateParams->size() - 1;
2664 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002665 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002666 }
Mike Stump11289f42009-09-09 15:08:12 +00002667
Douglas Gregor9b146582009-07-08 20:55:45 +00002668 // Form the template argument list from the explicitly-specified
2669 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002670 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002671 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002672 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002673
John McCall036855a2010-10-12 19:40:14 +00002674 // Template argument deduction and the final substitution should be
2675 // done in the context of the templated declaration. Explicit
2676 // argument substitution, on the other hand, needs to happen in the
2677 // calling context.
2678 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2679
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002680 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002681 // note that the template argument pack is partially substituted and record
2682 // the explicit template arguments. They'll be used as part of deduction
2683 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002684 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2685 const TemplateArgument &Arg = Builder[I];
2686 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002687 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002688 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002689 Arg.pack_begin(),
2690 Arg.pack_size());
2691 break;
2692 }
2693 }
2694
Richard Smith5e580292012-02-10 09:58:53 +00002695 const FunctionProtoType *Proto
2696 = Function->getType()->getAs<FunctionProtoType>();
2697 assert(Proto && "Function template does not have a prototype?");
2698
Richard Smith70b13042015-01-09 01:19:56 +00002699 // Isolate our substituted parameters from our caller.
2700 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2701
John McCallc8e321d2016-03-01 02:09:25 +00002702 ExtParameterInfoBuilder ExtParamInfos;
2703
Douglas Gregor9b146582009-07-08 20:55:45 +00002704 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002705 // explicitly-specified template arguments. If the function has a trailing
2706 // return type, substitute it after the arguments to ensure we substitute
2707 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002708 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002709 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002710 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002711 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002712 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002713 return TDK_SubstitutionFailure;
2714 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002715
Richard Smith5e580292012-02-10 09:58:53 +00002716 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002717 QualType ResultType;
2718 {
2719 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002720 // If a declaration declares a member function or member function
2721 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002722 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002723 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002724 // declarator.
2725 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002726 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002727 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2728 ThisContext = Method->getParent();
2729 ThisTypeQuals = Method->getTypeQualifiers();
2730 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002731
Douglas Gregor3024f072012-04-16 07:05:22 +00002732 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002733 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002734
2735 ResultType =
2736 SubstType(Proto->getReturnType(),
2737 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2738 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002739 if (ResultType.isNull() || Trap.hasErrorOccurred())
2740 return TDK_SubstitutionFailure;
2741 }
John McCallc8e321d2016-03-01 02:09:25 +00002742
Richard Smith5e580292012-02-10 09:58:53 +00002743 // Instantiate the types of each of the function parameters given the
2744 // explicitly-specified template arguments if we didn't do so earlier.
2745 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002746 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002747 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002748 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002749 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002750 return TDK_SubstitutionFailure;
2751
Douglas Gregor9b146582009-07-08 20:55:45 +00002752 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002753 auto EPI = Proto->getExtProtoInfo();
2754 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002755 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002756 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002757 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002758 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002759 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2760 return TDK_SubstitutionFailure;
2761 }
Mike Stump11289f42009-09-09 15:08:12 +00002762
Douglas Gregor9b146582009-07-08 20:55:45 +00002763 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002764 // Trailing template arguments that can be deduced (14.8.2) may be
2765 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002766 // template arguments can be deduced, they may all be omitted; in this
2767 // case, the empty template argument list <> itself may also be omitted.
2768 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002769 // Take all of the explicitly-specified arguments and put them into
2770 // the set of deduced template arguments. Explicitly-specified
2771 // parameter packs, however, will be set to NULL since the deduction
2772 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002773 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002774 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2775 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2776 if (Arg.getKind() == TemplateArgument::Pack)
2777 Deduced.push_back(DeducedTemplateArgument());
2778 else
2779 Deduced.push_back(Arg);
2780 }
Mike Stump11289f42009-09-09 15:08:12 +00002781
Douglas Gregor9b146582009-07-08 20:55:45 +00002782 return TDK_Success;
2783}
2784
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002785/// \brief Check whether the deduced argument type for a call to a function
2786/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002787static bool
2788CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002789 QualType DeducedA) {
2790 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002791
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002792 QualType A = OriginalArg.OriginalArgType;
2793 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002794
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002795 // Check for type equality (top-level cv-qualifiers are ignored).
2796 if (Context.hasSameUnqualifiedType(A, DeducedA))
2797 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002798
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002799 // Strip off references on the argument types; they aren't needed for
2800 // the following checks.
2801 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2802 DeducedA = DeducedARef->getPointeeType();
2803 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2804 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002805
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002806 // C++ [temp.deduct.call]p4:
2807 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002808 // - If the original P is a reference type, the deduced A (i.e., the
2809 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002810 // the transformed A.
2811 if (const ReferenceType *OriginalParamRef
2812 = OriginalParamType->getAs<ReferenceType>()) {
2813 // We don't want to keep the reference around any more.
2814 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002815
Richard Smith1be59c52016-10-22 01:32:19 +00002816 // FIXME: Resolve core issue (no number yet): if the original P is a
2817 // reference type and the transformed A is function type "noexcept F",
2818 // the deduced A can be F.
2819 QualType Tmp;
2820 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2821 return false;
2822
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002823 Qualifiers AQuals = A.getQualifiers();
2824 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002825
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002826 // Under Objective-C++ ARC, the deduced type may have implicitly
2827 // been given strong or (when dealing with a const reference)
2828 // unsafe_unretained lifetime. If so, update the original
2829 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002830 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002831 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2832 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2833 (DeducedAQuals.hasConst() &&
2834 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2835 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002836 }
2837
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002838 if (AQuals == DeducedAQuals) {
2839 // Qualifiers match; there's nothing to do.
2840 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002841 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002842 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002843 // Qualifiers are compatible, so have the argument type adopt the
2844 // deduced argument type's qualifiers as if we had performed the
2845 // qualification conversion.
2846 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2847 }
2848 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002849
2850 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002851 // type that can be converted to the deduced A via a function pointer
2852 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002853 //
Richard Smith1be59c52016-10-22 01:32:19 +00002854 // Also allow conversions which merely strip __attribute__((noreturn)) from
2855 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002856 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002857 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002858 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002859 (S.IsQualificationConversion(A, DeducedA, false,
2860 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002861 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002862 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002863
Simon Pilgrim728134c2016-08-12 11:43:57 +00002864 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002865 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002866 // [...] Likewise, if P is a pointer to a class of the form
2867 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002868 // derived class pointed to by the deduced A.
2869 if (const PointerType *OriginalParamPtr
2870 = OriginalParamType->getAs<PointerType>()) {
2871 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2872 if (const PointerType *APtr = A->getAs<PointerType>()) {
2873 if (A->getPointeeType()->isRecordType()) {
2874 OriginalParamType = OriginalParamPtr->getPointeeType();
2875 DeducedA = DeducedAPtr->getPointeeType();
2876 A = APtr->getPointeeType();
2877 }
2878 }
2879 }
2880 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002881
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002882 if (Context.hasSameUnqualifiedType(A, DeducedA))
2883 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002884
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002885 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002886 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002887 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002888
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002889 return true;
2890}
2891
Mike Stump11289f42009-09-09 15:08:12 +00002892/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002893/// checking the deduced template arguments for completeness and forming
2894/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002895///
2896/// \param OriginalCallArgs If non-NULL, the original call arguments against
2897/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002898Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002899Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002900 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002901 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002902 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002903 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002904 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2905 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002906 // Unevaluated SFINAE context.
2907 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002908 SFINAETrap Trap(*this);
2909
Douglas Gregor9b146582009-07-08 20:55:45 +00002910 // Enter a new template instantiation context while we instantiate the
2911 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002912 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002913 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2914 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002915 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2916 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002917 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002918 return TDK_InstantiationDepth;
2919
John McCalle23b8712010-04-29 01:18:58 +00002920 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002921
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002922 // C++ [temp.deduct.type]p2:
2923 // [...] or if any template argument remains neither deduced nor
2924 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002925 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002926 if (auto Result = ConvertDeducedTemplateArguments(
2927 *this, FunctionTemplate, Deduced, Info, Builder,
2928 CurrentInstantiationScope, NumExplicitlySpecified,
2929 PartialOverloading))
2930 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002931
2932 // Form the template argument list from the deduced template arguments.
2933 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002934 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002935 Info.reset(DeducedArgumentList);
2936
Mike Stump11289f42009-09-09 15:08:12 +00002937 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002938 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002939 DeclContext *Owner = FunctionTemplate->getDeclContext();
2940 if (FunctionTemplate->getFriendObjectKind())
2941 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002942 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002943 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002944 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002945 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002946 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002947
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002949 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950
Mike Stump11289f42009-09-09 15:08:12 +00002951 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002952 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002953 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2954 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002955 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002956
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002957 // There may have been an error that did not prevent us from constructing a
2958 // declaration. Mark the declaration invalid and return with a substitution
2959 // failure.
2960 if (Trap.hasErrorOccurred()) {
2961 Specialization->setInvalidDecl(true);
2962 return TDK_SubstitutionFailure;
2963 }
2964
Douglas Gregore65aacb2011-06-16 16:50:48 +00002965 if (OriginalCallArgs) {
2966 // C++ [temp.deduct.call]p4:
2967 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002968 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002969 // is transformed as described above). [...]
2970 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2971 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002972 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002973
Douglas Gregore65aacb2011-06-16 16:50:48 +00002974 if (ParamIdx >= Specialization->getNumParams())
2975 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002976
Douglas Gregore65aacb2011-06-16 16:50:48 +00002977 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002978 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2979 Info.FirstArg = TemplateArgument(DeducedA);
2980 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2981 Info.CallArgIndex = OriginalArg.ArgIdx;
2982 return TDK_DeducedMismatch;
2983 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002984 }
2985 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002986
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002987 // If we suppressed any diagnostics while performing template argument
2988 // deduction, and if we haven't already instantiated this declaration,
2989 // keep track of these diagnostics. They'll be emitted if this specialization
2990 // is actually used.
2991 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002992 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002993 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2994 if (Pos == SuppressedDiagnostics.end())
2995 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2996 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002997 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002998
Mike Stump11289f42009-09-09 15:08:12 +00002999 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003000}
3001
John McCall8d08b9b2010-08-27 09:08:28 +00003002/// Gets the type of a function for template-argument-deducton
3003/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003004static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003005 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003006 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003007 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003008 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003009 return QualType();
3010
John McCallc1f69982010-02-02 02:21:27 +00003011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003012 if (Method->isInstance()) {
3013 // An instance method that's referenced in a form that doesn't
3014 // look like a member pointer is just invalid.
3015 if (!R.HasFormOfMemberPointer) return QualType();
3016
Richard Smith2a7d4812013-05-04 07:00:32 +00003017 return S.Context.getMemberPointerType(Fn->getType(),
3018 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003019 }
3020
3021 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003022 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003023}
3024
3025/// Apply the deduction rules for overload sets.
3026///
3027/// \return the null type if this argument should be treated as an
3028/// undeduced context
3029static QualType
3030ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003031 Expr *Arg, QualType ParamType,
3032 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003033
John McCall8d08b9b2010-08-27 09:08:28 +00003034 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003035
John McCall8d08b9b2010-08-27 09:08:28 +00003036 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003037
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003038 // C++0x [temp.deduct.call]p4
3039 unsigned TDF = 0;
3040 if (ParamWasReference)
3041 TDF |= TDF_ParamWithReferenceType;
3042 if (R.IsAddressOfOperand)
3043 TDF |= TDF_IgnoreQualifiers;
3044
John McCallc1f69982010-02-02 02:21:27 +00003045 // C++0x [temp.deduct.call]p6:
3046 // When P is a function type, pointer to function type, or pointer
3047 // to member function type:
3048
3049 if (!ParamType->isFunctionType() &&
3050 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003051 !ParamType->isMemberFunctionPointerType()) {
3052 if (Ovl->hasExplicitTemplateArgs()) {
3053 // But we can still look for an explicit specialization.
3054 if (FunctionDecl *ExplicitSpec
3055 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003056 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003057 }
John McCallc1f69982010-02-02 02:21:27 +00003058
George Burgess IVcc2f3552016-03-19 21:51:45 +00003059 DeclAccessPair DAP;
3060 if (FunctionDecl *Viable =
3061 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3062 return GetTypeOfFunction(S, R, Viable);
3063
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003064 return QualType();
3065 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003066
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003067 // Gather the explicit template arguments, if any.
3068 TemplateArgumentListInfo ExplicitTemplateArgs;
3069 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003070 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003071 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003072 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3073 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003074 NamedDecl *D = (*I)->getUnderlyingDecl();
3075
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003076 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3077 // - If the argument is an overload set containing one or more
3078 // function templates, the parameter is treated as a
3079 // non-deduced context.
3080 if (!Ovl->hasExplicitTemplateArgs())
3081 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003082
3083 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003084 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003085 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003086 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3087 Specialization, Info))
3088 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003089
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003090 D = Specialization;
3091 }
John McCallc1f69982010-02-02 02:21:27 +00003092
3093 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003094 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003095 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003096
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003097 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003098 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003099 ArgType->isFunctionType())
3100 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101
John McCallc1f69982010-02-02 02:21:27 +00003102 // - If the argument is an overload set (not containing function
3103 // templates), trial argument deduction is attempted using each
3104 // of the members of the set. If deduction succeeds for only one
3105 // of the overload set members, that member is used as the
3106 // argument value for the deduction. If deduction succeeds for
3107 // more than one member of the overload set the parameter is
3108 // treated as a non-deduced context.
3109
3110 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3111 // Type deduction is done independently for each P/A pair, and
3112 // the deduced template argument values are then combined.
3113 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003114 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003115 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003116 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003117 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003118 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3119 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003120 if (Result) continue;
3121 if (!Match.isNull()) return QualType();
3122 Match = ArgType;
3123 }
3124
3125 return Match;
3126}
3127
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003128/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003129/// described in C++ [temp.deduct.call].
3130///
3131/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003132/// argument deduction based on this P/A pair because the argument is an
3133/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003134static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3135 TemplateParameterList *TemplateParams,
3136 QualType &ParamType,
3137 QualType &ArgType,
3138 Expr *Arg,
3139 unsigned &TDF) {
3140 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003141 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003142 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003143 if (ParamType.hasQualifiers())
3144 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003145
3146 // [...] If P is a reference type, the type referred to by P is
3147 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003148 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003149 if (ParamRefType)
3150 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003151
Nathan Sidwell96090022015-01-16 15:20:14 +00003152 // Overload sets usually make this parameter an undeduced context,
3153 // but there are sometimes special circumstances. Typically
3154 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003155 if (ArgType == S.Context.OverloadTy) {
3156 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3157 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003158 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003159 if (ArgType.isNull())
3160 return true;
3161 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003162
Douglas Gregor7825bf32011-01-06 22:09:01 +00003163 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003164 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003165 if (ArgType->isIncompleteArrayType()) {
3166 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003167 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003168 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003169
Douglas Gregor7825bf32011-01-06 22:09:01 +00003170 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003171 // If P is an rvalue reference to a cv-unqualified template
3172 // parameter and the argument is an lvalue, the type "lvalue
3173 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003174 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003175 !ParamType.getQualifiers() &&
3176 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003177 Arg->isLValue())
3178 ArgType = S.Context.getLValueReferenceType(ArgType);
3179 } else {
3180 // C++ [temp.deduct.call]p2:
3181 // If P is not a reference type:
3182 // - If A is an array type, the pointer type produced by the
3183 // array-to-pointer standard conversion (4.2) is used in place of
3184 // A for type deduction; otherwise,
3185 if (ArgType->isArrayType())
3186 ArgType = S.Context.getArrayDecayedType(ArgType);
3187 // - If A is a function type, the pointer type produced by the
3188 // function-to-pointer standard conversion (4.3) is used in place
3189 // of A for type deduction; otherwise,
3190 else if (ArgType->isFunctionType())
3191 ArgType = S.Context.getPointerType(ArgType);
3192 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003193 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003194 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003195 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003196 }
3197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198
Douglas Gregor7825bf32011-01-06 22:09:01 +00003199 // C++0x [temp.deduct.call]p4:
3200 // In general, the deduction process attempts to find template argument
3201 // values that will make the deduced A identical to A (after the type A
3202 // is transformed as described above). [...]
3203 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204
Douglas Gregor7825bf32011-01-06 22:09:01 +00003205 // - If the original P is a reference type, the deduced A (i.e., the
3206 // type referred to by the reference) can be more cv-qualified than
3207 // the transformed A.
3208 if (ParamRefType)
3209 TDF |= TDF_ParamWithReferenceType;
3210 // - The transformed A can be another pointer or pointer to member
3211 // type that can be converted to the deduced A via a qualification
3212 // conversion (4.4).
3213 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3214 ArgType->isObjCObjectPointerType())
3215 TDF |= TDF_IgnoreQualifiers;
3216 // - If P is a class and P has the form simple-template-id, then the
3217 // transformed A can be a derived class of the deduced A. Likewise,
3218 // if P is a pointer to a class of the form simple-template-id, the
3219 // transformed A can be a pointer to a derived class pointed to by
3220 // the deduced A.
3221 if (isSimpleTemplateIdType(ParamType) ||
3222 (isa<PointerType>(ParamType) &&
3223 isSimpleTemplateIdType(
3224 ParamType->getAs<PointerType>()->getPointeeType())))
3225 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003226
Douglas Gregor7825bf32011-01-06 22:09:01 +00003227 return false;
3228}
3229
Nico Weberc153d242014-07-28 00:02:09 +00003230static bool
3231hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3232 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003233
Hubert Tong3280b332015-06-25 00:25:49 +00003234static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3235 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3236 Expr *Arg, TemplateDeductionInfo &Info,
3237 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3238
3239/// \brief Attempt template argument deduction from an initializer list
3240/// deemed to be an argument in a function call.
3241static bool
3242DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3243 QualType AdjustedParamType, InitListExpr *ILE,
3244 TemplateDeductionInfo &Info,
3245 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3246 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003247
3248 // [temp.deduct.call] p1 (post CWG-1591)
3249 // If removing references and cv-qualifiers from P gives
3250 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3251 // non-empty initializer list (8.5.4), then deduction is performed instead for
3252 // each element of the initializer list, taking P0 as a function template
3253 // parameter type and the initializer element as its argument, and in the
3254 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3255 // length of the initializer list. Otherwise, an initializer list argument
3256 // causes the parameter to be considered a non-deduced context
3257
3258 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3259
3260 const bool IsDependentSizedArray =
3261 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3262
Faisal Validd76cc12015-12-10 12:29:11 +00003263 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003264
3265 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3266 S.isStdInitializerList(AdjustedParamType, &ElTy);
3267
3268 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003269 return false;
3270
3271 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003272 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3273 // deduce against the 'T' in T[N].
3274 if (ElTy.isNull()) {
3275 assert(!IsSTDList);
3276 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003277 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003278 // Deduction only needs to be done for dependent types.
3279 if (ElTy->isDependentType()) {
3280 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003281 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3282 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003283 return true;
3284 }
3285 }
3286 if (IsDependentSizedArray) {
3287 const DependentSizedArrayType *ArrTy =
3288 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3289 // Determine the array bound is something we can deduce.
3290 if (NonTypeTemplateParmDecl *NTTP =
3291 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3292 // We can perform template argument deduction for the given non-type
3293 // template parameter.
3294 assert(NTTP->getDepth() == 0 &&
3295 "Cannot deduce non-type template argument at depth > 0");
3296 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3297 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003298
Faisal Valif6dfdb32015-12-10 05:36:39 +00003299 Result = DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +00003300 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
Faisal Valif6dfdb32015-12-10 05:36:39 +00003301 /*ArrayBound=*/true, Info, Deduced);
3302 }
3303 }
Hubert Tong3280b332015-06-25 00:25:49 +00003304 return true;
3305}
3306
Sebastian Redl19181662012-03-15 21:40:51 +00003307/// \brief Perform template argument deduction by matching a parameter type
3308/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003309/// an initializer list that was originally matched against a parameter
3310/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003311static Sema::TemplateDeductionResult
3312DeduceTemplateArgumentByListElement(Sema &S,
3313 TemplateParameterList *TemplateParams,
3314 QualType ParamType, Expr *Arg,
3315 TemplateDeductionInfo &Info,
3316 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3317 unsigned TDF) {
3318 // Handle the case where an init list contains another init list as the
3319 // element.
3320 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003321 Sema::TemplateDeductionResult Result;
3322 if (!DeduceFromInitializerList(S, TemplateParams,
3323 ParamType.getNonReferenceType(), ILE, Info,
3324 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003325 return Sema::TDK_Success; // Just ignore this expression.
3326
Hubert Tong3280b332015-06-25 00:25:49 +00003327 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003328 }
3329
3330 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003331 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003332 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003333 ArgType, Arg, TDF)) {
3334 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003335 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003336 }
Sebastian Redl19181662012-03-15 21:40:51 +00003337 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003338 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003339}
3340
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003341/// \brief Perform template argument deduction from a function call
3342/// (C++ [temp.deduct.call]).
3343///
3344/// \param FunctionTemplate the function template for which we are performing
3345/// template argument deduction.
3346///
James Dennett18348b62012-06-22 08:52:37 +00003347/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003348/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003349///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003350/// \param Args the function call arguments
3351///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003352/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003353/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003354/// template argument deduction.
3355///
3356/// \param Info the argument will be updated to provide additional information
3357/// about template argument deduction.
3358///
3359/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003360Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3361 FunctionTemplateDecl *FunctionTemplate,
3362 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003363 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3364 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003365 if (FunctionTemplate->isInvalidDecl())
3366 return TDK_Invalid;
3367
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003368 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003369 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003370
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003371 // C++ [temp.deduct.call]p1:
3372 // Template argument deduction is done by comparing each function template
3373 // parameter type (call it P) with the type of the corresponding argument
3374 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003375 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003376 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003377 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003378 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003379 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003380 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003381 if (Proto->isTemplateVariadic())
3382 /* Do nothing */;
3383 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003384 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003386 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003387 }
Mike Stump11289f42009-09-09 15:08:12 +00003388
Douglas Gregor89026b52009-06-30 23:57:56 +00003389 // The types of the parameters from which we will perform template argument
3390 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003391 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003392 TemplateParameterList *TemplateParams
3393 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003394 SmallVector<DeducedTemplateArgument, 4> Deduced;
3395 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003396 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003397 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003398 TemplateDeductionResult Result =
3399 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003400 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003401 Deduced,
3402 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003403 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003404 Info);
3405 if (Result)
3406 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003407
3408 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003409 } else {
3410 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003411 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003412 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3413 }
Mike Stump11289f42009-09-09 15:08:12 +00003414
Douglas Gregor89026b52009-06-30 23:57:56 +00003415 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003416 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003417 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003418 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003419 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3420 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003421 QualType OrigParamType = ParamTypes[ParamIdx];
3422 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003423
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003425 = dyn_cast<PackExpansionType>(ParamType);
3426 if (!ParamExpansion) {
3427 // Simple case: matching a function parameter to a function argument.
3428 if (ArgIdx >= CheckArgs)
3429 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003430
Douglas Gregor7825bf32011-01-06 22:09:01 +00003431 Expr *Arg = Args[ArgIdx++];
3432 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003433
Douglas Gregor7825bf32011-01-06 22:09:01 +00003434 unsigned TDF = 0;
3435 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3436 ParamType, ArgType, Arg,
3437 TDF))
3438 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439
Douglas Gregor0c83c812011-10-09 22:06:46 +00003440 // If we have nothing to deduce, we're done.
3441 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3442 continue;
3443
Sebastian Redl43144e72012-01-17 22:49:58 +00003444 // If the argument is an initializer list ...
3445 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003446 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003447 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003448 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3449 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003450 continue;
3451
Hubert Tong3280b332015-06-25 00:25:49 +00003452 if (Result)
3453 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003454 // Don't track the argument type, since an initializer list has none.
3455 continue;
3456 }
3457
Douglas Gregore65aacb2011-06-16 16:50:48 +00003458 // Keep track of the argument type and corresponding parameter index,
3459 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003460 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003461 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003462
Douglas Gregor7825bf32011-01-06 22:09:01 +00003463 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003464 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3465 ParamType, ArgType,
3466 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003467 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003468
Douglas Gregor7825bf32011-01-06 22:09:01 +00003469 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003471
Douglas Gregor7825bf32011-01-06 22:09:01 +00003472 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473 // For a function parameter pack that occurs at the end of the
3474 // parameter-declaration-list, the type A of each remaining argument of
3475 // the call is compared with the type P of the declarator-id of the
3476 // function parameter pack. Each comparison deduces template arguments
3477 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003478 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003479 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003480 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003481 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003482 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003483
Douglas Gregor7825bf32011-01-06 22:09:01 +00003484 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003485 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3486 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003487
Douglas Gregor7825bf32011-01-06 22:09:01 +00003488 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003489 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003490 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491
Douglas Gregore65aacb2011-06-16 16:50:48 +00003492 QualType OrigParamType = ParamPattern;
3493 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003494 Expr *Arg = Args[ArgIdx];
3495 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003496
Douglas Gregor7825bf32011-01-06 22:09:01 +00003497 unsigned TDF = 0;
3498 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3499 ParamType, ArgType, Arg,
3500 TDF)) {
3501 // We can't actually perform any deduction for this argument, so stop
3502 // deduction at this point.
3503 ++ArgIdx;
3504 break;
3505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Sebastian Redl43144e72012-01-17 22:49:58 +00003507 // As above, initializer lists need special handling.
3508 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003509 TemplateDeductionResult Result;
3510 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3511 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003512 ++ArgIdx;
3513 break;
3514 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003515
Hubert Tong3280b332015-06-25 00:25:49 +00003516 if (Result)
3517 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003518 } else {
3519
3520 // Keep track of the argument type and corresponding argument index,
3521 // so we can check for compatibility between the deduced A and A.
3522 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003523 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003524 ArgType));
3525
3526 if (TemplateDeductionResult Result
3527 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3528 ParamType, ArgType, Info,
3529 Deduced, TDF))
3530 return Result;
3531 }
Mike Stump11289f42009-09-09 15:08:12 +00003532
Richard Smith0a80d572014-05-29 01:12:14 +00003533 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535
Douglas Gregor7825bf32011-01-06 22:09:01 +00003536 // Build argument packs for each of the parameter packs expanded by this
3537 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003538 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003540
Douglas Gregor7825bf32011-01-06 22:09:01 +00003541 // After we've matching against a parameter pack, we're done.
3542 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003543 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003544
Mike Stump11289f42009-09-09 15:08:12 +00003545 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003546 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003547 Info, &OriginalCallArgs,
3548 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003549}
3550
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003551QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003552 QualType FunctionType,
3553 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003554 if (ArgFunctionType.isNull())
3555 return ArgFunctionType;
3556
3557 const FunctionProtoType *FunctionTypeP =
3558 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003559 const FunctionProtoType *ArgFunctionTypeP =
3560 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003561
3562 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3563 bool Rebuild = false;
3564
3565 CallingConv CC = FunctionTypeP->getCallConv();
3566 if (EPI.ExtInfo.getCC() != CC) {
3567 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3568 Rebuild = true;
3569 }
3570
3571 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3572 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3573 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3574 Rebuild = true;
3575 }
3576
3577 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3578 ArgFunctionTypeP->hasExceptionSpec())) {
3579 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3580 Rebuild = true;
3581 }
3582
3583 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003584 return ArgFunctionType;
3585
Richard Smithbaa47832016-12-01 02:11:49 +00003586 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3587 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003588}
3589
Douglas Gregor9b146582009-07-08 20:55:45 +00003590/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003591/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3592/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003593///
3594/// \param FunctionTemplate the function template for which we are performing
3595/// template argument deduction.
3596///
James Dennett18348b62012-06-22 08:52:37 +00003597/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003598/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003599///
3600/// \param ArgFunctionType the function type that will be used as the
3601/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003602/// function template's function type. This type may be NULL, if there is no
3603/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003604///
3605/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003606/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003607/// template argument deduction.
3608///
3609/// \param Info the argument will be updated to provide additional information
3610/// about template argument deduction.
3611///
Richard Smithbaa47832016-12-01 02:11:49 +00003612/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3613/// the address of a function template per [temp.deduct.funcaddr] and
3614/// [over.over]. If \c false, we are looking up a function template
3615/// specialization based on its signature, per [temp.deduct.decl].
3616///
Douglas Gregor9b146582009-07-08 20:55:45 +00003617/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003618Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3619 FunctionTemplateDecl *FunctionTemplate,
3620 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3621 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3622 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003623 if (FunctionTemplate->isInvalidDecl())
3624 return TDK_Invalid;
3625
Douglas Gregor9b146582009-07-08 20:55:45 +00003626 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3627 TemplateParameterList *TemplateParams
3628 = FunctionTemplate->getTemplateParameters();
3629 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003630
3631 // When taking the address of a function, we require convertibility of
3632 // the resulting function type. Otherwise, we allow arbitrary mismatches
3633 // of calling convention, noreturn, and noexcept.
3634 if (!IsAddressOfFunction)
3635 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3636 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003637
Douglas Gregor9b146582009-07-08 20:55:45 +00003638 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003639 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003640 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003641 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003642 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003643 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003644 if (TemplateDeductionResult Result
3645 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003646 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003647 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003648 &FunctionType, Info))
3649 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003650
3651 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003652 }
3653
Eli Friedman77dcc722012-02-08 03:07:05 +00003654 // Unevaluated SFINAE context.
3655 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003656 SFINAETrap Trap(*this);
3657
John McCallc1f69982010-02-02 02:21:27 +00003658 Deduced.resize(TemplateParams->size());
3659
Richard Smith2a7d4812013-05-04 07:00:32 +00003660 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003661 // type so that we treat it as a non-deduced context in what follows. If we
3662 // are looking up by signature, the signature type should also have a deduced
3663 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003664 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003665 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003666 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003667 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003668 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003669 }
3670
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003671 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003672 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003673 if (IsAddressOfFunction)
3674 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003675 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003676 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003677 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003678 FunctionType, ArgFunctionType,
3679 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003680 return Result;
3681 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003682
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003683 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003684 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3685 NumExplicitlySpecified,
3686 Specialization, Info))
3687 return Result;
3688
Richard Smith2a7d4812013-05-04 07:00:32 +00003689 // If the function has a deduced return type, deduce it now, so we can check
3690 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003691 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003692 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003693 DeduceReturnType(Specialization, Info.getLocation(), false))
3694 return TDK_MiscellaneousDeductionFailure;
3695
Richard Smith9095e5b2016-11-01 01:31:23 +00003696 // If the function has a dependent exception specification, resolve it now,
3697 // so we can check that the exception specification matches.
3698 auto *SpecializationFPT =
3699 Specialization->getType()->castAs<FunctionProtoType>();
3700 if (getLangOpts().CPlusPlus1z &&
3701 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3702 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3703 return TDK_MiscellaneousDeductionFailure;
3704
Richard Smithbaa47832016-12-01 02:11:49 +00003705 // Adjust the exception specification of the argument again to match the
3706 // substituted and resolved type we just formed. (Calling convention and
3707 // noreturn can't be dependent, so we don't actually need this for them
3708 // right now.)
3709 QualType SpecializationType = Specialization->getType();
3710 if (!IsAddressOfFunction)
3711 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3712 /*AdjustExceptionSpec*/true);
3713
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003714 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003715 // specialization with respect to arguments of compatible pointer to function
3716 // types, template argument deduction fails.
3717 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003718 if (IsAddressOfFunction &&
3719 !isSameOrCompatibleFunctionType(
3720 Context.getCanonicalType(SpecializationType),
3721 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003722 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003723
3724 if (!IsAddressOfFunction &&
3725 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003726 return TDK_MiscellaneousDeductionFailure;
3727 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003728
3729 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003730}
3731
Simon Pilgrim728134c2016-08-12 11:43:57 +00003732/// \brief Given a function declaration (e.g. a generic lambda conversion
3733/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003734/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3735/// to replace 'auto' with and not the actual result type you want
3736/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003737static inline void
3738SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003739 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003740 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003741 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003742 assert(AutoResultType->getContainedAutoType());
3743 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003744 TypeToReplaceAutoWith);
3745 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3746}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003747
Simon Pilgrim728134c2016-08-12 11:43:57 +00003748/// \brief Given a specialized conversion operator of a generic lambda
3749/// create the corresponding specializations of the call operator and
3750/// the static-invoker. If the return type of the call operator is auto,
3751/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003752/// return type of the destination function ptr.
3753
Simon Pilgrim728134c2016-08-12 11:43:57 +00003754static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003755SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3756 CXXConversionDecl *ConversionSpecialized,
3757 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3758 QualType ReturnTypeOfDestFunctionPtr,
3759 TemplateDeductionInfo &TDInfo,
3760 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003761
Faisal Vali2b3a3012013-10-24 23:40:02 +00003762 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003763 assert(LambdaClass && LambdaClass->isGenericLambda());
3764
Faisal Vali2b3a3012013-10-24 23:40:02 +00003765 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003766 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003767 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003768 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003769
3770 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003771 CallOpGeneric->getDescribedFunctionTemplate();
3772
Craig Topperc3ec1492014-05-26 06:22:03 +00003773 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003774 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003775 // generic lambda's call operator.
3776 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003777 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3778 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003779 0, CallOpSpecialized, TDInfo))
3780 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003781
Faisal Vali2b3a3012013-10-24 23:40:02 +00003782 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003783 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3784 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003785 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003786 CallOpSpecialized->getPointOfInstantiation(),
3787 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003788
Faisal Vali2b3a3012013-10-24 23:40:02 +00003789 // Check to see if the return type of the destination ptr-to-function
3790 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003791 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003792 ReturnTypeOfDestFunctionPtr))
3793 return Sema::TDK_NonDeducedMismatch;
3794 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003795 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003796 // specialized our corresponding call operator, we are ready to
3797 // specialize the static invoker with the deduced arguments of our
3798 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003799 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003800 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3801 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3802
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003803#ifndef NDEBUG
3804 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3805#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003806 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003807 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003808 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003809 "If the call operator succeeded so should the invoker!");
3810 // Set the result type to match the corresponding call operator
3811 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003812 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3813 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003814 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003815 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003816 // to substitute into the 'auto' of the invoker and conversion
3817 // function.
3818 // For e.g.
3819 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3820 // We don't want to subst 'int*' into 'auto' to get int**.
3821
Alp Toker314cc812014-01-25 16:55:45 +00003822 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3823 ->getContainedAutoType()
3824 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003825 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3826 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003827 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003828 TypeToReplaceAutoWith, S);
3829 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003830
Faisal Vali2b3a3012013-10-24 23:40:02 +00003831 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003832 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003833 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003834 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003835 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3836 getType().getTypePtr()->castAs<FunctionProtoType>();
3837 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3838 EPI.TypeQuals = 0;
3839 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003840 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003841 return Sema::TDK_Success;
3842}
Douglas Gregor05155d82009-08-21 23:19:43 +00003843/// \brief Deduce template arguments for a templated conversion
3844/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3845/// conversion function template specialization.
3846Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003847Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003848 QualType ToType,
3849 CXXConversionDecl *&Specialization,
3850 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003851 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003852 return TDK_Invalid;
3853
Faisal Vali2b3a3012013-10-24 23:40:02 +00003854 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003855 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3856
Faisal Vali2b3a3012013-10-24 23:40:02 +00003857 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003858
3859 // Canonicalize the types for deduction.
3860 QualType P = Context.getCanonicalType(FromType);
3861 QualType A = Context.getCanonicalType(ToType);
3862
Douglas Gregord99609a2011-03-06 09:03:20 +00003863 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003864 // If P is a reference type, the type referred to by P is used for
3865 // type deduction.
3866 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3867 P = PRef->getPointeeType();
3868
Douglas Gregord99609a2011-03-06 09:03:20 +00003869 // C++0x [temp.deduct.conv]p4:
3870 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003871 // for type deduction.
3872 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003873 A = ARef->getPointeeType().getUnqualifiedType();
3874 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003875 //
Mike Stump11289f42009-09-09 15:08:12 +00003876 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003877 else {
3878 assert(!A->isReferenceType() && "Reference types were handled above");
3879
3880 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003881 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003882 // of P for type deduction; otherwise,
3883 if (P->isArrayType())
3884 P = Context.getArrayDecayedType(P);
3885 // - If P is a function type, the pointer type produced by the
3886 // function-to-pointer standard conversion (4.3) is used in
3887 // place of P for type deduction; otherwise,
3888 else if (P->isFunctionType())
3889 P = Context.getPointerType(P);
3890 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003891 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003892 else
3893 P = P.getUnqualifiedType();
3894
Douglas Gregord99609a2011-03-06 09:03:20 +00003895 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003896 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003897 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003898 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003899 A = A.getUnqualifiedType();
3900 }
3901
Eli Friedman77dcc722012-02-08 03:07:05 +00003902 // Unevaluated SFINAE context.
3903 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003904 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003905
3906 // C++ [temp.deduct.conv]p1:
3907 // Template argument deduction is done by comparing the return
3908 // type of the template conversion function (call it P) with the
3909 // type that is required as the result of the conversion (call it
3910 // A) as described in 14.8.2.4.
3911 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003912 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003913 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003914 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003915
3916 // C++0x [temp.deduct.conv]p4:
3917 // In general, the deduction process attempts to find template
3918 // argument values that will make the deduced A identical to
3919 // A. However, there are two cases that allow a difference:
3920 unsigned TDF = 0;
3921 // - If the original A is a reference type, A can be more
3922 // cv-qualified than the deduced A (i.e., the type referred to
3923 // by the reference)
3924 if (ToType->isReferenceType())
3925 TDF |= TDF_ParamWithReferenceType;
3926 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003927 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003928 // conversion.
3929 //
3930 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3931 // both P and A are pointers or member pointers. In this case, we
3932 // just ignore cv-qualifiers completely).
3933 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003934 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003935 TDF |= TDF_IgnoreQualifiers;
3936 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003937 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3938 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003939 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003940
3941 // Create an Instantiation Scope for finalizing the operator.
3942 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003943 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003944 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003945 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003946 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003947 ConversionSpecialized, Info);
3948 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3949
3950 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003951 // to a ptr-to-function, use the deduced arguments from the conversion
3952 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003953 // e.g., int (*fp)(int) = [](auto a) { return a; };
3954 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003955
Faisal Vali2b3a3012013-10-24 23:40:02 +00003956 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003957 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003958 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003959 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003960 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003961 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003962 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003963 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3964
Simon Pilgrim728134c2016-08-12 11:43:57 +00003965 // Create the corresponding specializations of the call operator and
3966 // the static-invoker; and if the return type is auto,
3967 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003968 // DestFunctionPtrReturnType.
3969 // For instance:
3970 // auto L = [](auto a) { return f(a); };
3971 // int (*fp)(int) = L;
3972 // char (*fp2)(int) = L; <-- Not OK.
3973
3974 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003975 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003976 Info, *this);
3977 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003978 return Result;
3979}
3980
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003981/// \brief Deduce template arguments for a function template when there is
3982/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3983///
3984/// \param FunctionTemplate the function template for which we are performing
3985/// template argument deduction.
3986///
James Dennett18348b62012-06-22 08:52:37 +00003987/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003988/// arguments.
3989///
3990/// \param Specialization if template argument deduction was successful,
3991/// this will be set to the function template specialization produced by
3992/// template argument deduction.
3993///
3994/// \param Info the argument will be updated to provide additional information
3995/// about template argument deduction.
3996///
Richard Smithbaa47832016-12-01 02:11:49 +00003997/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3998/// the address of a function template in a context where we do not have a
3999/// target type, per [over.over]. If \c false, we are looking up a function
4000/// template specialization based on its signature, which only happens when
4001/// deducing a function parameter type from an argument that is a template-id
4002/// naming a function template specialization.
4003///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004004/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004005Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4006 FunctionTemplateDecl *FunctionTemplate,
4007 TemplateArgumentListInfo *ExplicitTemplateArgs,
4008 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4009 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004010 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004011 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004012 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004013}
4014
Richard Smith30482bc2011-02-20 03:19:35 +00004015namespace {
4016 /// Substitute the 'auto' type specifier within a type for a given replacement
4017 /// type.
4018 class SubstituteAutoTransform :
4019 public TreeTransform<SubstituteAutoTransform> {
4020 QualType Replacement;
4021 public:
Nico Weberc153d242014-07-28 00:02:09 +00004022 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
4023 : TreeTransform<SubstituteAutoTransform>(SemaRef),
4024 Replacement(Replacement) {}
4025
Richard Smith30482bc2011-02-20 03:19:35 +00004026 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4027 // If we're building the type pattern to deduce against, don't wrap the
4028 // substituted type in an AutoType. Certain template deduction rules
4029 // apply only when a template type parameter appears directly (and not if
4030 // the parameter is found through desugaring). For instance:
4031 // auto &&lref = lvalue;
4032 // must transform into "rvalue reference to T" not "rvalue reference to
4033 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00004034 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00004035 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00004036 TemplateTypeParmTypeLoc NewTL =
4037 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00004038 NewTL.setNameLoc(TL.getNameLoc());
4039 return Result;
4040 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00004041 bool Dependent =
4042 !Replacement.isNull() && Replacement->isDependentType();
4043 QualType Result =
4044 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00004045 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004046 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00004047 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4048 NewTL.setNameLoc(TL.getNameLoc());
4049 return Result;
4050 }
4051 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004052
4053 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4054 // Lambdas never need to be transformed.
4055 return E;
4056 }
Richard Smith061f1e22013-04-30 21:23:01 +00004057
Richard Smith2a7d4812013-05-04 07:00:32 +00004058 QualType Apply(TypeLoc TL) {
4059 // Create some scratch storage for the transformed type locations.
4060 // FIXME: We're just going to throw this information away. Don't build it.
4061 TypeLocBuilder TLB;
4062 TLB.reserve(TL.getFullDataSize());
4063 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004064 }
Richard Smith30482bc2011-02-20 03:19:35 +00004065 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004066}
Richard Smith30482bc2011-02-20 03:19:35 +00004067
Richard Smith2a7d4812013-05-04 07:00:32 +00004068Sema::DeduceAutoResult
4069Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
4070 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
4071}
4072
Richard Smith061f1e22013-04-30 21:23:01 +00004073/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004074///
4075/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004076/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004077/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004078/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00004079Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00004080Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00004081 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004082 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4083 if (NonPlaceholder.isInvalid())
4084 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004085 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004086 }
4087
Richard Smith2a7d4812013-05-04 07:00:32 +00004088 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004089 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004090 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004091 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004092 }
4093
Richard Smith74aeef52013-04-26 16:15:35 +00004094 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4095 // Since 'decltype(auto)' can only occur at the top of the type, we
4096 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004097 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004098 if (AT->isDecltypeAuto()) {
4099 if (isa<InitListExpr>(Init)) {
4100 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4101 return DAR_FailedAlreadyDiagnosed;
4102 }
4103
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004104 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004105 if (Deduced.isNull())
4106 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004107 // FIXME: Support a non-canonical deduced type for 'auto'.
4108 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004109 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004110 if (Result.isNull())
4111 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004112 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004113 } else if (!getLangOpts().CPlusPlus) {
4114 if (isa<InitListExpr>(Init)) {
4115 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4116 return DAR_FailedAlreadyDiagnosed;
4117 }
Richard Smith74aeef52013-04-26 16:15:35 +00004118 }
4119 }
4120
Richard Smith30482bc2011-02-20 03:19:35 +00004121 SourceLocation Loc = Init->getExprLoc();
4122
4123 LocalInstantiationScope InstScope(*this);
4124
4125 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004126 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004127 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4128 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004129 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4130 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004131 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4132 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004133
Richard Smith061f1e22013-04-30 21:23:01 +00004134 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4135 assert(!FuncParam.isNull() &&
4136 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004137
4138 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004139 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004140 Deduced.resize(1);
4141 QualType InitType = Init->getType();
4142 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004143
Craig Toppere6706e42012-09-19 02:26:47 +00004144 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004145
Richard Smith74801c82012-07-08 04:13:07 +00004146 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004147 if (InitList) {
4148 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004149 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4150 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004151 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004152 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004153 }
4154 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004155 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4156 Diag(Loc, diag::err_auto_bitfield);
4157 return DAR_FailedAlreadyDiagnosed;
4158 }
4159
James Y Knight7a22b242015-08-06 20:26:32 +00004160 if (AdjustFunctionParmAndArgTypesForDeduction(
4161 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004162 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004163
James Y Knight7a22b242015-08-06 20:26:32 +00004164 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4165 FuncParam, InitType, Info, Deduced,
4166 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004167 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004168 }
Richard Smith30482bc2011-02-20 03:19:35 +00004169
Eli Friedmane4310952012-11-06 23:56:42 +00004170 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004171 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004172
Eli Friedmane4310952012-11-06 23:56:42 +00004173 QualType DeducedType = Deduced[0].getAsType();
4174
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004175 if (InitList) {
4176 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4177 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004178 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004179 }
4180
Richard Smith061f1e22013-04-30 21:23:01 +00004181 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004182 if (Result.isNull())
4183 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004184
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004185 // Check that the deduced argument type is compatible with the original
4186 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004187 if (!InitList && !Result.isNull() &&
4188 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004189 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004190 Result)) {
4191 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004192 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004193 }
4194
Sebastian Redl09edce02012-01-23 22:09:39 +00004195 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004196}
4197
Simon Pilgrim728134c2016-08-12 11:43:57 +00004198QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004199 QualType TypeToReplaceAuto) {
4200 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4201 TransformType(TypeWithAuto);
4202}
4203
Simon Pilgrim728134c2016-08-12 11:43:57 +00004204TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004205 QualType TypeToReplaceAuto) {
4206 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4207 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004208}
4209
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004210void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4211 if (isa<InitListExpr>(Init))
4212 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004213 VDecl->isInitCapture()
4214 ? diag::err_init_capture_deduction_failure_from_init_list
4215 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004216 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4217 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004218 Diag(VDecl->getLocation(),
4219 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4220 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004221 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4222 << Init->getSourceRange();
4223}
4224
Richard Smith2a7d4812013-05-04 07:00:32 +00004225bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4226 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004227 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004228
4229 if (FD->getTemplateInstantiationPattern())
4230 InstantiateFunctionDefinition(Loc, FD);
4231
Alp Toker314cc812014-01-25 16:55:45 +00004232 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004233 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4234 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4235 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4236 }
4237
4238 return StillUndeduced;
4239}
4240
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004241static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004242MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004243 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004244 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004245 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004246
4247/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004248static void
4249AddImplicitObjectParameterType(ASTContext &Context,
4250 CXXMethodDecl *Method,
4251 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004252 // C++11 [temp.func.order]p3:
4253 // [...] The new parameter is of type "reference to cv A," where cv are
4254 // the cv-qualifiers of the function template (if any) and A is
4255 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004256 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004257 // The standard doesn't say explicitly, but we pick the appropriate kind of
4258 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004259 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4260 ArgTy = Context.getQualifiedType(ArgTy,
4261 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004262 if (Method->getRefQualifier() == RQ_RValue)
4263 ArgTy = Context.getRValueReferenceType(ArgTy);
4264 else
4265 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004266 ArgTypes.push_back(ArgTy);
4267}
4268
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004269/// \brief Determine whether the function template \p FT1 is at least as
4270/// specialized as \p FT2.
4271static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004272 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004273 FunctionTemplateDecl *FT1,
4274 FunctionTemplateDecl *FT2,
4275 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004276 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004277 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004279 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4280 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004282 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4283 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004284 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004285 Deduced.resize(TemplateParams->size());
4286
4287 // C++0x [temp.deduct.partial]p3:
4288 // The types used to determine the ordering depend on the context in which
4289 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004290 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004291 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004292 switch (TPOC) {
4293 case TPOC_Call: {
4294 // - In the context of a function call, the function parameter types are
4295 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004296 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4297 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004298
Eli Friedman3b5774a2012-09-19 23:27:04 +00004299 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004300 // [...] If only one of the function templates is a non-static
4301 // member, that function template is considered to have a new
4302 // first parameter inserted in its function parameter list. The
4303 // new parameter is of type "reference to cv A," where cv are
4304 // the cv-qualifiers of the function template (if any) and A is
4305 // the class of which the function template is a member.
4306 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004307 // Note that we interpret this to mean "if one of the function
4308 // templates is a non-static member and the other is a non-member";
4309 // otherwise, the ordering rules for static functions against non-static
4310 // functions don't make any sense.
4311 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004312 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4313 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004314 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004315
Richard Smithe5b52202013-09-11 00:52:39 +00004316 unsigned NumComparedArguments = NumCallArguments1;
4317
4318 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004319 // Compare 'this' from Method1 against first parameter from Method2.
4320 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4321 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004322 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004323 // Compare 'this' from Method2 against first parameter from Method1.
4324 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004325 }
4326
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004327 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004328 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004329 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004330 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331
Douglas Gregorb837ea42011-01-11 17:34:58 +00004332 // C++ [temp.func.order]p5:
4333 // The presence of unused ellipsis and default arguments has no effect on
4334 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004335 if (Args1.size() > NumComparedArguments)
4336 Args1.resize(NumComparedArguments);
4337 if (Args2.size() > NumComparedArguments)
4338 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004339 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4340 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004341 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004342 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004344 break;
4345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004347 case TPOC_Conversion:
4348 // - In the context of a call to a conversion operator, the return types
4349 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004350 if (DeduceTemplateArgumentsByTypeMatch(
4351 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4352 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004353 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004354 return false;
4355 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004357 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004358 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004359 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004360 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4361 FD2->getType(), FD1->getType(),
4362 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004363 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004364 return false;
4365 break;
4366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004368 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369 // In most cases, all template parameters must have values in order for
4370 // deduction to succeed, but for partial ordering purposes a template
4371 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004372 // types being used for partial ordering. [ Note: a template parameter used
4373 // in a non-deduced context is considered used. -end note]
4374 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4375 for (; ArgIdx != NumArgs; ++ArgIdx)
4376 if (Deduced[ArgIdx].isNull())
4377 break;
4378
4379 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004380 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004381 // as FT2.
4382 return true;
4383 }
4384
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004385 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004386 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004387 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004388 case TPOC_Call:
4389 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4390 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004391 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004392 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004393 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004395 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004396 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4397 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004398 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004400 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004401 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004402 TemplateParams->getDepth(),
4403 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004404 break;
4405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004407 for (; ArgIdx != NumArgs; ++ArgIdx)
4408 // If this argument had no value deduced but was used in one of the types
4409 // used for partial ordering, then deduction fails.
4410 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4411 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004413 return true;
4414}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415
Douglas Gregorcef1a032011-01-16 16:03:23 +00004416/// \brief Determine whether this a function template whose parameter-type-list
4417/// ends with a function parameter pack.
4418static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4419 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4420 unsigned NumParams = Function->getNumParams();
4421 if (NumParams == 0)
4422 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregorcef1a032011-01-16 16:03:23 +00004424 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4425 if (!Last->isParameterPack())
4426 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427
Douglas Gregorcef1a032011-01-16 16:03:23 +00004428 // Make sure that no previous parameter is a parameter pack.
4429 while (--NumParams > 0) {
4430 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4431 return false;
4432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433
Douglas Gregorcef1a032011-01-16 16:03:23 +00004434 return true;
4435}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436
Douglas Gregorbe999392009-09-15 16:23:51 +00004437/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004438/// to the rules of function template partial ordering (C++ [temp.func.order]).
4439///
4440/// \param FT1 the first function template
4441///
4442/// \param FT2 the second function template
4443///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004444/// \param TPOC the context in which we are performing partial ordering of
4445/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004446///
Richard Smithe5b52202013-09-11 00:52:39 +00004447/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4448/// only when \c TPOC is \c TPOC_Call.
4449///
4450/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4451/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004452///
Douglas Gregorbe999392009-09-15 16:23:51 +00004453/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004454/// template is more specialized, returns NULL.
4455FunctionTemplateDecl *
4456Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4457 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004458 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004459 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004460 unsigned NumCallArguments1,
4461 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004462 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004463 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004465 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004466
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004467 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004468 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004469
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004470 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004471 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004472
Douglas Gregorcef1a032011-01-16 16:03:23 +00004473 // FIXME: This mimics what GCC implements, but doesn't match up with the
4474 // proposed resolution for core issue 692. This area needs to be sorted out,
4475 // but for now we attempt to maintain compatibility.
4476 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4477 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4478 if (Variadic1 != Variadic2)
4479 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004480
Craig Topperc3ec1492014-05-26 06:22:03 +00004481 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004482}
Douglas Gregor9b146582009-07-08 20:55:45 +00004483
Douglas Gregor450f00842009-09-25 18:43:00 +00004484/// \brief Determine if the two templates are equivalent.
4485static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4486 if (T1 == T2)
4487 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004488
Douglas Gregor450f00842009-09-25 18:43:00 +00004489 if (!T1 || !T2)
4490 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491
Douglas Gregor450f00842009-09-25 18:43:00 +00004492 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4493}
4494
4495/// \brief Retrieve the most specialized of the given function template
4496/// specializations.
4497///
John McCall58cc69d2010-01-27 01:50:18 +00004498/// \param SpecBegin the start iterator of the function template
4499/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004500///
John McCall58cc69d2010-01-27 01:50:18 +00004501/// \param SpecEnd the end iterator of the function template
4502/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004503///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004505/// diagnostic should occur.
4506///
4507/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4508/// no matching candidates.
4509///
4510/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4511/// occurs.
4512///
4513/// \param CandidateDiag partial diagnostic used for each function template
4514/// specialization that is a candidate in the ambiguous ordering. One parameter
4515/// in this diagnostic should be unbound, which will correspond to the string
4516/// describing the template arguments for the function template specialization.
4517///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004519/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004520UnresolvedSetIterator Sema::getMostSpecialized(
4521 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4522 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004523 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4524 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4525 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004526 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004527 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004528 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004529 FailedCandidates.NoteCandidates(*this, Loc);
4530 }
John McCall58cc69d2010-01-27 01:50:18 +00004531 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533
4534 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004535 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004536
Douglas Gregor450f00842009-09-25 18:43:00 +00004537 // Find the function template that is better than all of the templates it
4538 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004539 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004541 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004542 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004543 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4544 FunctionTemplateDecl *Challenger
4545 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004546 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004547 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004548 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004549 Challenger)) {
4550 Best = I;
4551 BestTemplate = Challenger;
4552 }
4553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554
Douglas Gregor450f00842009-09-25 18:43:00 +00004555 // Make sure that the "best" function template is more specialized than all
4556 // of the others.
4557 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004558 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4559 FunctionTemplateDecl *Challenger
4560 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004561 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004563 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004564 BestTemplate)) {
4565 Ambiguous = true;
4566 break;
4567 }
4568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004569
Douglas Gregor450f00842009-09-25 18:43:00 +00004570 if (!Ambiguous) {
4571 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004572 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574
Douglas Gregor450f00842009-09-25 18:43:00 +00004575 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004576 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004577 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
Richard Smithb875c432013-05-04 01:51:08 +00004579 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004580 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4581 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004582 const auto *FD = cast<FunctionDecl>(*I);
4583 PD << FD << getTemplateArgumentBindingsText(
4584 FD->getPrimaryTemplate()->getTemplateParameters(),
4585 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004586 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004587 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004588 Diag((*I)->getLocation(), PD);
4589 }
Richard Smithb875c432013-05-04 01:51:08 +00004590 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591
John McCall58cc69d2010-01-27 01:50:18 +00004592 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004593}
4594
Douglas Gregorbe999392009-09-15 16:23:51 +00004595/// \brief Returns the more specialized class template partial specialization
4596/// according to the rules of partial ordering of class template partial
4597/// specializations (C++ [temp.class.order]).
4598///
4599/// \param PS1 the first class template partial specialization
4600///
4601/// \param PS2 the second class template partial specialization
4602///
4603/// \returns the more specialized class template partial specialization. If
4604/// neither partial specialization is more specialized, returns NULL.
4605ClassTemplatePartialSpecializationDecl *
4606Sema::getMoreSpecializedPartialSpecialization(
4607 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004608 ClassTemplatePartialSpecializationDecl *PS2,
4609 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004610 // C++ [temp.class.order]p1:
4611 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612 // specialized as the second if, given the following rewrite to two
4613 // function templates, the first function template is at least as
4614 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004615 // templates (14.6.6.2):
4616 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004617 // first partial specialization and has a single function parameter
4618 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004619 // arguments of the first partial specialization, and
4620 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621 // second partial specialization and has a single function parameter
4622 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004623 // arguments of the second partial specialization.
4624 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004625 // Rather than synthesize function templates, we merely perform the
4626 // equivalent partial ordering by performing deduction directly on
4627 // the template arguments of the class template partial
4628 // specializations. This computation is slightly simpler than the
4629 // general problem of function template partial ordering, because
4630 // class template partial specializations are more constrained. We
4631 // know that every template parameter is deducible from the class
4632 // template partial specialization's template arguments, for
4633 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004634 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004635 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004636
4637 QualType PT1 = PS1->getInjectedSpecializationType();
4638 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004639
Douglas Gregorbe999392009-09-15 16:23:51 +00004640 // Determine whether PS1 is at least as specialized as PS2
4641 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004642 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4643 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004644 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004645 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004646 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004647 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004648 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004649 Better1 = !::FinishTemplateArgumentDeduction(
4650 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4651 }
4652
4653 // Determine whether PS2 is at least as specialized as PS1
4654 Deduced.clear();
4655 Deduced.resize(PS1->getTemplateParameters()->size());
4656 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4657 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004658 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004659 if (Better2) {
4660 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4661 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004662 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004663 Better2 = !::FinishTemplateArgumentDeduction(
4664 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4665 }
4666
4667 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004668 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004669
4670 return Better1 ? PS1 : PS2;
4671}
4672
Larisse Voufo30616382013-08-23 22:21:36 +00004673/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4674/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4675/// VarTemplate(Partial)SpecializationDecl with a new data
4676/// structure Template(Partial)SpecializationDecl, and
4677/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004678VarTemplatePartialSpecializationDecl *
4679Sema::getMoreSpecializedPartialSpecialization(
4680 VarTemplatePartialSpecializationDecl *PS1,
4681 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4682 SmallVector<DeducedTemplateArgument, 4> Deduced;
4683 TemplateDeductionInfo Info(Loc);
4684
Richard Smithf04fd0b2013-12-12 23:14:16 +00004685 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004686 "the partial specializations being compared should specialize"
4687 " the same template.");
4688 TemplateName Name(PS1->getSpecializedTemplate());
4689 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4690 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004691 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004692 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004693 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004694
4695 // Determine whether PS1 is at least as specialized as PS2
4696 Deduced.resize(PS2->getTemplateParameters()->size());
4697 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4698 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004699 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004700 if (Better1) {
4701 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4702 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004703 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004704 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4705 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004706 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708
Douglas Gregorbe999392009-09-15 16:23:51 +00004709 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004710 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004711 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004712 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4713 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004714 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004715 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004716 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004717 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004718 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004719 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4720 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004721 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723
Douglas Gregorbe999392009-09-15 16:23:51 +00004724 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004725 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004726
Douglas Gregorbe999392009-09-15 16:23:51 +00004727 return Better1? PS1 : PS2;
4728}
4729
Mike Stump11289f42009-09-09 15:08:12 +00004730static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004731MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004732 const TemplateArgument &TemplateArg,
4733 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004734 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004735 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004736
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004737/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004738/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004739static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004740MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004741 const Expr *E,
4742 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004743 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004744 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004745 // We can deduce from a pack expansion.
4746 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4747 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748
Richard Smith34349002012-07-09 03:07:20 +00004749 // Skip through any implicit casts we added while type-checking, and any
4750 // substitutions performed by template alias expansion.
4751 while (1) {
4752 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4753 E = ICE->getSubExpr();
4754 else if (const SubstNonTypeTemplateParmExpr *Subst =
4755 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4756 E = Subst->getReplacement();
4757 else
4758 break;
4759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760
4761 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004762 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004763 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004764 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004765 return;
4766
Mike Stump11289f42009-09-09 15:08:12 +00004767 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004768 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4769 if (!NTTP)
4770 return;
4771
Douglas Gregor21610382009-10-29 00:04:11 +00004772 if (NTTP->getDepth() == Depth)
4773 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004774
4775 // In C++1z mode, additional arguments may be deduced from the type of a
4776 // non-type argument.
4777 if (Ctx.getLangOpts().CPlusPlus1z)
4778 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004779}
4780
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004781/// \brief Mark the template parameters that are used by the given
4782/// nested name specifier.
4783static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004784MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004785 NestedNameSpecifier *NNS,
4786 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004787 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004788 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004789 if (!NNS)
4790 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004792 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004793 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004794 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004795 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004796}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004798/// \brief Mark the template parameters that are used by the given
4799/// template name.
4800static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004801MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004802 TemplateName Name,
4803 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004804 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004805 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004806 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4807 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004808 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4809 if (TTP->getDepth() == Depth)
4810 Used[TTP->getIndex()] = true;
4811 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004812 return;
4813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004814
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004815 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004816 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004817 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004818 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004819 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004820 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004821}
4822
4823/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004824/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004825static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004826MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004827 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004828 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004829 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004830 if (T.isNull())
4831 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832
Douglas Gregor91772d12009-06-13 00:26:55 +00004833 // Non-dependent types have nothing deducible
4834 if (!T->isDependentType())
4835 return;
4836
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004837 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004838 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004839 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004840 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004841 cast<PointerType>(T)->getPointeeType(),
4842 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004843 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004844 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004845 break;
4846
4847 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004848 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004849 cast<BlockPointerType>(T)->getPointeeType(),
4850 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004851 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004852 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004853 break;
4854
4855 case Type::LValueReference:
4856 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004857 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004858 cast<ReferenceType>(T)->getPointeeType(),
4859 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004860 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004861 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004862 break;
4863
4864 case Type::MemberPointer: {
4865 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004866 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004867 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004868 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004869 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004870 break;
4871 }
4872
4873 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004874 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004875 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004876 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004877 // Fall through to check the element type
4878
4879 case Type::ConstantArray:
4880 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004881 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004882 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004883 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004884 break;
4885
4886 case Type::Vector:
4887 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004888 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004889 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004890 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004891 break;
4892
Douglas Gregor758a8692009-06-17 21:51:59 +00004893 case Type::DependentSizedExtVector: {
4894 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004895 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004896 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004897 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004898 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004899 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004900 break;
4901 }
4902
Douglas Gregor91772d12009-06-13 00:26:55 +00004903 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004904 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004905 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4906 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004907 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4908 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004909 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004910 break;
4911 }
4912
Douglas Gregor21610382009-10-29 00:04:11 +00004913 case Type::TemplateTypeParm: {
4914 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4915 if (TTP->getDepth() == Depth)
4916 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004917 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004918 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004919
Douglas Gregorfb322d82011-01-14 05:11:40 +00004920 case Type::SubstTemplateTypeParmPack: {
4921 const SubstTemplateTypeParmPackType *Subst
4922 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004923 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004924 QualType(Subst->getReplacedParameter(), 0),
4925 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004926 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004927 OnlyDeduced, Depth, Used);
4928 break;
4929 }
4930
John McCall2408e322010-04-27 00:57:59 +00004931 case Type::InjectedClassName:
4932 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4933 // fall through
4934
Douglas Gregor91772d12009-06-13 00:26:55 +00004935 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004936 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004937 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004938 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004939 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940
Douglas Gregord0ad2942010-12-23 01:24:45 +00004941 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004942 // If the template argument list of P contains a pack expansion that is
4943 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004944 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004945 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00004946 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00004947 break;
4948
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004949 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004950 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004951 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004952 break;
4953 }
4954
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004955 case Type::Complex:
4956 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004957 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004958 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004959 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004960 break;
4961
Eli Friedman0dfb8892011-10-06 23:00:33 +00004962 case Type::Atomic:
4963 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004964 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004965 cast<AtomicType>(T)->getValueType(),
4966 OnlyDeduced, Depth, Used);
4967 break;
4968
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004969 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004970 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004971 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004972 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004973 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004974 break;
4975
John McCallc392f372010-06-11 00:33:02 +00004976 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004977 // C++14 [temp.deduct.type]p5:
4978 // The non-deduced contexts are:
4979 // -- The nested-name-specifier of a type that was specified using a
4980 // qualified-id
4981 //
4982 // C++14 [temp.deduct.type]p6:
4983 // When a type name is specified in a way that includes a non-deduced
4984 // context, all of the types that comprise that type name are also
4985 // non-deduced.
4986 if (OnlyDeduced)
4987 break;
4988
John McCallc392f372010-06-11 00:33:02 +00004989 const DependentTemplateSpecializationType *Spec
4990 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004991
Richard Smith50d5b972015-12-30 20:56:05 +00004992 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4993 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004994
John McCallc392f372010-06-11 00:33:02 +00004995 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004996 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004997 Used);
4998 break;
4999 }
5000
John McCallbd8d9bd2010-03-01 23:49:17 +00005001 case Type::TypeOf:
5002 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005003 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005004 cast<TypeOfType>(T)->getUnderlyingType(),
5005 OnlyDeduced, Depth, Used);
5006 break;
5007
5008 case Type::TypeOfExpr:
5009 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005010 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005011 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5012 OnlyDeduced, Depth, Used);
5013 break;
5014
5015 case Type::Decltype:
5016 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005017 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005018 cast<DecltypeType>(T)->getUnderlyingExpr(),
5019 OnlyDeduced, Depth, Used);
5020 break;
5021
Alexis Hunte852b102011-05-24 22:41:36 +00005022 case Type::UnaryTransform:
5023 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005024 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005025 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005026 OnlyDeduced, Depth, Used);
5027 break;
5028
Douglas Gregord2fa7662010-12-20 02:24:11 +00005029 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005030 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005031 cast<PackExpansionType>(T)->getPattern(),
5032 OnlyDeduced, Depth, Used);
5033 break;
5034
Richard Smith30482bc2011-02-20 03:19:35 +00005035 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005036 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00005037 cast<AutoType>(T)->getDeducedType(),
5038 OnlyDeduced, Depth, Used);
5039
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005040 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005041 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005042 case Type::VariableArray:
5043 case Type::FunctionNoProto:
5044 case Type::Record:
5045 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005046 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005047 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005048 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005049 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005050 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005051#define TYPE(Class, Base)
5052#define ABSTRACT_TYPE(Class, Base)
5053#define DEPENDENT_TYPE(Class, Base)
5054#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5055#include "clang/AST/TypeNodes.def"
5056 break;
5057 }
5058}
5059
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005060/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005061/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005062static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005063MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005064 const TemplateArgument &TemplateArg,
5065 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005066 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005067 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005068 switch (TemplateArg.getKind()) {
5069 case TemplateArgument::Null:
5070 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005071 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005072 break;
Mike Stump11289f42009-09-09 15:08:12 +00005073
Eli Friedmanb826a002012-09-26 02:36:12 +00005074 case TemplateArgument::NullPtr:
5075 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5076 Depth, Used);
5077 break;
5078
Douglas Gregor91772d12009-06-13 00:26:55 +00005079 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005080 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005081 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005082 break;
5083
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005084 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005085 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005086 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005087 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005088 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005089 break;
5090
5091 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005092 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005093 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005094 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095
Anders Carlssonbc343912009-06-15 17:04:53 +00005096 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005097 for (const auto &P : TemplateArg.pack_elements())
5098 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005099 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005100 }
5101}
5102
James Dennett41725122012-06-22 10:16:05 +00005103/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005104/// template argument list.
5105///
5106/// \param TemplateArgs the template argument list from which template
5107/// parameters will be deduced.
5108///
James Dennett41725122012-06-22 10:16:05 +00005109/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005110/// to indicate when the corresponding template parameter will be
5111/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005112void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005113Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005114 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005115 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005116 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117 // If the template argument list of P contains a pack expansion that is not
5118 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005119 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005120 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005121 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005122 return;
5123
Douglas Gregor91772d12009-06-13 00:26:55 +00005124 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005125 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005126 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005127}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005128
5129/// \brief Marks all of the template parameters that will be deduced by a
5130/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005131void Sema::MarkDeducedTemplateParameters(
5132 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5133 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005134 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005135 = FunctionTemplate->getTemplateParameters();
5136 Deduced.clear();
5137 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005138
Douglas Gregorce23bae2009-09-18 23:21:38 +00005139 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5140 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005141 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005142 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005143}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005144
5145bool hasDeducibleTemplateParameters(Sema &S,
5146 FunctionTemplateDecl *FunctionTemplate,
5147 QualType T) {
5148 if (!T->isDependentType())
5149 return false;
5150
5151 TemplateParameterList *TemplateParams
5152 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005153 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005154 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005155 Deduced);
5156
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005157 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005158}