blob: 75740b64d192976b201f830218f4904c2a91e984 [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,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000108 const TemplateArgument *Params, unsigned NumParams,
109 const TemplateArgument *Args, unsigned NumArgs,
110 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.
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000523 return DeduceTemplateArguments(S, TemplateParams, Param->getArgs(),
524 Param->getNumArgs(), SpecArg->getArgs(),
525 SpecArg->getNumArgs(), Info, Deduced,
526 /*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.
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000557 return DeduceTemplateArguments(
558 S, TemplateParams, Param->getArgs(), Param->getNumArgs(),
559 SpecArg->getTemplateArgs().data(), SpecArg->getTemplateArgs().size(),
560 Info, Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000561}
562
John McCall08569062010-08-28 22:14:41 +0000563/// \brief Determines whether the given type is an opaque type that
564/// might be more qualified when instantiated.
565static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
566 switch (T->getTypeClass()) {
567 case Type::TypeOfExpr:
568 case Type::TypeOf:
569 case Type::DependentName:
570 case Type::Decltype:
571 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000572 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000573 return true;
574
575 case Type::ConstantArray:
576 case Type::IncompleteArray:
577 case Type::VariableArray:
578 case Type::DependentSizedArray:
579 return IsPossiblyOpaquelyQualifiedType(
580 cast<ArrayType>(T)->getElementType());
581
582 default:
583 return false;
584 }
585}
586
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000587/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000588static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000589getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000590 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
591 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000592
Douglas Gregor5499af42011-01-05 23:12:31 +0000593 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
594 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregor5499af42011-01-05 23:12:31 +0000596 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
597 return std::make_pair(TTP->getDepth(), TTP->getIndex());
598}
599
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000600/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000602getDepthAndIndex(UnexpandedParameterPack UPP) {
603 if (const TemplateTypeParmType *TTP
604 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
605 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000606
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000607 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
608}
609
Douglas Gregor5499af42011-01-05 23:12:31 +0000610/// \brief Helper function to build a TemplateParameter when we don't
611/// know its type statically.
612static TemplateParameter makeTemplateParameter(Decl *D) {
613 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
614 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000615 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000616 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000617
Douglas Gregor5499af42011-01-05 23:12:31 +0000618 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
619}
620
Richard Smith0a80d572014-05-29 01:12:14 +0000621/// A pack that we're currently deducing.
622struct clang::DeducedPack {
623 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000624
Richard Smith0a80d572014-05-29 01:12:14 +0000625 // The index of the pack.
626 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
Richard Smith0a80d572014-05-29 01:12:14 +0000628 // The old value of the pack before we started deducing it.
629 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000630
Richard Smith0a80d572014-05-29 01:12:14 +0000631 // A deferred value of this pack from an inner deduction, that couldn't be
632 // deduced because this deduction hadn't happened yet.
633 DeducedTemplateArgument DeferredDeduction;
634
635 // The new value of the pack.
636 SmallVector<DeducedTemplateArgument, 4> New;
637
638 // The outer deduction for this pack, if any.
639 DeducedPack *Outer;
640};
641
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000642namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000643/// A scope in which we're performing pack deduction.
644class PackDeductionScope {
645public:
646 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
647 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
648 TemplateDeductionInfo &Info, TemplateArgument Pattern)
649 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
650 // Compute the set of template parameter indices that correspond to
651 // parameter packs expanded by the pack expansion.
652 {
653 llvm::SmallBitVector SawIndices(TemplateParams->size());
654 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
655 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
656 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
657 unsigned Depth, Index;
658 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
659 if (Depth == 0 && !SawIndices[Index]) {
660 SawIndices[Index] = true;
661
662 // Save the deduced template argument for the parameter pack expanded
663 // by this pack expansion, then clear out the deduction.
664 DeducedPack Pack(Index);
665 Pack.Saved = Deduced[Index];
666 Deduced[Index] = TemplateArgument();
667
668 Packs.push_back(Pack);
669 }
670 }
671 }
672 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
673
674 for (auto &Pack : Packs) {
675 if (Info.PendingDeducedPacks.size() > Pack.Index)
676 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
677 else
678 Info.PendingDeducedPacks.resize(Pack.Index + 1);
679 Info.PendingDeducedPacks[Pack.Index] = &Pack;
680
681 if (S.CurrentInstantiationScope) {
682 // If the template argument pack was explicitly specified, add that to
683 // the set of deduced arguments.
684 const TemplateArgument *ExplicitArgs;
685 unsigned NumExplicitArgs;
686 NamedDecl *PartiallySubstitutedPack =
687 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
688 &ExplicitArgs, &NumExplicitArgs);
689 if (PartiallySubstitutedPack &&
690 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
691 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
692 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000693 }
694 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000695
Richard Smith0a80d572014-05-29 01:12:14 +0000696 ~PackDeductionScope() {
697 for (auto &Pack : Packs)
698 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000699 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000700
Richard Smith0a80d572014-05-29 01:12:14 +0000701 /// Move to deducing the next element in each pack that is being deduced.
702 void nextPackElement() {
703 // Capture the deduced template arguments for each parameter pack expanded
704 // by this pack expansion, add them to the list of arguments we've deduced
705 // for that pack, then clear out the deduced argument.
706 for (auto &Pack : Packs) {
707 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
708 if (!DeducedArg.isNull()) {
709 Pack.New.push_back(DeducedArg);
710 DeducedArg = DeducedTemplateArgument();
711 }
712 }
713 }
714
715 /// \brief Finish template argument deduction for a set of argument packs,
716 /// producing the argument packs and checking for consistency with prior
717 /// deductions.
718 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
719 // Build argument packs for each of the parameter packs expanded by this
720 // pack expansion.
721 for (auto &Pack : Packs) {
722 // Put back the old value for this pack.
723 Deduced[Pack.Index] = Pack.Saved;
724
725 // Build or find a new value for this pack.
726 DeducedTemplateArgument NewPack;
727 if (HasAnyArguments && Pack.New.empty()) {
728 if (Pack.DeferredDeduction.isNull()) {
729 // We were not able to deduce anything for this parameter pack
730 // (because it only appeared in non-deduced contexts), so just
731 // restore the saved argument pack.
732 continue;
733 }
734
735 NewPack = Pack.DeferredDeduction;
736 Pack.DeferredDeduction = TemplateArgument();
737 } else if (Pack.New.empty()) {
738 // If we deduced an empty argument pack, create it now.
739 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
740 } else {
741 TemplateArgument *ArgumentPack =
742 new (S.Context) TemplateArgument[Pack.New.size()];
743 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
744 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000745 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000746 Pack.New[0].wasDeducedFromArrayBound());
747 }
748
749 // Pick where we're going to put the merged pack.
750 DeducedTemplateArgument *Loc;
751 if (Pack.Outer) {
752 if (Pack.Outer->DeferredDeduction.isNull()) {
753 // Defer checking this pack until we have a complete pack to compare
754 // it against.
755 Pack.Outer->DeferredDeduction = NewPack;
756 continue;
757 }
758 Loc = &Pack.Outer->DeferredDeduction;
759 } else {
760 Loc = &Deduced[Pack.Index];
761 }
762
763 // Check the new pack matches any previous value.
764 DeducedTemplateArgument OldPack = *Loc;
765 DeducedTemplateArgument Result =
766 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
767
768 // If we deferred a deduction of this pack, check that one now too.
769 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
770 OldPack = Result;
771 NewPack = Pack.DeferredDeduction;
772 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
773 }
774
775 if (Result.isNull()) {
776 Info.Param =
777 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
778 Info.FirstArg = OldPack;
779 Info.SecondArg = NewPack;
780 return Sema::TDK_Inconsistent;
781 }
782
783 *Loc = Result;
784 }
785
786 return Sema::TDK_Success;
787 }
788
789private:
790 Sema &S;
791 TemplateParameterList *TemplateParams;
792 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
793 TemplateDeductionInfo &Info;
794
795 SmallVector<DeducedPack, 2> Packs;
796};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000797} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000798
Douglas Gregor5499af42011-01-05 23:12:31 +0000799/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800/// types to the list of argument types, as in the parameter-type-lists of
801/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000802///
803/// \param S The semantic analysis object within which we are deducing
804///
805/// \param TemplateParams The template parameters that we are deducing
806///
807/// \param Params The list of parameter types
808///
809/// \param NumParams The number of types in \c Params
810///
811/// \param Args The list of argument types
812///
813/// \param NumArgs The number of types in \c Args
814///
815/// \param Info information about the template argument deduction itself
816///
817/// \param Deduced the deduced template arguments
818///
819/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
820/// how template argument deduction is performed.
821///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000822/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000823/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000824/// (C++0x [temp.deduct.partial]).
825///
Douglas Gregor5499af42011-01-05 23:12:31 +0000826/// \returns the result of template argument deduction so far. Note that a
827/// "success" result means that template argument deduction has not yet failed,
828/// but it may still fail, later, for other reasons.
829static Sema::TemplateDeductionResult
830DeduceTemplateArguments(Sema &S,
831 TemplateParameterList *TemplateParams,
832 const QualType *Params, unsigned NumParams,
833 const QualType *Args, unsigned NumArgs,
834 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000835 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000836 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000837 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000838 // Fast-path check to see if we have too many/too few arguments.
839 if (NumParams != NumArgs &&
840 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
841 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000842 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843
Douglas Gregor5499af42011-01-05 23:12:31 +0000844 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000845 // Similarly, if P has a form that contains (T), then each parameter type
846 // Pi of the respective parameter-type- list of P is compared with the
847 // corresponding parameter type Ai of the corresponding parameter-type-list
848 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000849 unsigned ArgIdx = 0, ParamIdx = 0;
850 for (; ParamIdx != NumParams; ++ParamIdx) {
851 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000852 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000853 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
854 if (!Expansion) {
855 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856
Douglas Gregor5499af42011-01-05 23:12:31 +0000857 // Make sure we have an argument.
858 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000859 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000860
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000861 if (isa<PackExpansionType>(Args[ArgIdx])) {
862 // C++0x [temp.deduct.type]p22:
863 // If the original function parameter associated with A is a function
864 // parameter pack and the function parameter associated with P is not
865 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000866 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Douglas Gregor5499af42011-01-05 23:12:31 +0000869 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000870 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
871 Params[ParamIdx], Args[ArgIdx],
872 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000873 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000874 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875
Douglas Gregor5499af42011-01-05 23:12:31 +0000876 ++ArgIdx;
877 continue;
878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000880 // C++0x [temp.deduct.type]p5:
881 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000882 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000883 // parameter-declaration-clause.
884 if (ParamIdx + 1 < NumParams)
885 return Sema::TDK_Success;
886
Douglas Gregor5499af42011-01-05 23:12:31 +0000887 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000889 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000890 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000891 // comparison deduces template arguments for subsequent positions in the
892 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000893
Douglas Gregor5499af42011-01-05 23:12:31 +0000894 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000895 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000896
Douglas Gregor5499af42011-01-05 23:12:31 +0000897 bool HasAnyArguments = false;
898 for (; ArgIdx < NumArgs; ++ArgIdx) {
899 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000900
Douglas Gregor5499af42011-01-05 23:12:31 +0000901 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000902 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000903 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
904 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000905 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000906 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000907
Richard Smith0a80d572014-05-29 01:12:14 +0000908 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000910
Douglas Gregor5499af42011-01-05 23:12:31 +0000911 // Build argument packs for each of the parameter packs expanded by this
912 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000913 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000914 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916
Douglas Gregor5499af42011-01-05 23:12:31 +0000917 // Make sure we don't have any extra arguments.
918 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000919 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920
Douglas Gregor5499af42011-01-05 23:12:31 +0000921 return Sema::TDK_Success;
922}
923
Douglas Gregor1d684c22011-04-28 00:56:09 +0000924/// \brief Determine whether the parameter has qualifiers that are either
925/// inconsistent with or a superset of the argument's qualifiers.
926static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
927 QualType ArgType) {
928 Qualifiers ParamQs = ParamType.getQualifiers();
929 Qualifiers ArgQs = ArgType.getQualifiers();
930
931 if (ParamQs == ArgQs)
932 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000933
Douglas Gregor1d684c22011-04-28 00:56:09 +0000934 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000935 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000936 ParamQs.hasObjCGCAttr())
937 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000938
Douglas Gregor1d684c22011-04-28 00:56:09 +0000939 // Mismatched (but not missing) address spaces.
940 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
941 ParamQs.hasAddressSpace())
942 return true;
943
John McCall31168b02011-06-15 23:02:42 +0000944 // Mismatched (but not missing) Objective-C lifetime qualifiers.
945 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
946 ParamQs.hasObjCLifetime())
947 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000948
Douglas Gregor1d684c22011-04-28 00:56:09 +0000949 // CVR qualifier superset.
950 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
951 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
952 == ParamQs.getCVRQualifiers());
953}
954
Douglas Gregor19a41f12013-04-17 08:45:07 +0000955/// \brief Compare types for equality with respect to possibly compatible
956/// function types (noreturn adjustment, implicit calling conventions). If any
957/// of parameter and argument is not a function, just perform type comparison.
958///
959/// \param Param the template parameter type.
960///
961/// \param Arg the argument type.
962bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
963 CanQualType Arg) {
964 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
965 *ArgFunction = Arg->getAs<FunctionType>();
966
967 // Just compare if not functions.
968 if (!ParamFunction || !ArgFunction)
969 return Param == Arg;
970
Richard Smith3c4f8d22016-10-16 17:54:23 +0000971 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000972 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000973 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000974 return Arg == Context.getCanonicalType(AdjustedParam);
975
976 // FIXME: Compatible calling conventions.
977
978 return Param == Arg;
979}
980
Douglas Gregorcceb9752009-06-26 18:27:22 +0000981/// \brief Deduce the template arguments by comparing the parameter type and
982/// the argument type (C++ [temp.deduct.type]).
983///
Chandler Carruthc1263112010-02-07 21:33:28 +0000984/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000985///
986/// \param TemplateParams the template parameters that we are deducing
987///
988/// \param ParamIn the parameter type
989///
990/// \param ArgIn the argument type
991///
992/// \param Info information about the template argument deduction itself
993///
994/// \param Deduced the deduced template arguments
995///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000996/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000997/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000998///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000999/// \param PartialOrdering Whether we're performing template argument deduction
1000/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1001///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001002/// \returns the result of template argument deduction so far. Note that a
1003/// "success" result means that template argument deduction has not yet failed,
1004/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001005static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001006DeduceTemplateArgumentsByTypeMatch(Sema &S,
1007 TemplateParameterList *TemplateParams,
1008 QualType ParamIn, QualType ArgIn,
1009 TemplateDeductionInfo &Info,
1010 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1011 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001012 bool PartialOrdering,
1013 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001014 // We only want to look at the canonical types, since typedefs and
1015 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001016 QualType Param = S.Context.getCanonicalType(ParamIn);
1017 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001018
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001019 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001021 if (const PackExpansionType *ArgExpansion
1022 = dyn_cast<PackExpansionType>(Arg))
1023 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001024
Douglas Gregorb837ea42011-01-11 17:34:58 +00001025 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001026 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027 // Before the partial ordering is done, certain transformations are
1028 // performed on the types used for partial ordering:
1029 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001030 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1031 if (ParamRef)
1032 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
Douglas Gregorb837ea42011-01-11 17:34:58 +00001034 // - If A is a reference type, A is replaced by the type referred to.
1035 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1036 if (ArgRef)
1037 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001038
Richard Smithed563c22015-02-20 04:45:22 +00001039 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1040 // C++11 [temp.deduct.partial]p9:
1041 // If, for a given type, deduction succeeds in both directions (i.e.,
1042 // the types are identical after the transformations above) and both
1043 // P and A were reference types [...]:
1044 // - if [one type] was an lvalue reference and [the other type] was
1045 // not, [the other type] is not considered to be at least as
1046 // specialized as [the first type]
1047 // - if [one type] is more cv-qualified than [the other type],
1048 // [the other type] is not considered to be at least as specialized
1049 // as [the first type]
1050 // Objective-C ARC adds:
1051 // - [one type] has non-trivial lifetime, [the other type] has
1052 // __unsafe_unretained lifetime, and the types are otherwise
1053 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001054 //
Richard Smithed563c22015-02-20 04:45:22 +00001055 // A is "considered to be at least as specialized" as P iff deduction
1056 // succeeds, so we model this as a deduction failure. Note that
1057 // [the first type] is P and [the other type] is A here; the standard
1058 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001059 Qualifiers ParamQuals = Param.getQualifiers();
1060 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001061 if ((ParamRef->isLValueReferenceType() &&
1062 !ArgRef->isLValueReferenceType()) ||
1063 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1064 (ParamQuals.hasNonTrivialObjCLifetime() &&
1065 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1066 ParamQuals.withoutObjCLifetime() ==
1067 ArgQuals.withoutObjCLifetime())) {
1068 Info.FirstArg = TemplateArgument(ParamIn);
1069 Info.SecondArg = TemplateArgument(ArgIn);
1070 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001071 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001073
Richard Smithed563c22015-02-20 04:45:22 +00001074 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001075 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001076 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001077 // version of P.
1078 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001079 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001080 // version of A.
1081 Arg = Arg.getUnqualifiedType();
1082 } else {
1083 // C++0x [temp.deduct.call]p4 bullet 1:
1084 // - If the original P is a reference type, the deduced A (i.e., the type
1085 // referred to by the reference) can be more cv-qualified than the
1086 // transformed A.
1087 if (TDF & TDF_ParamWithReferenceType) {
1088 Qualifiers Quals;
1089 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1090 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001091 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001092 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094
Douglas Gregor85f240c2011-01-25 17:19:08 +00001095 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1096 // C++0x [temp.deduct.type]p10:
1097 // If P and A are function types that originated from deduction when
1098 // taking the address of a function template (14.8.2.2) or when deducing
1099 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001100 // Ai are parameters of the top-level parameter-type-list of P and A,
1101 // respectively, Pi is adjusted if it is an rvalue reference to a
1102 // cv-unqualified template parameter and Ai is an lvalue reference, in
1103 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001104 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1105 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001106 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001107 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108
Douglas Gregor85f240c2011-01-25 17:19:08 +00001109 if (const RValueReferenceType *ParamRef
1110 = Param->getAs<RValueReferenceType>()) {
1111 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1112 !ParamRef->getPointeeType().getQualifiers())
1113 if (Arg->isLValueReferenceType())
1114 Param = ParamRef->getPointeeType();
1115 }
1116 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001118
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001119 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001120 // A template type argument T, a template template argument TT or a
1121 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001122 // the following forms:
1123 //
1124 // T
1125 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001126 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001127 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001128 // Just skip any attempts to deduce from a placeholder type.
1129 if (Arg->isPlaceholderType())
1130 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001131
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001132 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001133 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001134
Douglas Gregor60454822009-07-22 20:02:25 +00001135 // If the argument type is an array type, move the qualifiers up to the
1136 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001137 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001138 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001139 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001140 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001141 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001142 RecanonicalizeArg = true;
1143 }
1144 }
Mike Stump11289f42009-09-09 15:08:12 +00001145
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001146 // The argument type can not be less qualified than the parameter
1147 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001148 if (!(TDF & TDF_IgnoreQualifiers) &&
1149 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001150 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001151 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001152 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001153 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001154 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001155
1156 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001157 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001158 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001159
Douglas Gregor1d684c22011-04-28 00:56:09 +00001160 // Remove any qualifiers on the parameter from the deduced type.
1161 // We checked the qualifiers for consistency above.
1162 Qualifiers DeducedQs = DeducedType.getQualifiers();
1163 Qualifiers ParamQs = Param.getQualifiers();
1164 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1165 if (ParamQs.hasObjCGCAttr())
1166 DeducedQs.removeObjCGCAttr();
1167 if (ParamQs.hasAddressSpace())
1168 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001169 if (ParamQs.hasObjCLifetime())
1170 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001171
Douglas Gregore46db902011-06-17 22:11:49 +00001172 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001173 // If template deduction would produce a lifetime qualifier on a type
1174 // that is not a lifetime type, template argument deduction fails.
1175 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1176 !DeducedType->isDependentType()) {
1177 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1178 Info.FirstArg = TemplateArgument(Param);
1179 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001180 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001181 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001182
Douglas Gregora4f2b432011-07-26 14:53:44 +00001183 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001184 // If template deduction would produce an argument type with lifetime type
1185 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001186 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001187 DeducedType->isObjCLifetimeType() &&
1188 !DeducedQs.hasObjCLifetime())
1189 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001190
Douglas Gregor1d684c22011-04-28 00:56:09 +00001191 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1192 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001193
Douglas Gregord6605db2009-07-22 21:30:48 +00001194 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001195 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001196
Richard Smith5f274382016-09-28 23:55:27 +00001197 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001198 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001199 Deduced[Index],
1200 NewDeduced);
1201 if (Result.isNull()) {
1202 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1203 Info.FirstArg = Deduced[Index];
1204 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001205 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001207
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001208 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001210 }
1211
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001212 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001213 Info.FirstArg = TemplateArgument(ParamIn);
1214 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001215
Douglas Gregorfb322d82011-01-14 05:11:40 +00001216 // If the parameter is an already-substituted template parameter
1217 // pack, do nothing: we don't know which of its arguments to look
1218 // at, so we have to wait until all of the parameter packs in this
1219 // expansion have arguments.
1220 if (isa<SubstTemplateTypeParmPackType>(Param))
1221 return Sema::TDK_Success;
1222
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001223 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001224 CanQualType CanParam = S.Context.getCanonicalType(Param);
1225 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001226 if (!(TDF & TDF_IgnoreQualifiers)) {
1227 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001228 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001229 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001230 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001231 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001232 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001233 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001234
Douglas Gregor194ea692012-03-11 03:29:50 +00001235 // If the parameter type is not dependent, there is nothing to deduce.
1236 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001237 if (!(TDF & TDF_SkipNonDependent)) {
1238 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1239 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1240 Param != Arg;
1241 if (NonDeduced) {
1242 return Sema::TDK_NonDeducedMismatch;
1243 }
1244 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001245 return Sema::TDK_Success;
1246 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001247 } else if (!Param->isDependentType()) {
1248 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1249 ArgUnqualType = CanArg.getUnqualifiedType();
1250 bool Success = (TDF & TDF_InOverloadResolution)?
1251 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1252 ArgUnqualType) :
1253 ParamUnqualType == ArgUnqualType;
1254 if (Success)
1255 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001256 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001257
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001258 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001259 // Non-canonical types cannot appear here.
1260#define NON_CANONICAL_TYPE(Class, Base) \
1261 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1262#define TYPE(Class, Base)
1263#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001264
Douglas Gregor39c02722011-06-15 16:02:29 +00001265 case Type::TemplateTypeParm:
1266 case Type::SubstTemplateTypeParmPack:
1267 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001268
1269 // These types cannot be dependent, so simply check whether the types are
1270 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001271 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001272 case Type::VariableArray:
1273 case Type::Vector:
1274 case Type::FunctionNoProto:
1275 case Type::Record:
1276 case Type::Enum:
1277 case Type::ObjCObject:
1278 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001279 case Type::ObjCObjectPointer: {
1280 if (TDF & TDF_SkipNonDependent)
1281 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001282
Douglas Gregor194ea692012-03-11 03:29:50 +00001283 if (TDF & TDF_IgnoreQualifiers) {
1284 Param = Param.getUnqualifiedType();
1285 Arg = Arg.getUnqualifiedType();
1286 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001287
Douglas Gregor194ea692012-03-11 03:29:50 +00001288 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1289 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001290
1291 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001292 case Type::Complex:
1293 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001294 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1295 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001296 ComplexArg->getElementType(),
1297 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001298
1299 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001300
1301 // _Atomic T [extension]
1302 case Type::Atomic:
1303 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001304 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001305 cast<AtomicType>(Param)->getValueType(),
1306 AtomicArg->getValueType(),
1307 Info, Deduced, TDF);
1308
1309 return Sema::TDK_NonDeducedMismatch;
1310
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001311 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001312 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001313 QualType PointeeType;
1314 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1315 PointeeType = PointerArg->getPointeeType();
1316 } else if (const ObjCObjectPointerType *PointerArg
1317 = Arg->getAs<ObjCObjectPointerType>()) {
1318 PointeeType = PointerArg->getPointeeType();
1319 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001320 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Douglas Gregorfc516c92009-06-26 23:27:24 +00001323 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001324 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1325 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001326 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001327 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001328 }
Mike Stump11289f42009-09-09 15:08:12 +00001329
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001330 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001331 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001332 const LValueReferenceType *ReferenceArg =
1333 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001334 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001335 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001336
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001337 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001338 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001339 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001340 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001341
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001342 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001343 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001344 const RValueReferenceType *ReferenceArg =
1345 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001346 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001347 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001348
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001349 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1350 cast<RValueReferenceType>(Param)->getPointeeType(),
1351 ReferenceArg->getPointeeType(),
1352 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001353 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001355 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001356 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001357 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001358 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001359 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001360 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001361
John McCallf7332682010-08-19 00:20:19 +00001362 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001363 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1364 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1365 IncompleteArrayArg->getElementType(),
1366 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001367 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001368
1369 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001370 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001371 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001372 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001373 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001374 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001375
1376 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001377 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001378 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001379 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001380
John McCallf7332682010-08-19 00:20:19 +00001381 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001382 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1383 ConstantArrayParm->getElementType(),
1384 ConstantArrayArg->getElementType(),
1385 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001386 }
1387
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001388 // type [i]
1389 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001390 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001391 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001392 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001393
John McCallf7332682010-08-19 00:20:19 +00001394 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1395
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001396 // Check the element type of the arrays
1397 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001398 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001399 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001400 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1401 DependentArrayParm->getElementType(),
1402 ArrayArg->getElementType(),
1403 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001404 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001405
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001406 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001407 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001408 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1409 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001410 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001411
1412 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001413 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001414 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001415 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001416 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001417 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1418 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001419 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001420 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001421 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001422 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001423 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001424 if (const DependentSizedArrayType *DependentArrayArg
1425 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001426 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001427 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001428 DependentArrayArg->getSizeExpr(),
1429 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001430
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001431 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001432 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001433 }
Mike Stump11289f42009-09-09 15:08:12 +00001434
1435 // type(*)(T)
1436 // T(*)()
1437 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001438 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001439 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001440 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001441 dyn_cast<FunctionProtoType>(Arg);
1442 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001443 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001444
1445 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001446 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001447
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001448 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001449 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001450 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001451 != FunctionProtoArg->getRefQualifier() ||
1452 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001453 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001454
Anders Carlsson2128ec72009-06-08 15:19:08 +00001455 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001456 if (Sema::TemplateDeductionResult Result =
1457 DeduceTemplateArgumentsByTypeMatch(
1458 S, TemplateParams, FunctionProtoParam->getReturnType(),
1459 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001460 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001461
Alp Toker9cacbab2014-01-20 20:26:09 +00001462 return DeduceTemplateArguments(
1463 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1464 FunctionProtoParam->getNumParams(),
1465 FunctionProtoArg->param_type_begin(),
1466 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001467 }
Mike Stump11289f42009-09-09 15:08:12 +00001468
John McCalle78aac42010-03-10 03:28:59 +00001469 case Type::InjectedClassName: {
1470 // Treat a template's injected-class-name as if the template
1471 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001472 Param = cast<InjectedClassNameType>(Param)
1473 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001474 assert(isa<TemplateSpecializationType>(Param) &&
1475 "injected class name is not a template specialization type");
1476 // fall through
1477 }
1478
Douglas Gregor705c9002009-06-26 20:57:09 +00001479 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001480 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001481 // TT<T>
1482 // TT<i>
1483 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001484 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001485 const TemplateSpecializationType *SpecParam =
1486 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001487
Richard Smith9b296e32016-04-25 19:09:05 +00001488 // When Arg cannot be a derived class, we can just try to deduce template
1489 // arguments from the template-id.
1490 const RecordType *RecordT = Arg->getAs<RecordType>();
1491 if (!(TDF & TDF_DerivedClass) || !RecordT)
1492 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1493 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001494
Richard Smith9b296e32016-04-25 19:09:05 +00001495 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1496 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001497
Richard Smith9b296e32016-04-25 19:09:05 +00001498 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1499 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001500
Richard Smith9b296e32016-04-25 19:09:05 +00001501 if (Result == Sema::TDK_Success)
1502 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001503
Richard Smith9b296e32016-04-25 19:09:05 +00001504 // We cannot inspect base classes as part of deduction when the type
1505 // is incomplete, so either instantiate any templates necessary to
1506 // complete the type, or skip over it if it cannot be completed.
1507 if (!S.isCompleteType(Info.getLocation(), Arg))
1508 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001509
Richard Smith9b296e32016-04-25 19:09:05 +00001510 // C++14 [temp.deduct.call] p4b3:
1511 // If P is a class and P has the form simple-template-id, then the
1512 // transformed A can be a derived class of the deduced A. Likewise if
1513 // P is a pointer to a class of the form simple-template-id, the
1514 // transformed A can be a pointer to a derived class pointed to by the
1515 // deduced A.
1516 //
1517 // These alternatives are considered only if type deduction would
1518 // otherwise fail. If they yield more than one possible deduced A, the
1519 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001520
Faisal Vali683b0742016-05-19 02:28:21 +00001521 // Reset the incorrectly deduced argument from above.
1522 Deduced = DeducedOrig;
1523
1524 // Use data recursion to crawl through the list of base classes.
1525 // Visited contains the set of nodes we have already visited, while
1526 // ToVisit is our stack of records that we still need to visit.
1527 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1528 SmallVector<const RecordType *, 8> ToVisit;
1529 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001530 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001531 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001532 while (!ToVisit.empty()) {
1533 // Retrieve the next class in the inheritance hierarchy.
1534 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001535
Faisal Vali683b0742016-05-19 02:28:21 +00001536 // If we have already seen this type, skip it.
1537 if (!Visited.insert(NextT).second)
1538 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001539
Faisal Vali683b0742016-05-19 02:28:21 +00001540 // If this is a base class, try to perform template argument
1541 // deduction from it.
1542 if (NextT != RecordT) {
1543 TemplateDeductionInfo BaseInfo(Info.getLocation());
1544 Sema::TemplateDeductionResult BaseResult =
1545 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1546 QualType(NextT, 0), BaseInfo, Deduced);
1547
1548 // If template argument deduction for this base was successful,
1549 // note that we had some success. Otherwise, ignore any deductions
1550 // from this base class.
1551 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001552 // If we've already seen some success, then deduction fails due to
1553 // an ambiguity (temp.deduct.call p5).
1554 if (Successful)
1555 return Sema::TDK_MiscellaneousDeductionFailure;
1556
Faisal Vali683b0742016-05-19 02:28:21 +00001557 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001558 std::swap(SuccessfulDeduced, Deduced);
1559
Faisal Vali683b0742016-05-19 02:28:21 +00001560 Info.Param = BaseInfo.Param;
1561 Info.FirstArg = BaseInfo.FirstArg;
1562 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001563 }
1564
1565 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001566 }
Mike Stump11289f42009-09-09 15:08:12 +00001567
Faisal Vali683b0742016-05-19 02:28:21 +00001568 // Visit base classes
1569 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1570 for (const auto &Base : Next->bases()) {
1571 assert(Base.getType()->isRecordType() &&
1572 "Base class that isn't a record?");
1573 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1574 }
1575 }
Mike Stump11289f42009-09-09 15:08:12 +00001576
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001577 if (Successful) {
1578 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001579 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001580 }
Richard Smith9b296e32016-04-25 19:09:05 +00001581
Douglas Gregore81f3e72009-07-07 23:09:34 +00001582 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001583 }
1584
Douglas Gregor637d9982009-06-10 23:47:09 +00001585 // T type::*
1586 // T T::*
1587 // T (type::*)()
1588 // type (T::*)()
1589 // type (type::*)(T)
1590 // type (T::*)(T)
1591 // T (type::*)(T)
1592 // T (T::*)()
1593 // T (T::*)(T)
1594 case Type::MemberPointer: {
1595 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1596 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1597 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001598 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001599
David Majnemera381cda2015-11-30 20:34:28 +00001600 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1601 if (ParamPointeeType->isFunctionType())
1602 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1603 /*IsCtorOrDtor=*/false, Info.getLocation());
1604 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1605 if (ArgPointeeType->isFunctionType())
1606 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1607 /*IsCtorOrDtor=*/false, Info.getLocation());
1608
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001609 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001610 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001611 ParamPointeeType,
1612 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001613 Info, Deduced,
1614 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001615 return Result;
1616
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001617 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1618 QualType(MemPtrParam->getClass(), 0),
1619 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001620 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001621 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001622 }
1623
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001624 // (clang extension)
1625 //
Mike Stump11289f42009-09-09 15:08:12 +00001626 // type(^)(T)
1627 // T(^)()
1628 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001629 case Type::BlockPointer: {
1630 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1631 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001632
Anders Carlssona767eee2009-06-12 16:23:10 +00001633 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001634 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001635
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001636 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1637 BlockPtrParam->getPointeeType(),
1638 BlockPtrArg->getPointeeType(),
1639 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001640 }
1641
Douglas Gregor39c02722011-06-15 16:02:29 +00001642 // (clang extension)
1643 //
1644 // T __attribute__(((ext_vector_type(<integral constant>))))
1645 case Type::ExtVector: {
1646 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1647 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1648 // Make sure that the vectors have the same number of elements.
1649 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1650 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001651
Douglas Gregor39c02722011-06-15 16:02:29 +00001652 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001653 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1654 VectorParam->getElementType(),
1655 VectorArg->getElementType(),
1656 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001657 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001658
1659 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001660 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1661 // We can't check the number of elements, since the argument has a
1662 // dependent number of elements. This can only occur during partial
1663 // ordering.
1664
1665 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001666 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1667 VectorParam->getElementType(),
1668 VectorArg->getElementType(),
1669 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001670 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001671
Douglas Gregor39c02722011-06-15 16:02:29 +00001672 return Sema::TDK_NonDeducedMismatch;
1673 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001674
Douglas Gregor39c02722011-06-15 16:02:29 +00001675 // (clang extension)
1676 //
1677 // T __attribute__(((ext_vector_type(N))))
1678 case Type::DependentSizedExtVector: {
1679 const DependentSizedExtVectorType *VectorParam
1680 = cast<DependentSizedExtVectorType>(Param);
1681
1682 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1683 // Perform deduction on the element types.
1684 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001685 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1686 VectorParam->getElementType(),
1687 VectorArg->getElementType(),
1688 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001689 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001690
Douglas Gregor39c02722011-06-15 16:02:29 +00001691 // Perform deduction on the vector size, if we can.
1692 NonTypeTemplateParmDecl *NTTP
1693 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1694 if (!NTTP)
1695 return Sema::TDK_Success;
1696
1697 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1698 ArgSize = VectorArg->getNumElements();
Richard Smith5f274382016-09-28 23:55:27 +00001699 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith593d6a12016-12-23 01:30:39 +00001700 S.Context.IntTy, false, Info,
1701 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001702 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001703
1704 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001705 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1706 // Perform deduction on the element types.
1707 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001708 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1709 VectorParam->getElementType(),
1710 VectorArg->getElementType(),
1711 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001712 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001713
Douglas Gregor39c02722011-06-15 16:02:29 +00001714 // Perform deduction on the vector size, if we can.
1715 NonTypeTemplateParmDecl *NTTP
1716 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1717 if (!NTTP)
1718 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001719
Richard Smith5f274382016-09-28 23:55:27 +00001720 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1721 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001722 Info, Deduced);
1723 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001724
Douglas Gregor39c02722011-06-15 16:02:29 +00001725 return Sema::TDK_NonDeducedMismatch;
1726 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001727
Douglas Gregor637d9982009-06-10 23:47:09 +00001728 case Type::TypeOfExpr:
1729 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001730 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001731 case Type::UnresolvedUsing:
1732 case Type::Decltype:
1733 case Type::UnaryTransform:
1734 case Type::Auto:
1735 case Type::DependentTemplateSpecialization:
1736 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001737 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001738 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001739 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001740 }
1741
David Blaikiee4d798f2012-01-20 21:50:17 +00001742 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001743}
1744
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001745static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001746DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001747 TemplateParameterList *TemplateParams,
1748 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001749 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001750 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001751 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001752 // If the template argument is a pack expansion, perform template argument
1753 // deduction against the pattern of that expansion. This only occurs during
1754 // partial ordering.
1755 if (Arg.isPackExpansion())
1756 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001758 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001759 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001760 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001761
1762 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001763 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001764 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1765 Param.getAsType(),
1766 Arg.getAsType(),
1767 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001768 Info.FirstArg = Param;
1769 Info.SecondArg = Arg;
1770 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001771
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001772 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001773 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001775 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001776 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001777 Info.FirstArg = Param;
1778 Info.SecondArg = Arg;
1779 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001780
1781 case TemplateArgument::TemplateExpansion:
1782 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001783
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001784 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001785 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001786 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001787 return Sema::TDK_Success;
1788
1789 Info.FirstArg = Param;
1790 Info.SecondArg = Arg;
1791 return Sema::TDK_NonDeducedMismatch;
1792
1793 case TemplateArgument::NullPtr:
1794 if (Arg.getKind() == TemplateArgument::NullPtr &&
1795 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001796 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001797
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001798 Info.FirstArg = Param;
1799 Info.SecondArg = Arg;
1800 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001801
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001802 case TemplateArgument::Integral:
1803 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001804 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001805 return Sema::TDK_Success;
1806
1807 Info.FirstArg = Param;
1808 Info.SecondArg = Arg;
1809 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001810 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001811
1812 if (Arg.getKind() == TemplateArgument::Expression) {
1813 Info.FirstArg = Param;
1814 Info.SecondArg = Arg;
1815 return Sema::TDK_NonDeducedMismatch;
1816 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001817
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001818 Info.FirstArg = Param;
1819 Info.SecondArg = Arg;
1820 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001821
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001822 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001823 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001824 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1825 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001826 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001827 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001828 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001829 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001830 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001831 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001832 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1833 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001834 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001835 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001836 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1837 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001838 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001839 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1840 Arg.getAsDecl(),
1841 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001842 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001843
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001844 Info.FirstArg = Param;
1845 Info.SecondArg = Arg;
1846 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001847 }
Mike Stump11289f42009-09-09 15:08:12 +00001848
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001849 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001850 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001851 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001852 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001853 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
David Blaikiee4d798f2012-01-20 21:50:17 +00001856 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001857}
1858
Douglas Gregor7baabef2010-12-22 18:17:10 +00001859/// \brief Determine whether there is a template argument to be used for
1860/// deduction.
1861///
1862/// This routine "expands" argument packs in-place, overriding its input
1863/// parameters so that \c Args[ArgIdx] will be the available template argument.
1864///
1865/// \returns true if there is another template argument (which will be at
1866/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001867static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001868 unsigned &ArgIdx,
1869 unsigned &NumArgs) {
1870 if (ArgIdx == NumArgs)
1871 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001872
Douglas Gregor7baabef2010-12-22 18:17:10 +00001873 const TemplateArgument &Arg = Args[ArgIdx];
1874 if (Arg.getKind() != TemplateArgument::Pack)
1875 return true;
1876
1877 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1878 Args = Arg.pack_begin();
1879 NumArgs = Arg.pack_size();
1880 ArgIdx = 0;
1881 return ArgIdx < NumArgs;
1882}
1883
Douglas Gregord0ad2942010-12-23 01:24:45 +00001884/// \brief Determine whether the given set of template arguments has a pack
1885/// expansion that is not the last template argument.
1886static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1887 unsigned NumArgs) {
1888 unsigned ArgIdx = 0;
1889 while (ArgIdx < NumArgs) {
1890 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891
Douglas Gregord0ad2942010-12-23 01:24:45 +00001892 // Unwrap argument packs.
1893 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1894 Args = Arg.pack_begin();
1895 NumArgs = Arg.pack_size();
1896 ArgIdx = 0;
1897 continue;
1898 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001899
Douglas Gregord0ad2942010-12-23 01:24:45 +00001900 ++ArgIdx;
1901 if (ArgIdx == NumArgs)
1902 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903
Douglas Gregord0ad2942010-12-23 01:24:45 +00001904 if (Arg.isPackExpansion())
1905 return true;
1906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907
Douglas Gregord0ad2942010-12-23 01:24:45 +00001908 return false;
1909}
1910
Douglas Gregor7baabef2010-12-22 18:17:10 +00001911static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001912DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001913 const TemplateArgument *Params, unsigned NumParams,
1914 const TemplateArgument *Args, unsigned NumArgs,
1915 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001916 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1917 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001918 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919 // If the template argument list of P contains a pack expansion that is not
1920 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001921 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001922 if (hasPackExpansionBeforeEnd(Params, NumParams))
1923 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001925 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926 // If P has a form that contains <T> or <i>, then each argument Pi of the
1927 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001928 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001929 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001930 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001931 ++ParamIdx) {
1932 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001933 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001934
Douglas Gregor7baabef2010-12-22 18:17:10 +00001935 // Check whether we have enough arguments.
1936 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001937 return NumberOfArgumentsMustMatch ? Sema::TDK_TooFewArguments
1938 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001939
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001940 if (Args[ArgIdx].isPackExpansion()) {
1941 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1942 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001943 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001944 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001946 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001947 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001948 = DeduceTemplateArguments(S, TemplateParams,
1949 Params[ParamIdx], Args[ArgIdx],
1950 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951 return Result;
1952
Douglas Gregor7baabef2010-12-22 18:17:10 +00001953 // Move to the next argument.
1954 ++ArgIdx;
1955 continue;
1956 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001958 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001960 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001961 // If Pi is a pack expansion, then the pattern of Pi is compared with
1962 // each remaining argument in the template argument list of A. Each
1963 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001964 // template parameter packs expanded by Pi.
1965 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001966
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001967 // FIXME: If there are no remaining arguments, we can bail out early
1968 // and set any deduced parameter packs to an empty argument pack.
1969 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970
Richard Smith0a80d572014-05-29 01:12:14 +00001971 // Prepare to deduce the packs within the pattern.
1972 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001973
1974 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001976 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001977 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001978 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001979 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001981 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001983 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1984 Info, Deduced))
1985 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Richard Smith0a80d572014-05-29 01:12:14 +00001987 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001988 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001989
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001990 // Build argument packs for each of the parameter packs expanded by this
1991 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001992 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995
Douglas Gregor7baabef2010-12-22 18:17:10 +00001996 return Sema::TDK_Success;
1997}
1998
Mike Stump11289f42009-09-09 15:08:12 +00001999static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002000DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002001 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002002 const TemplateArgumentList &ParamList,
2003 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002004 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002005 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00002007 ParamList.data(), ParamList.size(),
2008 ArgList.data(), ArgList.size(),
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002009 Info, Deduced, false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002010}
2011
Douglas Gregor705c9002009-06-26 20:57:09 +00002012/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002013static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00002014 const TemplateArgument &X,
2015 const TemplateArgument &Y) {
2016 if (X.getKind() != Y.getKind())
2017 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002018
Douglas Gregor705c9002009-06-26 20:57:09 +00002019 switch (X.getKind()) {
2020 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002021 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002022
Douglas Gregor705c9002009-06-26 20:57:09 +00002023 case TemplateArgument::Type:
2024 return Context.getCanonicalType(X.getAsType()) ==
2025 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002026
Douglas Gregor705c9002009-06-26 20:57:09 +00002027 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002028 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002029
2030 case TemplateArgument::NullPtr:
2031 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002032
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002033 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002034 case TemplateArgument::TemplateExpansion:
2035 return Context.getCanonicalTemplateName(
2036 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2037 Context.getCanonicalTemplateName(
2038 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002039
Douglas Gregor705c9002009-06-26 20:57:09 +00002040 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002041 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00002042
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002043 case TemplateArgument::Expression: {
2044 llvm::FoldingSetNodeID XID, YID;
2045 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002046 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002047 return XID == YID;
2048 }
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor705c9002009-06-26 20:57:09 +00002050 case TemplateArgument::Pack:
2051 if (X.pack_size() != Y.pack_size())
2052 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002053
2054 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2055 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002056 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002057 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00002058 if (!isSameTemplateArg(Context, *XP, *YP))
2059 return false;
2060
2061 return true;
2062 }
2063
David Blaikiee4d798f2012-01-20 21:50:17 +00002064 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002065}
2066
Douglas Gregorca4686d2011-01-04 23:35:54 +00002067/// \brief Allocate a TemplateArgumentLoc where all locations have
2068/// been initialized to the given location.
2069///
James Dennett634962f2012-06-14 21:40:34 +00002070/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002071/// location information for.
2072///
2073/// \param NTTPType For a declaration template argument, the type of
2074/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002075/// argument. Can be null if no type sugar is available to add to the
2076/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002077///
2078/// \param Loc The source location to use for the resulting template
2079/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002080TemplateArgumentLoc
2081Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2082 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002083 switch (Arg.getKind()) {
2084 case TemplateArgument::Null:
2085 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
Douglas Gregorca4686d2011-01-04 23:35:54 +00002087 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002088 return TemplateArgumentLoc(
2089 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090
Douglas Gregorca4686d2011-01-04 23:35:54 +00002091 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002092 if (NTTPType.isNull())
2093 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002094 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2095 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002096 return TemplateArgumentLoc(TemplateArgument(E), E);
2097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098
Eli Friedmanb826a002012-09-26 02:36:12 +00002099 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002100 if (NTTPType.isNull())
2101 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002102 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2103 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002104 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2105 E);
2106 }
2107
Douglas Gregorca4686d2011-01-04 23:35:54 +00002108 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002109 Expr *E =
2110 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002111 return TemplateArgumentLoc(TemplateArgument(E), E);
2112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002113
Douglas Gregor9d802122011-03-02 17:09:35 +00002114 case TemplateArgument::Template:
2115 case TemplateArgument::TemplateExpansion: {
2116 NestedNameSpecifierLocBuilder Builder;
2117 TemplateName Template = Arg.getAsTemplate();
2118 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002119 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002120 else if (QualifiedTemplateName *QTN =
2121 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002122 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002123
Douglas Gregor9d802122011-03-02 17:09:35 +00002124 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002125 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002126 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002127
2128 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002129 Loc, Loc);
2130 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002131
Douglas Gregorca4686d2011-01-04 23:35:54 +00002132 case TemplateArgument::Expression:
2133 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002134
Douglas Gregorca4686d2011-01-04 23:35:54 +00002135 case TemplateArgument::Pack:
2136 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002138
David Blaikiee4d798f2012-01-20 21:50:17 +00002139 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002140}
2141
2142
2143/// \brief Convert the given deduced template argument and add it to the set of
2144/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002145static bool
2146ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2147 DeducedTemplateArgument Arg,
2148 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002149 TemplateDeductionInfo &Info,
2150 bool InFunctionTemplate,
2151 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002152 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2153 unsigned ArgumentPackIndex) {
2154 // Convert the deduced template argument into a template
2155 // argument that we can check, almost as if the user had written
2156 // the template argument explicitly.
2157 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002158 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002159
2160 // Check the template argument, converting it as necessary.
2161 return S.CheckTemplateArgument(
2162 Param, ArgLoc, Template, Template->getLocation(),
2163 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2164 InFunctionTemplate
2165 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2166 : Sema::CTAK_Deduced)
2167 : Sema::CTAK_Specified);
2168 };
2169
Douglas Gregorca4686d2011-01-04 23:35:54 +00002170 if (Arg.getKind() == TemplateArgument::Pack) {
2171 // This is a template argument pack, so check each of its arguments against
2172 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002173 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002174 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002175 // When converting the deduced template argument, append it to the
2176 // general output list. We need to do this so that the template argument
2177 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002178 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002179 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002180 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2181 "deduced nested pack");
2182 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002183 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184
Douglas Gregor51bc5712011-01-05 20:52:18 +00002185 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002186 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188
Richard Smithdf18ee92016-02-03 20:40:30 +00002189 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002190 // itself, in case that substitution fails.
2191 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002192 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002193 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002194 MultiLevelTemplateArgumentList Args(TemplateArgs);
2195
2196 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2197 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2198 NTTP, Output,
2199 Template->getSourceRange());
2200 if (Inst.isInvalid() ||
2201 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2202 NTTP->getDeclName()).isNull())
2203 return true;
2204 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2205 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2206 TTP, Output,
2207 Template->getSourceRange());
2208 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2209 return true;
2210 }
2211 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002212 }
Richard Smith37acb792016-02-03 20:15:01 +00002213
Douglas Gregorca4686d2011-01-04 23:35:54 +00002214 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002215 Output.push_back(
2216 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002217 return false;
2218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002219
Richard Smith37acb792016-02-03 20:15:01 +00002220 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002221}
2222
Richard Smith1f5be4d2016-12-21 01:10:31 +00002223// FIXME: This should not be a template, but
2224// ClassTemplatePartialSpecializationDecl sadly does not derive from
2225// TemplateDecl.
2226template<typename TemplateDeclT>
2227static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2228 Sema &S, TemplateDeclT *Template,
2229 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2230 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2231 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2232 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2233 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2234
2235 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2236 NamedDecl *Param = TemplateParams->getParam(I);
2237
2238 if (!Deduced[I].isNull()) {
2239 if (I < NumAlreadyConverted) {
2240 // We have already fully type-checked and converted this
2241 // argument, because it was explicitly-specified. Just record the
2242 // presence of this argument.
2243 Builder.push_back(Deduced[I]);
2244 // We may have had explicitly-specified template arguments for a
2245 // template parameter pack (that may or may not have been extended
2246 // via additional deduced arguments).
2247 if (Param->isParameterPack() && CurrentInstantiationScope) {
2248 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2249 Param) {
2250 // Forget the partially-substituted pack; its substitution is now
2251 // complete.
2252 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2253 }
2254 }
2255 continue;
2256 }
2257
2258 // We have deduced this argument, so it still needs to be
2259 // checked and converted.
2260 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2261 isa<FunctionTemplateDecl>(Template),
2262 Builder)) {
2263 Info.Param = makeTemplateParameter(Param);
2264 // FIXME: These template arguments are temporary. Free them!
2265 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2266 return Sema::TDK_SubstitutionFailure;
2267 }
2268
2269 continue;
2270 }
2271
2272 // C++0x [temp.arg.explicit]p3:
2273 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2274 // be deduced to an empty sequence of template arguments.
2275 // FIXME: Where did the word "trailing" come from?
2276 if (Param->isTemplateParameterPack()) {
2277 // We may have had explicitly-specified template arguments for this
2278 // template parameter pack. If so, our empty deduction extends the
2279 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2280 const TemplateArgument *ExplicitArgs;
2281 unsigned NumExplicitArgs;
2282 if (CurrentInstantiationScope &&
2283 CurrentInstantiationScope->getPartiallySubstitutedPack(
2284 &ExplicitArgs, &NumExplicitArgs) == Param) {
2285 Builder.push_back(TemplateArgument(
2286 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2287
2288 // Forget the partially-substituted pack; its substitution is now
2289 // complete.
2290 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2291 } else {
2292 // Go through the motions of checking the empty argument pack against
2293 // the parameter pack.
2294 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2295 if (ConvertDeducedTemplateArgument(
2296 S, Param, DeducedPack, Template, Info,
2297 isa<FunctionTemplateDecl>(Template), Builder)) {
2298 Info.Param = makeTemplateParameter(Param);
2299 // FIXME: These template arguments are temporary. Free them!
2300 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2301 return Sema::TDK_SubstitutionFailure;
2302 }
2303 }
2304 continue;
2305 }
2306
2307 // Substitute into the default template argument, if available.
2308 bool HasDefaultArg = false;
2309 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2310 if (!TD) {
2311 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2312 return Sema::TDK_Incomplete;
2313 }
2314
2315 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2316 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2317 HasDefaultArg);
2318
2319 // If there was no default argument, deduction is incomplete.
2320 if (DefArg.getArgument().isNull()) {
2321 Info.Param = makeTemplateParameter(
2322 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2323 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2324 if (PartialOverloading) break;
2325
2326 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2327 : Sema::TDK_Incomplete;
2328 }
2329
2330 // Check whether we can actually use the default argument.
2331 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2332 TD->getSourceRange().getEnd(), 0, Builder,
2333 Sema::CTAK_Specified)) {
2334 Info.Param = makeTemplateParameter(
2335 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2336 // FIXME: These template arguments are temporary. Free them!
2337 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2338 return Sema::TDK_SubstitutionFailure;
2339 }
2340
2341 // If we get here, we successfully used the default template argument.
2342 }
2343
2344 return Sema::TDK_Success;
2345}
2346
Douglas Gregor684268d2010-04-29 06:21:43 +00002347/// Complete template argument deduction for a class template partial
2348/// specialization.
2349static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002350FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002351 ClassTemplatePartialSpecializationDecl *Partial,
2352 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002353 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002354 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002355 // Unevaluated SFINAE context.
2356 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002357 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002358
Douglas Gregor684268d2010-04-29 06:21:43 +00002359 Sema::ContextRAII SavedContext(S, Partial);
2360
2361 // C++ [temp.deduct.type]p2:
2362 // [...] or if any template argument remains neither deduced nor
2363 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002364 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002365 if (auto Result = ConvertDeducedTemplateArguments(S, Partial, Deduced,
2366 Info, Builder))
2367 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002368
Douglas Gregor684268d2010-04-29 06:21:43 +00002369 // Form the template argument list from the deduced template arguments.
2370 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002371 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002372
Douglas Gregor684268d2010-04-29 06:21:43 +00002373 Info.reset(DeducedArgumentList);
2374
2375 // Substitute the deduced template arguments into the template
2376 // arguments of the class template partial specialization, and
2377 // verify that the instantiated template arguments are both valid
2378 // and are equivalent to the template arguments originally provided
2379 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002380 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002381 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002382 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002383 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002384 const TemplateArgumentLoc *PartialTemplateArgs
2385 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002386
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002387 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2388 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002389
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002390 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002391 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2392 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2393 if (ParamIdx >= Partial->getTemplateParameters()->size())
2394 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2395
2396 Decl *Param
2397 = const_cast<NamedDecl *>(
2398 Partial->getTemplateParameters()->getParam(ParamIdx));
2399 Info.Param = makeTemplateParameter(Param);
2400 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2401 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002402 }
2403
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002404 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002405 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002406 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002407 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002408
Douglas Gregorca4686d2011-01-04 23:35:54 +00002409 TemplateParameterList *TemplateParams
2410 = ClassTemplate->getTemplateParameters();
2411 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002412 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002413 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002414 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002415 Info.FirstArg = TemplateArgs[I];
2416 Info.SecondArg = InstArg;
2417 return Sema::TDK_NonDeducedMismatch;
2418 }
2419 }
2420
2421 if (Trap.hasErrorOccurred())
2422 return Sema::TDK_SubstitutionFailure;
2423
2424 return Sema::TDK_Success;
2425}
2426
Douglas Gregor170bc422009-06-12 22:31:52 +00002427/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002428/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002429/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002430Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002431Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002432 const TemplateArgumentList &TemplateArgs,
2433 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002434 if (Partial->isInvalidDecl())
2435 return TDK_Invalid;
2436
Douglas Gregor170bc422009-06-12 22:31:52 +00002437 // C++ [temp.class.spec.match]p2:
2438 // A partial specialization matches a given actual template
2439 // argument list if the template arguments of the partial
2440 // specialization can be deduced from the actual template argument
2441 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002442
2443 // Unevaluated SFINAE context.
2444 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002445 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002446
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002447 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002448 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002449 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002450 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002451 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002452 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002453 TemplateArgs, Info, Deduced))
2454 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002455
Richard Smith80934652012-07-16 01:09:10 +00002456 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002457 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2458 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002459 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002460 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002461
Douglas Gregore1416332009-06-14 08:02:22 +00002462 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002463 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002464
2465 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002466 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002467}
Douglas Gregor91772d12009-06-13 00:26:55 +00002468
Larisse Voufo39a1e502013-08-06 01:03:05 +00002469/// Complete template argument deduction for a variable template partial
2470/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002471/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2472/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2473/// VarTemplate(Partial)SpecializationDecl with a new data
2474/// structure Template(Partial)SpecializationDecl, and
2475/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002476static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2477 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2478 const TemplateArgumentList &TemplateArgs,
2479 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2480 TemplateDeductionInfo &Info) {
2481 // Unevaluated SFINAE context.
2482 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2483 Sema::SFINAETrap Trap(S);
2484
2485 // C++ [temp.deduct.type]p2:
2486 // [...] or if any template argument remains neither deduced nor
2487 // explicitly specified, template argument deduction fails.
2488 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002489 if (auto Result = ConvertDeducedTemplateArguments(S, Partial, Deduced,
2490 Info, Builder))
2491 return Result;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002492
2493 // Form the template argument list from the deduced template arguments.
2494 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
David Majnemer8b622692016-07-03 21:17:51 +00002495 S.Context, Builder);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002496
2497 Info.reset(DeducedArgumentList);
2498
2499 // Substitute the deduced template arguments into the template
2500 // arguments of the class template partial specialization, and
2501 // verify that the instantiated template arguments are both valid
2502 // and are equivalent to the template arguments originally provided
2503 // to the class template.
2504 LocalInstantiationScope InstScope(S);
2505 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002506 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2507 = Partial->getTemplateArgsAsWritten();
2508 const TemplateArgumentLoc *PartialTemplateArgs
2509 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002510
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002511 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2512 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002513
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002514 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002515 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2516 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2517 if (ParamIdx >= Partial->getTemplateParameters()->size())
2518 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2519
2520 Decl *Param = const_cast<NamedDecl *>(
2521 Partial->getTemplateParameters()->getParam(ParamIdx));
2522 Info.Param = makeTemplateParameter(Param);
2523 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2524 return Sema::TDK_SubstitutionFailure;
2525 }
2526 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2527 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2528 false, ConvertedInstArgs))
2529 return Sema::TDK_SubstitutionFailure;
2530
2531 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2532 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2533 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2534 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2535 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2536 Info.FirstArg = TemplateArgs[I];
2537 Info.SecondArg = InstArg;
2538 return Sema::TDK_NonDeducedMismatch;
2539 }
2540 }
2541
2542 if (Trap.hasErrorOccurred())
2543 return Sema::TDK_SubstitutionFailure;
2544
2545 return Sema::TDK_Success;
2546}
2547
2548/// \brief Perform template argument deduction to determine whether
2549/// the given template arguments match the given variable template
2550/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002551/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2552/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2553/// VarTemplate(Partial)SpecializationDecl with a new data
2554/// structure Template(Partial)SpecializationDecl, and
2555/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002556Sema::TemplateDeductionResult
2557Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2558 const TemplateArgumentList &TemplateArgs,
2559 TemplateDeductionInfo &Info) {
2560 if (Partial->isInvalidDecl())
2561 return TDK_Invalid;
2562
2563 // C++ [temp.class.spec.match]p2:
2564 // A partial specialization matches a given actual template
2565 // argument list if the template arguments of the partial
2566 // specialization can be deduced from the actual template argument
2567 // list (14.8.2).
2568
2569 // Unevaluated SFINAE context.
2570 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2571 SFINAETrap Trap(*this);
2572
2573 SmallVector<DeducedTemplateArgument, 4> Deduced;
2574 Deduced.resize(Partial->getTemplateParameters()->size());
2575 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2576 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2577 TemplateArgs, Info, Deduced))
2578 return Result;
2579
2580 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002581 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2582 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002583 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002584 return TDK_InstantiationDepth;
2585
2586 if (Trap.hasErrorOccurred())
2587 return Sema::TDK_SubstitutionFailure;
2588
2589 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2590 Deduced, Info);
2591}
2592
Douglas Gregorfc516c92009-06-26 23:27:24 +00002593/// \brief Determine whether the given type T is a simple-template-id type.
2594static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002595 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002596 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002597 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002598
Douglas Gregorfc516c92009-06-26 23:27:24 +00002599 return false;
2600}
Douglas Gregor9b146582009-07-08 20:55:45 +00002601
2602/// \brief Substitute the explicitly-provided template arguments into the
2603/// given function template according to C++ [temp.arg.explicit].
2604///
2605/// \param FunctionTemplate the function template into which the explicit
2606/// template arguments will be substituted.
2607///
James Dennett634962f2012-06-14 21:40:34 +00002608/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002609/// arguments.
2610///
Mike Stump11289f42009-09-09 15:08:12 +00002611/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002612/// with the converted and checked explicit template arguments.
2613///
Mike Stump11289f42009-09-09 15:08:12 +00002614/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002615/// parameters.
2616///
2617/// \param FunctionType if non-NULL, the result type of the function template
2618/// will also be instantiated and the pointed-to value will be updated with
2619/// the instantiated function type.
2620///
2621/// \param Info if substitution fails for any reason, this object will be
2622/// populated with more information about the failure.
2623///
2624/// \returns TDK_Success if substitution was successful, or some failure
2625/// condition.
2626Sema::TemplateDeductionResult
2627Sema::SubstituteExplicitTemplateArguments(
2628 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002629 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002630 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2631 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002632 QualType *FunctionType,
2633 TemplateDeductionInfo &Info) {
2634 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2635 TemplateParameterList *TemplateParams
2636 = FunctionTemplate->getTemplateParameters();
2637
John McCall6b51f282009-11-23 01:53:49 +00002638 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002639 // No arguments to substitute; just copy over the parameter types and
2640 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002641 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002642 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002643
Douglas Gregor9b146582009-07-08 20:55:45 +00002644 if (FunctionType)
2645 *FunctionType = Function->getType();
2646 return TDK_Success;
2647 }
Mike Stump11289f42009-09-09 15:08:12 +00002648
Eli Friedman77dcc722012-02-08 03:07:05 +00002649 // Unevaluated SFINAE context.
2650 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002651 SFINAETrap Trap(*this);
2652
Douglas Gregor9b146582009-07-08 20:55:45 +00002653 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002654 // Template arguments that are present shall be specified in the
2655 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002656 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002657 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002658 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002659
2660 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002661 // explicitly-specified template arguments against this function template,
2662 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002663 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002664 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2665 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002666 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2667 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002668 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002669 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002670
Douglas Gregor9b146582009-07-08 20:55:45 +00002671 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002672 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002673 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002674 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002675 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002676 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002677 if (Index >= TemplateParams->size())
2678 Index = TemplateParams->size() - 1;
2679 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002680 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002681 }
Mike Stump11289f42009-09-09 15:08:12 +00002682
Douglas Gregor9b146582009-07-08 20:55:45 +00002683 // Form the template argument list from the explicitly-specified
2684 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002685 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002686 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002687 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002688
John McCall036855a2010-10-12 19:40:14 +00002689 // Template argument deduction and the final substitution should be
2690 // done in the context of the templated declaration. Explicit
2691 // argument substitution, on the other hand, needs to happen in the
2692 // calling context.
2693 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2694
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002696 // note that the template argument pack is partially substituted and record
2697 // the explicit template arguments. They'll be used as part of deduction
2698 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002699 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2700 const TemplateArgument &Arg = Builder[I];
2701 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002702 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002704 Arg.pack_begin(),
2705 Arg.pack_size());
2706 break;
2707 }
2708 }
2709
Richard Smith5e580292012-02-10 09:58:53 +00002710 const FunctionProtoType *Proto
2711 = Function->getType()->getAs<FunctionProtoType>();
2712 assert(Proto && "Function template does not have a prototype?");
2713
Richard Smith70b13042015-01-09 01:19:56 +00002714 // Isolate our substituted parameters from our caller.
2715 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2716
John McCallc8e321d2016-03-01 02:09:25 +00002717 ExtParameterInfoBuilder ExtParamInfos;
2718
Douglas Gregor9b146582009-07-08 20:55:45 +00002719 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002720 // explicitly-specified template arguments. If the function has a trailing
2721 // return type, substitute it after the arguments to ensure we substitute
2722 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002723 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002724 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002725 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002726 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002727 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002728 return TDK_SubstitutionFailure;
2729 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002730
Richard Smith5e580292012-02-10 09:58:53 +00002731 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002732 QualType ResultType;
2733 {
2734 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002735 // If a declaration declares a member function or member function
2736 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002737 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002738 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002739 // declarator.
2740 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002741 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002742 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2743 ThisContext = Method->getParent();
2744 ThisTypeQuals = Method->getTypeQualifiers();
2745 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002746
Douglas Gregor3024f072012-04-16 07:05:22 +00002747 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002748 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002749
2750 ResultType =
2751 SubstType(Proto->getReturnType(),
2752 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2753 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002754 if (ResultType.isNull() || Trap.hasErrorOccurred())
2755 return TDK_SubstitutionFailure;
2756 }
John McCallc8e321d2016-03-01 02:09:25 +00002757
Richard Smith5e580292012-02-10 09:58:53 +00002758 // Instantiate the types of each of the function parameters given the
2759 // explicitly-specified template arguments if we didn't do so earlier.
2760 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002761 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002762 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002763 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002764 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002765 return TDK_SubstitutionFailure;
2766
Douglas Gregor9b146582009-07-08 20:55:45 +00002767 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002768 auto EPI = Proto->getExtProtoInfo();
2769 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002770 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002771 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002772 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002773 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002774 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2775 return TDK_SubstitutionFailure;
2776 }
Mike Stump11289f42009-09-09 15:08:12 +00002777
Douglas Gregor9b146582009-07-08 20:55:45 +00002778 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002779 // Trailing template arguments that can be deduced (14.8.2) may be
2780 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002781 // template arguments can be deduced, they may all be omitted; in this
2782 // case, the empty template argument list <> itself may also be omitted.
2783 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002784 // Take all of the explicitly-specified arguments and put them into
2785 // the set of deduced template arguments. Explicitly-specified
2786 // parameter packs, however, will be set to NULL since the deduction
2787 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002788 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002789 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2790 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2791 if (Arg.getKind() == TemplateArgument::Pack)
2792 Deduced.push_back(DeducedTemplateArgument());
2793 else
2794 Deduced.push_back(Arg);
2795 }
Mike Stump11289f42009-09-09 15:08:12 +00002796
Douglas Gregor9b146582009-07-08 20:55:45 +00002797 return TDK_Success;
2798}
2799
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002800/// \brief Check whether the deduced argument type for a call to a function
2801/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002802static bool
2803CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002804 QualType DeducedA) {
2805 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002806
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002807 QualType A = OriginalArg.OriginalArgType;
2808 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002809
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002810 // Check for type equality (top-level cv-qualifiers are ignored).
2811 if (Context.hasSameUnqualifiedType(A, DeducedA))
2812 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002813
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002814 // Strip off references on the argument types; they aren't needed for
2815 // the following checks.
2816 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2817 DeducedA = DeducedARef->getPointeeType();
2818 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2819 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002820
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002821 // C++ [temp.deduct.call]p4:
2822 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002823 // - If the original P is a reference type, the deduced A (i.e., the
2824 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002825 // the transformed A.
2826 if (const ReferenceType *OriginalParamRef
2827 = OriginalParamType->getAs<ReferenceType>()) {
2828 // We don't want to keep the reference around any more.
2829 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002830
Richard Smith1be59c52016-10-22 01:32:19 +00002831 // FIXME: Resolve core issue (no number yet): if the original P is a
2832 // reference type and the transformed A is function type "noexcept F",
2833 // the deduced A can be F.
2834 QualType Tmp;
2835 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2836 return false;
2837
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002838 Qualifiers AQuals = A.getQualifiers();
2839 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002840
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002841 // Under Objective-C++ ARC, the deduced type may have implicitly
2842 // been given strong or (when dealing with a const reference)
2843 // unsafe_unretained lifetime. If so, update the original
2844 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002845 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002846 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2847 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2848 (DeducedAQuals.hasConst() &&
2849 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2850 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002851 }
2852
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002853 if (AQuals == DeducedAQuals) {
2854 // Qualifiers match; there's nothing to do.
2855 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002856 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002857 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002858 // Qualifiers are compatible, so have the argument type adopt the
2859 // deduced argument type's qualifiers as if we had performed the
2860 // qualification conversion.
2861 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2862 }
2863 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002864
2865 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002866 // type that can be converted to the deduced A via a function pointer
2867 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002868 //
Richard Smith1be59c52016-10-22 01:32:19 +00002869 // Also allow conversions which merely strip __attribute__((noreturn)) from
2870 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002871 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002872 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002873 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002874 (S.IsQualificationConversion(A, DeducedA, false,
2875 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002876 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002877 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002878
Simon Pilgrim728134c2016-08-12 11:43:57 +00002879 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002880 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002881 // [...] Likewise, if P is a pointer to a class of the form
2882 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002883 // derived class pointed to by the deduced A.
2884 if (const PointerType *OriginalParamPtr
2885 = OriginalParamType->getAs<PointerType>()) {
2886 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2887 if (const PointerType *APtr = A->getAs<PointerType>()) {
2888 if (A->getPointeeType()->isRecordType()) {
2889 OriginalParamType = OriginalParamPtr->getPointeeType();
2890 DeducedA = DeducedAPtr->getPointeeType();
2891 A = APtr->getPointeeType();
2892 }
2893 }
2894 }
2895 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002896
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002897 if (Context.hasSameUnqualifiedType(A, DeducedA))
2898 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002899
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002900 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002901 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002902 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002903
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002904 return true;
2905}
2906
Mike Stump11289f42009-09-09 15:08:12 +00002907/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002908/// checking the deduced template arguments for completeness and forming
2909/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002910///
2911/// \param OriginalCallArgs If non-NULL, the original call arguments against
2912/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002913Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002914Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002915 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002916 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002917 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002918 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002919 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2920 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002921 // Unevaluated SFINAE context.
2922 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002923 SFINAETrap Trap(*this);
2924
Douglas Gregor9b146582009-07-08 20:55:45 +00002925 // Enter a new template instantiation context while we instantiate the
2926 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002927 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002928 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2929 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002930 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2931 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002932 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002933 return TDK_InstantiationDepth;
2934
John McCalle23b8712010-04-29 01:18:58 +00002935 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002936
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002937 // C++ [temp.deduct.type]p2:
2938 // [...] or if any template argument remains neither deduced nor
2939 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002940 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002941 if (auto Result = ConvertDeducedTemplateArguments(
2942 *this, FunctionTemplate, Deduced, Info, Builder,
2943 CurrentInstantiationScope, NumExplicitlySpecified,
2944 PartialOverloading))
2945 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002946
2947 // Form the template argument list from the deduced template arguments.
2948 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002949 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002950 Info.reset(DeducedArgumentList);
2951
Mike Stump11289f42009-09-09 15:08:12 +00002952 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002953 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002954 DeclContext *Owner = FunctionTemplate->getDeclContext();
2955 if (FunctionTemplate->getFriendObjectKind())
2956 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002957 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002958 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002959 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002960 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002961 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002962
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002964 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965
Mike Stump11289f42009-09-09 15:08:12 +00002966 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002967 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002968 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2969 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002970 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002971
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002972 // There may have been an error that did not prevent us from constructing a
2973 // declaration. Mark the declaration invalid and return with a substitution
2974 // failure.
2975 if (Trap.hasErrorOccurred()) {
2976 Specialization->setInvalidDecl(true);
2977 return TDK_SubstitutionFailure;
2978 }
2979
Douglas Gregore65aacb2011-06-16 16:50:48 +00002980 if (OriginalCallArgs) {
2981 // C++ [temp.deduct.call]p4:
2982 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002983 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002984 // is transformed as described above). [...]
2985 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2986 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002987 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002988
Douglas Gregore65aacb2011-06-16 16:50:48 +00002989 if (ParamIdx >= Specialization->getNumParams())
2990 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002991
Douglas Gregore65aacb2011-06-16 16:50:48 +00002992 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002993 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2994 Info.FirstArg = TemplateArgument(DeducedA);
2995 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2996 Info.CallArgIndex = OriginalArg.ArgIdx;
2997 return TDK_DeducedMismatch;
2998 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002999 }
3000 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003001
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003002 // If we suppressed any diagnostics while performing template argument
3003 // deduction, and if we haven't already instantiated this declaration,
3004 // keep track of these diagnostics. They'll be emitted if this specialization
3005 // is actually used.
3006 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003007 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003008 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3009 if (Pos == SuppressedDiagnostics.end())
3010 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3011 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003012 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003013
Mike Stump11289f42009-09-09 15:08:12 +00003014 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003015}
3016
John McCall8d08b9b2010-08-27 09:08:28 +00003017/// Gets the type of a function for template-argument-deducton
3018/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003019static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003020 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003021 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003022 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003023 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003024 return QualType();
3025
John McCallc1f69982010-02-02 02:21:27 +00003026 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003027 if (Method->isInstance()) {
3028 // An instance method that's referenced in a form that doesn't
3029 // look like a member pointer is just invalid.
3030 if (!R.HasFormOfMemberPointer) return QualType();
3031
Richard Smith2a7d4812013-05-04 07:00:32 +00003032 return S.Context.getMemberPointerType(Fn->getType(),
3033 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003034 }
3035
3036 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003037 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003038}
3039
3040/// Apply the deduction rules for overload sets.
3041///
3042/// \return the null type if this argument should be treated as an
3043/// undeduced context
3044static QualType
3045ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003046 Expr *Arg, QualType ParamType,
3047 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048
John McCall8d08b9b2010-08-27 09:08:28 +00003049 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003050
John McCall8d08b9b2010-08-27 09:08:28 +00003051 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003052
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003053 // C++0x [temp.deduct.call]p4
3054 unsigned TDF = 0;
3055 if (ParamWasReference)
3056 TDF |= TDF_ParamWithReferenceType;
3057 if (R.IsAddressOfOperand)
3058 TDF |= TDF_IgnoreQualifiers;
3059
John McCallc1f69982010-02-02 02:21:27 +00003060 // C++0x [temp.deduct.call]p6:
3061 // When P is a function type, pointer to function type, or pointer
3062 // to member function type:
3063
3064 if (!ParamType->isFunctionType() &&
3065 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003066 !ParamType->isMemberFunctionPointerType()) {
3067 if (Ovl->hasExplicitTemplateArgs()) {
3068 // But we can still look for an explicit specialization.
3069 if (FunctionDecl *ExplicitSpec
3070 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003071 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003072 }
John McCallc1f69982010-02-02 02:21:27 +00003073
George Burgess IVcc2f3552016-03-19 21:51:45 +00003074 DeclAccessPair DAP;
3075 if (FunctionDecl *Viable =
3076 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3077 return GetTypeOfFunction(S, R, Viable);
3078
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003079 return QualType();
3080 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003081
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003082 // Gather the explicit template arguments, if any.
3083 TemplateArgumentListInfo ExplicitTemplateArgs;
3084 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003085 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003086 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003087 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3088 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003089 NamedDecl *D = (*I)->getUnderlyingDecl();
3090
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003091 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3092 // - If the argument is an overload set containing one or more
3093 // function templates, the parameter is treated as a
3094 // non-deduced context.
3095 if (!Ovl->hasExplicitTemplateArgs())
3096 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003097
3098 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003099 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003100 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003101 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3102 Specialization, Info))
3103 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003104
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003105 D = Specialization;
3106 }
John McCallc1f69982010-02-02 02:21:27 +00003107
3108 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003109 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003110 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003111
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003112 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003113 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003114 ArgType->isFunctionType())
3115 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003116
John McCallc1f69982010-02-02 02:21:27 +00003117 // - If the argument is an overload set (not containing function
3118 // templates), trial argument deduction is attempted using each
3119 // of the members of the set. If deduction succeeds for only one
3120 // of the overload set members, that member is used as the
3121 // argument value for the deduction. If deduction succeeds for
3122 // more than one member of the overload set the parameter is
3123 // treated as a non-deduced context.
3124
3125 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3126 // Type deduction is done independently for each P/A pair, and
3127 // the deduced template argument values are then combined.
3128 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003129 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003130 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003131 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003132 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003133 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3134 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003135 if (Result) continue;
3136 if (!Match.isNull()) return QualType();
3137 Match = ArgType;
3138 }
3139
3140 return Match;
3141}
3142
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003144/// described in C++ [temp.deduct.call].
3145///
3146/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003147/// argument deduction based on this P/A pair because the argument is an
3148/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003149static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3150 TemplateParameterList *TemplateParams,
3151 QualType &ParamType,
3152 QualType &ArgType,
3153 Expr *Arg,
3154 unsigned &TDF) {
3155 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003156 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003157 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003158 if (ParamType.hasQualifiers())
3159 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003160
3161 // [...] If P is a reference type, the type referred to by P is
3162 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003163 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003164 if (ParamRefType)
3165 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003166
Nathan Sidwell96090022015-01-16 15:20:14 +00003167 // Overload sets usually make this parameter an undeduced context,
3168 // but there are sometimes special circumstances. Typically
3169 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003170 if (ArgType == S.Context.OverloadTy) {
3171 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3172 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003173 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003174 if (ArgType.isNull())
3175 return true;
3176 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003177
Douglas Gregor7825bf32011-01-06 22:09:01 +00003178 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003179 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003180 if (ArgType->isIncompleteArrayType()) {
3181 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003182 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003183 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003184
Douglas Gregor7825bf32011-01-06 22:09:01 +00003185 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003186 // If P is an rvalue reference to a cv-unqualified template
3187 // parameter and the argument is an lvalue, the type "lvalue
3188 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003189 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003190 !ParamType.getQualifiers() &&
3191 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003192 Arg->isLValue())
3193 ArgType = S.Context.getLValueReferenceType(ArgType);
3194 } else {
3195 // C++ [temp.deduct.call]p2:
3196 // If P is not a reference type:
3197 // - If A is an array type, the pointer type produced by the
3198 // array-to-pointer standard conversion (4.2) is used in place of
3199 // A for type deduction; otherwise,
3200 if (ArgType->isArrayType())
3201 ArgType = S.Context.getArrayDecayedType(ArgType);
3202 // - If A is a function type, the pointer type produced by the
3203 // function-to-pointer standard conversion (4.3) is used in place
3204 // of A for type deduction; otherwise,
3205 else if (ArgType->isFunctionType())
3206 ArgType = S.Context.getPointerType(ArgType);
3207 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003208 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003209 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003210 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003211 }
3212 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213
Douglas Gregor7825bf32011-01-06 22:09:01 +00003214 // C++0x [temp.deduct.call]p4:
3215 // In general, the deduction process attempts to find template argument
3216 // values that will make the deduced A identical to A (after the type A
3217 // is transformed as described above). [...]
3218 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219
Douglas Gregor7825bf32011-01-06 22:09:01 +00003220 // - If the original P is a reference type, the deduced A (i.e., the
3221 // type referred to by the reference) can be more cv-qualified than
3222 // the transformed A.
3223 if (ParamRefType)
3224 TDF |= TDF_ParamWithReferenceType;
3225 // - The transformed A can be another pointer or pointer to member
3226 // type that can be converted to the deduced A via a qualification
3227 // conversion (4.4).
3228 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3229 ArgType->isObjCObjectPointerType())
3230 TDF |= TDF_IgnoreQualifiers;
3231 // - If P is a class and P has the form simple-template-id, then the
3232 // transformed A can be a derived class of the deduced A. Likewise,
3233 // if P is a pointer to a class of the form simple-template-id, the
3234 // transformed A can be a pointer to a derived class pointed to by
3235 // the deduced A.
3236 if (isSimpleTemplateIdType(ParamType) ||
3237 (isa<PointerType>(ParamType) &&
3238 isSimpleTemplateIdType(
3239 ParamType->getAs<PointerType>()->getPointeeType())))
3240 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241
Douglas Gregor7825bf32011-01-06 22:09:01 +00003242 return false;
3243}
3244
Nico Weberc153d242014-07-28 00:02:09 +00003245static bool
3246hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3247 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003248
Hubert Tong3280b332015-06-25 00:25:49 +00003249static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3250 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3251 Expr *Arg, TemplateDeductionInfo &Info,
3252 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3253
3254/// \brief Attempt template argument deduction from an initializer list
3255/// deemed to be an argument in a function call.
3256static bool
3257DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3258 QualType AdjustedParamType, InitListExpr *ILE,
3259 TemplateDeductionInfo &Info,
3260 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3261 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003262
3263 // [temp.deduct.call] p1 (post CWG-1591)
3264 // If removing references and cv-qualifiers from P gives
3265 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3266 // non-empty initializer list (8.5.4), then deduction is performed instead for
3267 // each element of the initializer list, taking P0 as a function template
3268 // parameter type and the initializer element as its argument, and in the
3269 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3270 // length of the initializer list. Otherwise, an initializer list argument
3271 // causes the parameter to be considered a non-deduced context
3272
3273 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3274
3275 const bool IsDependentSizedArray =
3276 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3277
Faisal Validd76cc12015-12-10 12:29:11 +00003278 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003279
3280 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3281 S.isStdInitializerList(AdjustedParamType, &ElTy);
3282
3283 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003284 return false;
3285
3286 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003287 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3288 // deduce against the 'T' in T[N].
3289 if (ElTy.isNull()) {
3290 assert(!IsSTDList);
3291 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003292 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003293 // Deduction only needs to be done for dependent types.
3294 if (ElTy->isDependentType()) {
3295 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003296 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3297 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003298 return true;
3299 }
3300 }
3301 if (IsDependentSizedArray) {
3302 const DependentSizedArrayType *ArrTy =
3303 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3304 // Determine the array bound is something we can deduce.
3305 if (NonTypeTemplateParmDecl *NTTP =
3306 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3307 // We can perform template argument deduction for the given non-type
3308 // template parameter.
3309 assert(NTTP->getDepth() == 0 &&
3310 "Cannot deduce non-type template argument at depth > 0");
3311 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3312 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003313
Faisal Valif6dfdb32015-12-10 05:36:39 +00003314 Result = DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +00003315 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
Faisal Valif6dfdb32015-12-10 05:36:39 +00003316 /*ArrayBound=*/true, Info, Deduced);
3317 }
3318 }
Hubert Tong3280b332015-06-25 00:25:49 +00003319 return true;
3320}
3321
Sebastian Redl19181662012-03-15 21:40:51 +00003322/// \brief Perform template argument deduction by matching a parameter type
3323/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003324/// an initializer list that was originally matched against a parameter
3325/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003326static Sema::TemplateDeductionResult
3327DeduceTemplateArgumentByListElement(Sema &S,
3328 TemplateParameterList *TemplateParams,
3329 QualType ParamType, Expr *Arg,
3330 TemplateDeductionInfo &Info,
3331 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3332 unsigned TDF) {
3333 // Handle the case where an init list contains another init list as the
3334 // element.
3335 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003336 Sema::TemplateDeductionResult Result;
3337 if (!DeduceFromInitializerList(S, TemplateParams,
3338 ParamType.getNonReferenceType(), ILE, Info,
3339 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003340 return Sema::TDK_Success; // Just ignore this expression.
3341
Hubert Tong3280b332015-06-25 00:25:49 +00003342 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003343 }
3344
3345 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003346 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003347 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003348 ArgType, Arg, TDF)) {
3349 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003350 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003351 }
Sebastian Redl19181662012-03-15 21:40:51 +00003352 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003353 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003354}
3355
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003356/// \brief Perform template argument deduction from a function call
3357/// (C++ [temp.deduct.call]).
3358///
3359/// \param FunctionTemplate the function template for which we are performing
3360/// template argument deduction.
3361///
James Dennett18348b62012-06-22 08:52:37 +00003362/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003363/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003364///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003365/// \param Args the function call arguments
3366///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003367/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003368/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003369/// template argument deduction.
3370///
3371/// \param Info the argument will be updated to provide additional information
3372/// about template argument deduction.
3373///
3374/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003375Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3376 FunctionTemplateDecl *FunctionTemplate,
3377 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003378 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3379 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003380 if (FunctionTemplate->isInvalidDecl())
3381 return TDK_Invalid;
3382
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003383 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003384 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003385
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003386 // C++ [temp.deduct.call]p1:
3387 // Template argument deduction is done by comparing each function template
3388 // parameter type (call it P) with the type of the corresponding argument
3389 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003390 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003391 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003392 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003393 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003394 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003395 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003396 if (Proto->isTemplateVariadic())
3397 /* Do nothing */;
3398 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003399 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003401 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003402 }
Mike Stump11289f42009-09-09 15:08:12 +00003403
Douglas Gregor89026b52009-06-30 23:57:56 +00003404 // The types of the parameters from which we will perform template argument
3405 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003406 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003407 TemplateParameterList *TemplateParams
3408 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003409 SmallVector<DeducedTemplateArgument, 4> Deduced;
3410 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003411 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003412 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003413 TemplateDeductionResult Result =
3414 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003415 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003416 Deduced,
3417 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003418 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003419 Info);
3420 if (Result)
3421 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003422
3423 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003424 } else {
3425 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003426 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003427 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3428 }
Mike Stump11289f42009-09-09 15:08:12 +00003429
Douglas Gregor89026b52009-06-30 23:57:56 +00003430 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003431 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003432 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003433 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003434 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3435 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003436 QualType OrigParamType = ParamTypes[ParamIdx];
3437 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003438
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003440 = dyn_cast<PackExpansionType>(ParamType);
3441 if (!ParamExpansion) {
3442 // Simple case: matching a function parameter to a function argument.
3443 if (ArgIdx >= CheckArgs)
3444 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445
Douglas Gregor7825bf32011-01-06 22:09:01 +00003446 Expr *Arg = Args[ArgIdx++];
3447 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003448
Douglas Gregor7825bf32011-01-06 22:09:01 +00003449 unsigned TDF = 0;
3450 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3451 ParamType, ArgType, Arg,
3452 TDF))
3453 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454
Douglas Gregor0c83c812011-10-09 22:06:46 +00003455 // If we have nothing to deduce, we're done.
3456 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3457 continue;
3458
Sebastian Redl43144e72012-01-17 22:49:58 +00003459 // If the argument is an initializer list ...
3460 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003461 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003462 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003463 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3464 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003465 continue;
3466
Hubert Tong3280b332015-06-25 00:25:49 +00003467 if (Result)
3468 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003469 // Don't track the argument type, since an initializer list has none.
3470 continue;
3471 }
3472
Douglas Gregore65aacb2011-06-16 16:50:48 +00003473 // Keep track of the argument type and corresponding parameter index,
3474 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003475 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003476 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003477
Douglas Gregor7825bf32011-01-06 22:09:01 +00003478 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003479 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3480 ParamType, ArgType,
3481 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003482 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003483
Douglas Gregor7825bf32011-01-06 22:09:01 +00003484 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003486
Douglas Gregor7825bf32011-01-06 22:09:01 +00003487 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488 // For a function parameter pack that occurs at the end of the
3489 // parameter-declaration-list, the type A of each remaining argument of
3490 // the call is compared with the type P of the declarator-id of the
3491 // function parameter pack. Each comparison deduces template arguments
3492 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003493 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003494 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003495 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003496 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003497 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003498
Douglas Gregor7825bf32011-01-06 22:09:01 +00003499 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003500 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3501 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregor7825bf32011-01-06 22:09:01 +00003503 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003504 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003505 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506
Douglas Gregore65aacb2011-06-16 16:50:48 +00003507 QualType OrigParamType = ParamPattern;
3508 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003509 Expr *Arg = Args[ArgIdx];
3510 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003511
Douglas Gregor7825bf32011-01-06 22:09:01 +00003512 unsigned TDF = 0;
3513 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3514 ParamType, ArgType, Arg,
3515 TDF)) {
3516 // We can't actually perform any deduction for this argument, so stop
3517 // deduction at this point.
3518 ++ArgIdx;
3519 break;
3520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
Sebastian Redl43144e72012-01-17 22:49:58 +00003522 // As above, initializer lists need special handling.
3523 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003524 TemplateDeductionResult Result;
3525 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3526 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003527 ++ArgIdx;
3528 break;
3529 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003530
Hubert Tong3280b332015-06-25 00:25:49 +00003531 if (Result)
3532 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003533 } else {
3534
3535 // Keep track of the argument type and corresponding argument index,
3536 // so we can check for compatibility between the deduced A and A.
3537 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003538 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003539 ArgType));
3540
3541 if (TemplateDeductionResult Result
3542 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3543 ParamType, ArgType, Info,
3544 Deduced, TDF))
3545 return Result;
3546 }
Mike Stump11289f42009-09-09 15:08:12 +00003547
Richard Smith0a80d572014-05-29 01:12:14 +00003548 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003549 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003550
Douglas Gregor7825bf32011-01-06 22:09:01 +00003551 // Build argument packs for each of the parameter packs expanded by this
3552 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003553 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003554 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003555
Douglas Gregor7825bf32011-01-06 22:09:01 +00003556 // After we've matching against a parameter pack, we're done.
3557 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003558 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003559
Mike Stump11289f42009-09-09 15:08:12 +00003560 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003561 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003562 Info, &OriginalCallArgs,
3563 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003564}
3565
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003566QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003567 QualType FunctionType,
3568 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003569 if (ArgFunctionType.isNull())
3570 return ArgFunctionType;
3571
3572 const FunctionProtoType *FunctionTypeP =
3573 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003574 const FunctionProtoType *ArgFunctionTypeP =
3575 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003576
3577 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3578 bool Rebuild = false;
3579
3580 CallingConv CC = FunctionTypeP->getCallConv();
3581 if (EPI.ExtInfo.getCC() != CC) {
3582 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3583 Rebuild = true;
3584 }
3585
3586 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3587 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3588 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3589 Rebuild = true;
3590 }
3591
3592 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3593 ArgFunctionTypeP->hasExceptionSpec())) {
3594 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3595 Rebuild = true;
3596 }
3597
3598 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003599 return ArgFunctionType;
3600
Richard Smithbaa47832016-12-01 02:11:49 +00003601 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3602 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003603}
3604
Douglas Gregor9b146582009-07-08 20:55:45 +00003605/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003606/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3607/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003608///
3609/// \param FunctionTemplate the function template for which we are performing
3610/// template argument deduction.
3611///
James Dennett18348b62012-06-22 08:52:37 +00003612/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003613/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003614///
3615/// \param ArgFunctionType the function type that will be used as the
3616/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003617/// function template's function type. This type may be NULL, if there is no
3618/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003619///
3620/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003621/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003622/// template argument deduction.
3623///
3624/// \param Info the argument will be updated to provide additional information
3625/// about template argument deduction.
3626///
Richard Smithbaa47832016-12-01 02:11:49 +00003627/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3628/// the address of a function template per [temp.deduct.funcaddr] and
3629/// [over.over]. If \c false, we are looking up a function template
3630/// specialization based on its signature, per [temp.deduct.decl].
3631///
Douglas Gregor9b146582009-07-08 20:55:45 +00003632/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003633Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3634 FunctionTemplateDecl *FunctionTemplate,
3635 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3636 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3637 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003638 if (FunctionTemplate->isInvalidDecl())
3639 return TDK_Invalid;
3640
Douglas Gregor9b146582009-07-08 20:55:45 +00003641 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3642 TemplateParameterList *TemplateParams
3643 = FunctionTemplate->getTemplateParameters();
3644 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003645
3646 // When taking the address of a function, we require convertibility of
3647 // the resulting function type. Otherwise, we allow arbitrary mismatches
3648 // of calling convention, noreturn, and noexcept.
3649 if (!IsAddressOfFunction)
3650 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3651 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003652
Douglas Gregor9b146582009-07-08 20:55:45 +00003653 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003654 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003655 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003656 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003657 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003658 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003659 if (TemplateDeductionResult Result
3660 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003661 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003662 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003663 &FunctionType, Info))
3664 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003665
3666 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003667 }
3668
Eli Friedman77dcc722012-02-08 03:07:05 +00003669 // Unevaluated SFINAE context.
3670 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003671 SFINAETrap Trap(*this);
3672
John McCallc1f69982010-02-02 02:21:27 +00003673 Deduced.resize(TemplateParams->size());
3674
Richard Smith2a7d4812013-05-04 07:00:32 +00003675 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003676 // type so that we treat it as a non-deduced context in what follows. If we
3677 // are looking up by signature, the signature type should also have a deduced
3678 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003679 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003680 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003681 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003682 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003683 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003684 }
3685
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003686 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003687 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003688 if (IsAddressOfFunction)
3689 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003690 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003691 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003692 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003693 FunctionType, ArgFunctionType,
3694 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003695 return Result;
3696 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003697
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003699 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3700 NumExplicitlySpecified,
3701 Specialization, Info))
3702 return Result;
3703
Richard Smith2a7d4812013-05-04 07:00:32 +00003704 // If the function has a deduced return type, deduce it now, so we can check
3705 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003706 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003707 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003708 DeduceReturnType(Specialization, Info.getLocation(), false))
3709 return TDK_MiscellaneousDeductionFailure;
3710
Richard Smith9095e5b2016-11-01 01:31:23 +00003711 // If the function has a dependent exception specification, resolve it now,
3712 // so we can check that the exception specification matches.
3713 auto *SpecializationFPT =
3714 Specialization->getType()->castAs<FunctionProtoType>();
3715 if (getLangOpts().CPlusPlus1z &&
3716 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3717 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3718 return TDK_MiscellaneousDeductionFailure;
3719
Richard Smithbaa47832016-12-01 02:11:49 +00003720 // Adjust the exception specification of the argument again to match the
3721 // substituted and resolved type we just formed. (Calling convention and
3722 // noreturn can't be dependent, so we don't actually need this for them
3723 // right now.)
3724 QualType SpecializationType = Specialization->getType();
3725 if (!IsAddressOfFunction)
3726 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3727 /*AdjustExceptionSpec*/true);
3728
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003729 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003730 // specialization with respect to arguments of compatible pointer to function
3731 // types, template argument deduction fails.
3732 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003733 if (IsAddressOfFunction &&
3734 !isSameOrCompatibleFunctionType(
3735 Context.getCanonicalType(SpecializationType),
3736 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003737 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003738
3739 if (!IsAddressOfFunction &&
3740 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003741 return TDK_MiscellaneousDeductionFailure;
3742 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003743
3744 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003745}
3746
Simon Pilgrim728134c2016-08-12 11:43:57 +00003747/// \brief Given a function declaration (e.g. a generic lambda conversion
3748/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003749/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3750/// to replace 'auto' with and not the actual result type you want
3751/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003752static inline void
3753SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003754 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003755 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003756 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003757 assert(AutoResultType->getContainedAutoType());
3758 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003759 TypeToReplaceAutoWith);
3760 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3761}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003762
Simon Pilgrim728134c2016-08-12 11:43:57 +00003763/// \brief Given a specialized conversion operator of a generic lambda
3764/// create the corresponding specializations of the call operator and
3765/// the static-invoker. If the return type of the call operator is auto,
3766/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003767/// return type of the destination function ptr.
3768
Simon Pilgrim728134c2016-08-12 11:43:57 +00003769static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003770SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3771 CXXConversionDecl *ConversionSpecialized,
3772 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3773 QualType ReturnTypeOfDestFunctionPtr,
3774 TemplateDeductionInfo &TDInfo,
3775 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003776
Faisal Vali2b3a3012013-10-24 23:40:02 +00003777 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003778 assert(LambdaClass && LambdaClass->isGenericLambda());
3779
Faisal Vali2b3a3012013-10-24 23:40:02 +00003780 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003781 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003782 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003783 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003784
3785 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003786 CallOpGeneric->getDescribedFunctionTemplate();
3787
Craig Topperc3ec1492014-05-26 06:22:03 +00003788 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003789 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003790 // generic lambda's call operator.
3791 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003792 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3793 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003794 0, CallOpSpecialized, TDInfo))
3795 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003796
Faisal Vali2b3a3012013-10-24 23:40:02 +00003797 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003798 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3799 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003800 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003801 CallOpSpecialized->getPointOfInstantiation(),
3802 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003803
Faisal Vali2b3a3012013-10-24 23:40:02 +00003804 // Check to see if the return type of the destination ptr-to-function
3805 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003806 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003807 ReturnTypeOfDestFunctionPtr))
3808 return Sema::TDK_NonDeducedMismatch;
3809 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003810 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003811 // specialized our corresponding call operator, we are ready to
3812 // specialize the static invoker with the deduced arguments of our
3813 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003814 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003815 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3816 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3817
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003818#ifndef NDEBUG
3819 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3820#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003821 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003822 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003823 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003824 "If the call operator succeeded so should the invoker!");
3825 // Set the result type to match the corresponding call operator
3826 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003827 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3828 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003829 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003830 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003831 // to substitute into the 'auto' of the invoker and conversion
3832 // function.
3833 // For e.g.
3834 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3835 // We don't want to subst 'int*' into 'auto' to get int**.
3836
Alp Toker314cc812014-01-25 16:55:45 +00003837 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3838 ->getContainedAutoType()
3839 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003840 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3841 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003842 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003843 TypeToReplaceAutoWith, S);
3844 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003845
Faisal Vali2b3a3012013-10-24 23:40:02 +00003846 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003847 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003848 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003849 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003850 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3851 getType().getTypePtr()->castAs<FunctionProtoType>();
3852 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3853 EPI.TypeQuals = 0;
3854 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003855 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003856 return Sema::TDK_Success;
3857}
Douglas Gregor05155d82009-08-21 23:19:43 +00003858/// \brief Deduce template arguments for a templated conversion
3859/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3860/// conversion function template specialization.
3861Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003862Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003863 QualType ToType,
3864 CXXConversionDecl *&Specialization,
3865 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003866 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003867 return TDK_Invalid;
3868
Faisal Vali2b3a3012013-10-24 23:40:02 +00003869 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003870 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3871
Faisal Vali2b3a3012013-10-24 23:40:02 +00003872 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003873
3874 // Canonicalize the types for deduction.
3875 QualType P = Context.getCanonicalType(FromType);
3876 QualType A = Context.getCanonicalType(ToType);
3877
Douglas Gregord99609a2011-03-06 09:03:20 +00003878 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003879 // If P is a reference type, the type referred to by P is used for
3880 // type deduction.
3881 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3882 P = PRef->getPointeeType();
3883
Douglas Gregord99609a2011-03-06 09:03:20 +00003884 // C++0x [temp.deduct.conv]p4:
3885 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003886 // for type deduction.
3887 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003888 A = ARef->getPointeeType().getUnqualifiedType();
3889 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003890 //
Mike Stump11289f42009-09-09 15:08:12 +00003891 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003892 else {
3893 assert(!A->isReferenceType() && "Reference types were handled above");
3894
3895 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003896 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003897 // of P for type deduction; otherwise,
3898 if (P->isArrayType())
3899 P = Context.getArrayDecayedType(P);
3900 // - If P is a function type, the pointer type produced by the
3901 // function-to-pointer standard conversion (4.3) is used in
3902 // place of P for type deduction; otherwise,
3903 else if (P->isFunctionType())
3904 P = Context.getPointerType(P);
3905 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003906 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003907 else
3908 P = P.getUnqualifiedType();
3909
Douglas Gregord99609a2011-03-06 09:03:20 +00003910 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003911 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003912 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003913 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003914 A = A.getUnqualifiedType();
3915 }
3916
Eli Friedman77dcc722012-02-08 03:07:05 +00003917 // Unevaluated SFINAE context.
3918 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003919 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003920
3921 // C++ [temp.deduct.conv]p1:
3922 // Template argument deduction is done by comparing the return
3923 // type of the template conversion function (call it P) with the
3924 // type that is required as the result of the conversion (call it
3925 // A) as described in 14.8.2.4.
3926 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003927 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003928 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003929 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003930
3931 // C++0x [temp.deduct.conv]p4:
3932 // In general, the deduction process attempts to find template
3933 // argument values that will make the deduced A identical to
3934 // A. However, there are two cases that allow a difference:
3935 unsigned TDF = 0;
3936 // - If the original A is a reference type, A can be more
3937 // cv-qualified than the deduced A (i.e., the type referred to
3938 // by the reference)
3939 if (ToType->isReferenceType())
3940 TDF |= TDF_ParamWithReferenceType;
3941 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003942 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003943 // conversion.
3944 //
3945 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3946 // both P and A are pointers or member pointers. In this case, we
3947 // just ignore cv-qualifiers completely).
3948 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003949 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003950 TDF |= TDF_IgnoreQualifiers;
3951 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003952 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3953 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003954 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003955
3956 // Create an Instantiation Scope for finalizing the operator.
3957 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003958 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003959 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003960 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003961 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003962 ConversionSpecialized, Info);
3963 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3964
3965 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003966 // to a ptr-to-function, use the deduced arguments from the conversion
3967 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003968 // e.g., int (*fp)(int) = [](auto a) { return a; };
3969 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003970
Faisal Vali2b3a3012013-10-24 23:40:02 +00003971 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003972 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003973 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003974 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003975 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003976 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003977 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003978 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3979
Simon Pilgrim728134c2016-08-12 11:43:57 +00003980 // Create the corresponding specializations of the call operator and
3981 // the static-invoker; and if the return type is auto,
3982 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003983 // DestFunctionPtrReturnType.
3984 // For instance:
3985 // auto L = [](auto a) { return f(a); };
3986 // int (*fp)(int) = L;
3987 // char (*fp2)(int) = L; <-- Not OK.
3988
3989 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003990 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003991 Info, *this);
3992 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003993 return Result;
3994}
3995
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003996/// \brief Deduce template arguments for a function template when there is
3997/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3998///
3999/// \param FunctionTemplate the function template for which we are performing
4000/// template argument deduction.
4001///
James Dennett18348b62012-06-22 08:52:37 +00004002/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004003/// arguments.
4004///
4005/// \param Specialization if template argument deduction was successful,
4006/// this will be set to the function template specialization produced by
4007/// template argument deduction.
4008///
4009/// \param Info the argument will be updated to provide additional information
4010/// about template argument deduction.
4011///
Richard Smithbaa47832016-12-01 02:11:49 +00004012/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4013/// the address of a function template in a context where we do not have a
4014/// target type, per [over.over]. If \c false, we are looking up a function
4015/// template specialization based on its signature, which only happens when
4016/// deducing a function parameter type from an argument that is a template-id
4017/// naming a function template specialization.
4018///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004019/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004020Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4021 FunctionTemplateDecl *FunctionTemplate,
4022 TemplateArgumentListInfo *ExplicitTemplateArgs,
4023 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4024 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004025 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004026 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004027 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004028}
4029
Richard Smith30482bc2011-02-20 03:19:35 +00004030namespace {
4031 /// Substitute the 'auto' type specifier within a type for a given replacement
4032 /// type.
4033 class SubstituteAutoTransform :
4034 public TreeTransform<SubstituteAutoTransform> {
4035 QualType Replacement;
4036 public:
Nico Weberc153d242014-07-28 00:02:09 +00004037 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
4038 : TreeTransform<SubstituteAutoTransform>(SemaRef),
4039 Replacement(Replacement) {}
4040
Richard Smith30482bc2011-02-20 03:19:35 +00004041 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4042 // If we're building the type pattern to deduce against, don't wrap the
4043 // substituted type in an AutoType. Certain template deduction rules
4044 // apply only when a template type parameter appears directly (and not if
4045 // the parameter is found through desugaring). For instance:
4046 // auto &&lref = lvalue;
4047 // must transform into "rvalue reference to T" not "rvalue reference to
4048 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00004049 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00004050 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00004051 TemplateTypeParmTypeLoc NewTL =
4052 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00004053 NewTL.setNameLoc(TL.getNameLoc());
4054 return Result;
4055 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00004056 bool Dependent =
4057 !Replacement.isNull() && Replacement->isDependentType();
4058 QualType Result =
4059 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00004060 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004061 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00004062 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4063 NewTL.setNameLoc(TL.getNameLoc());
4064 return Result;
4065 }
4066 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004067
4068 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4069 // Lambdas never need to be transformed.
4070 return E;
4071 }
Richard Smith061f1e22013-04-30 21:23:01 +00004072
Richard Smith2a7d4812013-05-04 07:00:32 +00004073 QualType Apply(TypeLoc TL) {
4074 // Create some scratch storage for the transformed type locations.
4075 // FIXME: We're just going to throw this information away. Don't build it.
4076 TypeLocBuilder TLB;
4077 TLB.reserve(TL.getFullDataSize());
4078 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004079 }
Richard Smith30482bc2011-02-20 03:19:35 +00004080 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004081}
Richard Smith30482bc2011-02-20 03:19:35 +00004082
Richard Smith2a7d4812013-05-04 07:00:32 +00004083Sema::DeduceAutoResult
4084Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
4085 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
4086}
4087
Richard Smith061f1e22013-04-30 21:23:01 +00004088/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004089///
4090/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004091/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004092/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004093/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00004094Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00004095Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00004096 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004097 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4098 if (NonPlaceholder.isInvalid())
4099 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004100 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004101 }
4102
Richard Smith2a7d4812013-05-04 07:00:32 +00004103 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004104 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004105 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004106 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004107 }
4108
Richard Smith74aeef52013-04-26 16:15:35 +00004109 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4110 // Since 'decltype(auto)' can only occur at the top of the type, we
4111 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004112 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004113 if (AT->isDecltypeAuto()) {
4114 if (isa<InitListExpr>(Init)) {
4115 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4116 return DAR_FailedAlreadyDiagnosed;
4117 }
4118
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004119 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004120 if (Deduced.isNull())
4121 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004122 // FIXME: Support a non-canonical deduced type for 'auto'.
4123 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004124 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004125 if (Result.isNull())
4126 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004127 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004128 } else if (!getLangOpts().CPlusPlus) {
4129 if (isa<InitListExpr>(Init)) {
4130 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4131 return DAR_FailedAlreadyDiagnosed;
4132 }
Richard Smith74aeef52013-04-26 16:15:35 +00004133 }
4134 }
4135
Richard Smith30482bc2011-02-20 03:19:35 +00004136 SourceLocation Loc = Init->getExprLoc();
4137
4138 LocalInstantiationScope InstScope(*this);
4139
4140 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004141 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004142 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4143 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004144 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4145 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004146 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4147 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004148
Richard Smith061f1e22013-04-30 21:23:01 +00004149 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4150 assert(!FuncParam.isNull() &&
4151 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004152
4153 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004154 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004155 Deduced.resize(1);
4156 QualType InitType = Init->getType();
4157 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004158
Craig Toppere6706e42012-09-19 02:26:47 +00004159 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004160
Richard Smith74801c82012-07-08 04:13:07 +00004161 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004162 if (InitList) {
4163 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004164 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4165 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004166 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004167 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004168 }
4169 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004170 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4171 Diag(Loc, diag::err_auto_bitfield);
4172 return DAR_FailedAlreadyDiagnosed;
4173 }
4174
James Y Knight7a22b242015-08-06 20:26:32 +00004175 if (AdjustFunctionParmAndArgTypesForDeduction(
4176 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004177 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004178
James Y Knight7a22b242015-08-06 20:26:32 +00004179 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4180 FuncParam, InitType, Info, Deduced,
4181 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004182 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004183 }
Richard Smith30482bc2011-02-20 03:19:35 +00004184
Eli Friedmane4310952012-11-06 23:56:42 +00004185 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004186 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004187
Eli Friedmane4310952012-11-06 23:56:42 +00004188 QualType DeducedType = Deduced[0].getAsType();
4189
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004190 if (InitList) {
4191 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4192 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004193 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004194 }
4195
Richard Smith061f1e22013-04-30 21:23:01 +00004196 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004197 if (Result.isNull())
4198 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004199
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004200 // Check that the deduced argument type is compatible with the original
4201 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004202 if (!InitList && !Result.isNull() &&
4203 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004204 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004205 Result)) {
4206 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004207 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004208 }
4209
Sebastian Redl09edce02012-01-23 22:09:39 +00004210 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004211}
4212
Simon Pilgrim728134c2016-08-12 11:43:57 +00004213QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004214 QualType TypeToReplaceAuto) {
4215 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4216 TransformType(TypeWithAuto);
4217}
4218
Simon Pilgrim728134c2016-08-12 11:43:57 +00004219TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004220 QualType TypeToReplaceAuto) {
4221 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4222 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004223}
4224
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004225void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4226 if (isa<InitListExpr>(Init))
4227 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004228 VDecl->isInitCapture()
4229 ? diag::err_init_capture_deduction_failure_from_init_list
4230 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004231 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4232 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004233 Diag(VDecl->getLocation(),
4234 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4235 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004236 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4237 << Init->getSourceRange();
4238}
4239
Richard Smith2a7d4812013-05-04 07:00:32 +00004240bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4241 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004242 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004243
4244 if (FD->getTemplateInstantiationPattern())
4245 InstantiateFunctionDefinition(Loc, FD);
4246
Alp Toker314cc812014-01-25 16:55:45 +00004247 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004248 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4249 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4250 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4251 }
4252
4253 return StillUndeduced;
4254}
4255
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004256static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004257MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004258 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004259 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004260 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261
4262/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004263static void
4264AddImplicitObjectParameterType(ASTContext &Context,
4265 CXXMethodDecl *Method,
4266 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004267 // C++11 [temp.func.order]p3:
4268 // [...] The new parameter is of type "reference to cv A," where cv are
4269 // the cv-qualifiers of the function template (if any) and A is
4270 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004271 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004272 // The standard doesn't say explicitly, but we pick the appropriate kind of
4273 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004274 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4275 ArgTy = Context.getQualifiedType(ArgTy,
4276 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004277 if (Method->getRefQualifier() == RQ_RValue)
4278 ArgTy = Context.getRValueReferenceType(ArgTy);
4279 else
4280 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004281 ArgTypes.push_back(ArgTy);
4282}
4283
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004284/// \brief Determine whether the function template \p FT1 is at least as
4285/// specialized as \p FT2.
4286static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004287 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004288 FunctionTemplateDecl *FT1,
4289 FunctionTemplateDecl *FT2,
4290 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004291 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004292 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004294 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4295 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004297 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4298 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004299 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004300 Deduced.resize(TemplateParams->size());
4301
4302 // C++0x [temp.deduct.partial]p3:
4303 // The types used to determine the ordering depend on the context in which
4304 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004305 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004306 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004307 switch (TPOC) {
4308 case TPOC_Call: {
4309 // - In the context of a function call, the function parameter types are
4310 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004311 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4312 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004313
Eli Friedman3b5774a2012-09-19 23:27:04 +00004314 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004315 // [...] If only one of the function templates is a non-static
4316 // member, that function template is considered to have a new
4317 // first parameter inserted in its function parameter list. The
4318 // new parameter is of type "reference to cv A," where cv are
4319 // the cv-qualifiers of the function template (if any) and A is
4320 // the class of which the function template is a member.
4321 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004322 // Note that we interpret this to mean "if one of the function
4323 // templates is a non-static member and the other is a non-member";
4324 // otherwise, the ordering rules for static functions against non-static
4325 // functions don't make any sense.
4326 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004327 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4328 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004329 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004330
Richard Smithe5b52202013-09-11 00:52:39 +00004331 unsigned NumComparedArguments = NumCallArguments1;
4332
4333 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004334 // Compare 'this' from Method1 against first parameter from Method2.
4335 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4336 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004337 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004338 // Compare 'this' from Method2 against first parameter from Method1.
4339 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004340 }
4341
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004342 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004343 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004344 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004345 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregorb837ea42011-01-11 17:34:58 +00004347 // C++ [temp.func.order]p5:
4348 // The presence of unused ellipsis and default arguments has no effect on
4349 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004350 if (Args1.size() > NumComparedArguments)
4351 Args1.resize(NumComparedArguments);
4352 if (Args2.size() > NumComparedArguments)
4353 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004354 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4355 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004356 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004357 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004359 break;
4360 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004362 case TPOC_Conversion:
4363 // - In the context of a call to a conversion operator, the return types
4364 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004365 if (DeduceTemplateArgumentsByTypeMatch(
4366 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4367 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004368 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004369 return false;
4370 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004372 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004373 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004374 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004375 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4376 FD2->getType(), FD1->getType(),
4377 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004378 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004379 return false;
4380 break;
4381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004382
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004383 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384 // In most cases, all template parameters must have values in order for
4385 // deduction to succeed, but for partial ordering purposes a template
4386 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004387 // types being used for partial ordering. [ Note: a template parameter used
4388 // in a non-deduced context is considered used. -end note]
4389 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4390 for (; ArgIdx != NumArgs; ++ArgIdx)
4391 if (Deduced[ArgIdx].isNull())
4392 break;
4393
4394 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004396 // as FT2.
4397 return true;
4398 }
4399
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004400 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004401 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004402 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004403 case TPOC_Call:
4404 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4405 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004406 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004407 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004408 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004410 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004411 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4412 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004413 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004414
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004415 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004416 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004417 TemplateParams->getDepth(),
4418 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004419 break;
4420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004421
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004422 for (; ArgIdx != NumArgs; ++ArgIdx)
4423 // If this argument had no value deduced but was used in one of the types
4424 // used for partial ordering, then deduction fails.
4425 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4426 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004428 return true;
4429}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004430
Douglas Gregorcef1a032011-01-16 16:03:23 +00004431/// \brief Determine whether this a function template whose parameter-type-list
4432/// ends with a function parameter pack.
4433static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4434 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4435 unsigned NumParams = Function->getNumParams();
4436 if (NumParams == 0)
4437 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004438
Douglas Gregorcef1a032011-01-16 16:03:23 +00004439 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4440 if (!Last->isParameterPack())
4441 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442
Douglas Gregorcef1a032011-01-16 16:03:23 +00004443 // Make sure that no previous parameter is a parameter pack.
4444 while (--NumParams > 0) {
4445 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4446 return false;
4447 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448
Douglas Gregorcef1a032011-01-16 16:03:23 +00004449 return true;
4450}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451
Douglas Gregorbe999392009-09-15 16:23:51 +00004452/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004453/// to the rules of function template partial ordering (C++ [temp.func.order]).
4454///
4455/// \param FT1 the first function template
4456///
4457/// \param FT2 the second function template
4458///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004459/// \param TPOC the context in which we are performing partial ordering of
4460/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004461///
Richard Smithe5b52202013-09-11 00:52:39 +00004462/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4463/// only when \c TPOC is \c TPOC_Call.
4464///
4465/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4466/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004467///
Douglas Gregorbe999392009-09-15 16:23:51 +00004468/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004469/// template is more specialized, returns NULL.
4470FunctionTemplateDecl *
4471Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4472 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004473 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004474 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004475 unsigned NumCallArguments1,
4476 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004477 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004478 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004480 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004482 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004483 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004484
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004485 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004486 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004487
Douglas Gregorcef1a032011-01-16 16:03:23 +00004488 // FIXME: This mimics what GCC implements, but doesn't match up with the
4489 // proposed resolution for core issue 692. This area needs to be sorted out,
4490 // but for now we attempt to maintain compatibility.
4491 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4492 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4493 if (Variadic1 != Variadic2)
4494 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004495
Craig Topperc3ec1492014-05-26 06:22:03 +00004496 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004497}
Douglas Gregor9b146582009-07-08 20:55:45 +00004498
Douglas Gregor450f00842009-09-25 18:43:00 +00004499/// \brief Determine if the two templates are equivalent.
4500static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4501 if (T1 == T2)
4502 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregor450f00842009-09-25 18:43:00 +00004504 if (!T1 || !T2)
4505 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
Douglas Gregor450f00842009-09-25 18:43:00 +00004507 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4508}
4509
4510/// \brief Retrieve the most specialized of the given function template
4511/// specializations.
4512///
John McCall58cc69d2010-01-27 01:50:18 +00004513/// \param SpecBegin the start iterator of the function template
4514/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004515///
John McCall58cc69d2010-01-27 01:50:18 +00004516/// \param SpecEnd the end iterator of the function template
4517/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004518///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004520/// diagnostic should occur.
4521///
4522/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4523/// no matching candidates.
4524///
4525/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4526/// occurs.
4527///
4528/// \param CandidateDiag partial diagnostic used for each function template
4529/// specialization that is a candidate in the ambiguous ordering. One parameter
4530/// in this diagnostic should be unbound, which will correspond to the string
4531/// describing the template arguments for the function template specialization.
4532///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004534/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004535UnresolvedSetIterator Sema::getMostSpecialized(
4536 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4537 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004538 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4539 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4540 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004541 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004542 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004543 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004544 FailedCandidates.NoteCandidates(*this, Loc);
4545 }
John McCall58cc69d2010-01-27 01:50:18 +00004546 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548
4549 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004550 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551
Douglas Gregor450f00842009-09-25 18:43:00 +00004552 // Find the function template that is better than all of the templates it
4553 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004554 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004555 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004556 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004557 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004558 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4559 FunctionTemplateDecl *Challenger
4560 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004561 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004562 if (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 Challenger)) {
4565 Best = I;
4566 BestTemplate = Challenger;
4567 }
4568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004569
Douglas Gregor450f00842009-09-25 18:43:00 +00004570 // Make sure that the "best" function template is more specialized than all
4571 // of the others.
4572 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004573 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4574 FunctionTemplateDecl *Challenger
4575 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004576 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004578 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004579 BestTemplate)) {
4580 Ambiguous = true;
4581 break;
4582 }
4583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584
Douglas Gregor450f00842009-09-25 18:43:00 +00004585 if (!Ambiguous) {
4586 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004587 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004588 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589
Douglas Gregor450f00842009-09-25 18:43:00 +00004590 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004591 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004592 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004593
Richard Smithb875c432013-05-04 01:51:08 +00004594 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004595 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4596 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004597 const auto *FD = cast<FunctionDecl>(*I);
4598 PD << FD << getTemplateArgumentBindingsText(
4599 FD->getPrimaryTemplate()->getTemplateParameters(),
4600 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004601 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004602 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004603 Diag((*I)->getLocation(), PD);
4604 }
Richard Smithb875c432013-05-04 01:51:08 +00004605 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004606
John McCall58cc69d2010-01-27 01:50:18 +00004607 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004608}
4609
Douglas Gregorbe999392009-09-15 16:23:51 +00004610/// \brief Returns the more specialized class template partial specialization
4611/// according to the rules of partial ordering of class template partial
4612/// specializations (C++ [temp.class.order]).
4613///
4614/// \param PS1 the first class template partial specialization
4615///
4616/// \param PS2 the second class template partial specialization
4617///
4618/// \returns the more specialized class template partial specialization. If
4619/// neither partial specialization is more specialized, returns NULL.
4620ClassTemplatePartialSpecializationDecl *
4621Sema::getMoreSpecializedPartialSpecialization(
4622 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004623 ClassTemplatePartialSpecializationDecl *PS2,
4624 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004625 // C++ [temp.class.order]p1:
4626 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627 // specialized as the second if, given the following rewrite to two
4628 // function templates, the first function template is at least as
4629 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004630 // templates (14.6.6.2):
4631 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004632 // first partial specialization and has a single function parameter
4633 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004634 // arguments of the first partial specialization, and
4635 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004636 // second partial specialization and has a single function parameter
4637 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004638 // arguments of the second partial specialization.
4639 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004640 // Rather than synthesize function templates, we merely perform the
4641 // equivalent partial ordering by performing deduction directly on
4642 // the template arguments of the class template partial
4643 // specializations. This computation is slightly simpler than the
4644 // general problem of function template partial ordering, because
4645 // class template partial specializations are more constrained. We
4646 // know that every template parameter is deducible from the class
4647 // template partial specialization's template arguments, for
4648 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004649 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004650 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004651
4652 QualType PT1 = PS1->getInjectedSpecializationType();
4653 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654
Douglas Gregorbe999392009-09-15 16:23:51 +00004655 // Determine whether PS1 is at least as specialized as PS2
4656 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004657 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4658 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004659 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004660 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004661 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004662 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004663 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004664 Better1 = !::FinishTemplateArgumentDeduction(
4665 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4666 }
4667
4668 // Determine whether PS2 is at least as specialized as PS1
4669 Deduced.clear();
4670 Deduced.resize(PS1->getTemplateParameters()->size());
4671 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4672 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004673 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004674 if (Better2) {
4675 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4676 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004677 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004678 Better2 = !::FinishTemplateArgumentDeduction(
4679 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4680 }
4681
4682 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004683 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004684
4685 return Better1 ? PS1 : PS2;
4686}
4687
Larisse Voufo30616382013-08-23 22:21:36 +00004688/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4689/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4690/// VarTemplate(Partial)SpecializationDecl with a new data
4691/// structure Template(Partial)SpecializationDecl, and
4692/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004693VarTemplatePartialSpecializationDecl *
4694Sema::getMoreSpecializedPartialSpecialization(
4695 VarTemplatePartialSpecializationDecl *PS1,
4696 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4697 SmallVector<DeducedTemplateArgument, 4> Deduced;
4698 TemplateDeductionInfo Info(Loc);
4699
Richard Smithf04fd0b2013-12-12 23:14:16 +00004700 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004701 "the partial specializations being compared should specialize"
4702 " the same template.");
4703 TemplateName Name(PS1->getSpecializedTemplate());
4704 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4705 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004706 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004707 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004708 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004709
4710 // Determine whether PS1 is at least as specialized as PS2
4711 Deduced.resize(PS2->getTemplateParameters()->size());
4712 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4713 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004714 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004715 if (Better1) {
4716 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4717 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004718 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004719 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4720 PS1->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 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004725 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004726 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004727 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4728 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004729 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004730 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004731 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004732 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004733 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4735 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004736 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
Douglas Gregorbe999392009-09-15 16:23:51 +00004739 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004740 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741
Douglas Gregorbe999392009-09-15 16:23:51 +00004742 return Better1? PS1 : PS2;
4743}
4744
Mike Stump11289f42009-09-09 15:08:12 +00004745static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004746MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004747 const TemplateArgument &TemplateArg,
4748 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004749 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004750 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004751
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004752/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004753/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004754static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004755MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004756 const Expr *E,
4757 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004758 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004759 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004760 // We can deduce from a pack expansion.
4761 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4762 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763
Richard Smith34349002012-07-09 03:07:20 +00004764 // Skip through any implicit casts we added while type-checking, and any
4765 // substitutions performed by template alias expansion.
4766 while (1) {
4767 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4768 E = ICE->getSubExpr();
4769 else if (const SubstNonTypeTemplateParmExpr *Subst =
4770 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4771 E = Subst->getReplacement();
4772 else
4773 break;
4774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
4776 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004777 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004778 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004779 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004780 return;
4781
Mike Stump11289f42009-09-09 15:08:12 +00004782 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004783 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4784 if (!NTTP)
4785 return;
4786
Douglas Gregor21610382009-10-29 00:04:11 +00004787 if (NTTP->getDepth() == Depth)
4788 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004789
4790 // In C++1z mode, additional arguments may be deduced from the type of a
4791 // non-type argument.
4792 if (Ctx.getLangOpts().CPlusPlus1z)
4793 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004794}
4795
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004796/// \brief Mark the template parameters that are used by the given
4797/// nested name specifier.
4798static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004799MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004800 NestedNameSpecifier *NNS,
4801 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004802 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004803 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004804 if (!NNS)
4805 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004807 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004808 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004809 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004810 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004811}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004812
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004813/// \brief Mark the template parameters that are used by the given
4814/// template name.
4815static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004816MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004817 TemplateName Name,
4818 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004819 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004820 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004821 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4822 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004823 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4824 if (TTP->getDepth() == Depth)
4825 Used[TTP->getIndex()] = true;
4826 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004827 return;
4828 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004830 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004831 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004832 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004833 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004834 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004835 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004836}
4837
4838/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004839/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004840static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004841MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004842 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004843 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004844 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004845 if (T.isNull())
4846 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004847
Douglas Gregor91772d12009-06-13 00:26:55 +00004848 // Non-dependent types have nothing deducible
4849 if (!T->isDependentType())
4850 return;
4851
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004852 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004853 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004854 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004855 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004856 cast<PointerType>(T)->getPointeeType(),
4857 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004858 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004859 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004860 break;
4861
4862 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004863 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004864 cast<BlockPointerType>(T)->getPointeeType(),
4865 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004866 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004867 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004868 break;
4869
4870 case Type::LValueReference:
4871 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004872 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004873 cast<ReferenceType>(T)->getPointeeType(),
4874 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004875 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004876 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004877 break;
4878
4879 case Type::MemberPointer: {
4880 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004881 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004882 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004883 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004884 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004885 break;
4886 }
4887
4888 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004889 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004890 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004891 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004892 // Fall through to check the element type
4893
4894 case Type::ConstantArray:
4895 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004896 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004897 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004898 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004899 break;
4900
4901 case Type::Vector:
4902 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004903 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004904 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004905 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004906 break;
4907
Douglas Gregor758a8692009-06-17 21:51:59 +00004908 case Type::DependentSizedExtVector: {
4909 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004910 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004911 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004912 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004913 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004914 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004915 break;
4916 }
4917
Douglas Gregor91772d12009-06-13 00:26:55 +00004918 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004919 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004920 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4921 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004922 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4923 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004924 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004925 break;
4926 }
4927
Douglas Gregor21610382009-10-29 00:04:11 +00004928 case Type::TemplateTypeParm: {
4929 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4930 if (TTP->getDepth() == Depth)
4931 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004932 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004933 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004934
Douglas Gregorfb322d82011-01-14 05:11:40 +00004935 case Type::SubstTemplateTypeParmPack: {
4936 const SubstTemplateTypeParmPackType *Subst
4937 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004938 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004939 QualType(Subst->getReplacedParameter(), 0),
4940 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004941 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004942 OnlyDeduced, Depth, Used);
4943 break;
4944 }
4945
John McCall2408e322010-04-27 00:57:59 +00004946 case Type::InjectedClassName:
4947 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4948 // fall through
4949
Douglas Gregor91772d12009-06-13 00:26:55 +00004950 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004951 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004952 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004953 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004954 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955
Douglas Gregord0ad2942010-12-23 01:24:45 +00004956 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004957 // If the template argument list of P contains a pack expansion that is
4958 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004959 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004960 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004961 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4962 break;
4963
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004964 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004965 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004966 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004967 break;
4968 }
4969
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004970 case Type::Complex:
4971 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004972 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004973 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004974 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004975 break;
4976
Eli Friedman0dfb8892011-10-06 23:00:33 +00004977 case Type::Atomic:
4978 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004979 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004980 cast<AtomicType>(T)->getValueType(),
4981 OnlyDeduced, Depth, Used);
4982 break;
4983
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004984 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004985 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004986 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004987 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004988 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004989 break;
4990
John McCallc392f372010-06-11 00:33:02 +00004991 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004992 // C++14 [temp.deduct.type]p5:
4993 // The non-deduced contexts are:
4994 // -- The nested-name-specifier of a type that was specified using a
4995 // qualified-id
4996 //
4997 // C++14 [temp.deduct.type]p6:
4998 // When a type name is specified in a way that includes a non-deduced
4999 // context, all of the types that comprise that type name are also
5000 // non-deduced.
5001 if (OnlyDeduced)
5002 break;
5003
John McCallc392f372010-06-11 00:33:02 +00005004 const DependentTemplateSpecializationType *Spec
5005 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006
Richard Smith50d5b972015-12-30 20:56:05 +00005007 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5008 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005009
John McCallc392f372010-06-11 00:33:02 +00005010 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005011 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005012 Used);
5013 break;
5014 }
5015
John McCallbd8d9bd2010-03-01 23:49:17 +00005016 case Type::TypeOf:
5017 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005018 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005019 cast<TypeOfType>(T)->getUnderlyingType(),
5020 OnlyDeduced, Depth, Used);
5021 break;
5022
5023 case Type::TypeOfExpr:
5024 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005025 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005026 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5027 OnlyDeduced, Depth, Used);
5028 break;
5029
5030 case Type::Decltype:
5031 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005032 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005033 cast<DecltypeType>(T)->getUnderlyingExpr(),
5034 OnlyDeduced, Depth, Used);
5035 break;
5036
Alexis Hunte852b102011-05-24 22:41:36 +00005037 case Type::UnaryTransform:
5038 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005039 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005040 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005041 OnlyDeduced, Depth, Used);
5042 break;
5043
Douglas Gregord2fa7662010-12-20 02:24:11 +00005044 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005045 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005046 cast<PackExpansionType>(T)->getPattern(),
5047 OnlyDeduced, Depth, Used);
5048 break;
5049
Richard Smith30482bc2011-02-20 03:19:35 +00005050 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005051 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00005052 cast<AutoType>(T)->getDeducedType(),
5053 OnlyDeduced, Depth, Used);
5054
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005055 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005056 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005057 case Type::VariableArray:
5058 case Type::FunctionNoProto:
5059 case Type::Record:
5060 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005061 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005062 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005063 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005064 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005065 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005066#define TYPE(Class, Base)
5067#define ABSTRACT_TYPE(Class, Base)
5068#define DEPENDENT_TYPE(Class, Base)
5069#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5070#include "clang/AST/TypeNodes.def"
5071 break;
5072 }
5073}
5074
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005075/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005076/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005077static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005078MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005079 const TemplateArgument &TemplateArg,
5080 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005081 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005082 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005083 switch (TemplateArg.getKind()) {
5084 case TemplateArgument::Null:
5085 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005086 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005087 break;
Mike Stump11289f42009-09-09 15:08:12 +00005088
Eli Friedmanb826a002012-09-26 02:36:12 +00005089 case TemplateArgument::NullPtr:
5090 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5091 Depth, Used);
5092 break;
5093
Douglas Gregor91772d12009-06-13 00:26:55 +00005094 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005095 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005096 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005097 break;
5098
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005099 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005100 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005101 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005102 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005103 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005104 break;
5105
5106 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005107 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005108 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005109 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005110
Anders Carlssonbc343912009-06-15 17:04:53 +00005111 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005112 for (const auto &P : TemplateArg.pack_elements())
5113 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005114 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005115 }
5116}
5117
James Dennett41725122012-06-22 10:16:05 +00005118/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005119/// template argument list.
5120///
5121/// \param TemplateArgs the template argument list from which template
5122/// parameters will be deduced.
5123///
James Dennett41725122012-06-22 10:16:05 +00005124/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005125/// to indicate when the corresponding template parameter will be
5126/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005127void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005128Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005129 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005130 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005131 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005132 // If the template argument list of P contains a pack expansion that is not
5133 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005134 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005135 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005136 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5137 return;
5138
Douglas Gregor91772d12009-06-13 00:26:55 +00005139 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005140 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005141 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005142}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005143
5144/// \brief Marks all of the template parameters that will be deduced by a
5145/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005146void Sema::MarkDeducedTemplateParameters(
5147 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5148 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005149 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005150 = FunctionTemplate->getTemplateParameters();
5151 Deduced.clear();
5152 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005153
Douglas Gregorce23bae2009-09-18 23:21:38 +00005154 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5155 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005156 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005157 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005158}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005159
5160bool hasDeducibleTemplateParameters(Sema &S,
5161 FunctionTemplateDecl *FunctionTemplate,
5162 QualType T) {
5163 if (!T->isDependentType())
5164 return false;
5165
5166 TemplateParameterList *TemplateParams
5167 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005168 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005169 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005170 Deduced);
5171
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005172 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005173}