blob: 98e22c0b65e0b36ac49fedcf6cd18eed43744936 [file] [log] [blame]
Douglas Gregor0b9247f2009-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
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000017#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000019#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
Benjamin Kramer013b3662012-01-30 16:17:39 +000023#include "llvm/ADT/SmallBitVector.h"
Richard Smith34b41d92011-02-20 03:19:35 +000024#include "TreeTransform.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000026
27namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregor508f1c82009-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 Gregor41128772009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-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 Gregor73b3cf62011-01-25 17:19:08 +000052 TDF_SkipNonDependent = 0x08,
53 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000054 /// parameters and arguments in a top-level template argument
Douglas Gregor73b3cf62011-01-25 17:19:08 +000055 TDF_TopLevelParameterTypeList = 0x10
Douglas Gregor508f1c82009-06-26 23:10:12 +000056 };
57}
58
Douglas Gregor0b9247f2009-06-04 00:03:07 +000059using namespace clang;
60
Douglas Gregor9d0e4412010-03-26 05:50:28 +000061/// \brief Compare two APSInts, extending and switching the sign as
62/// necessary to compare their values regardless of underlying type.
63static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
64 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000065 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000066 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000067 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000068
69 // If there is a signedness mismatch, correct it.
70 if (X.isSigned() != Y.isSigned()) {
71 // If the signed value is negative, then the values cannot be the same.
72 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
73 return false;
74
75 Y.setIsSigned(true);
76 X.setIsSigned(true);
77 }
78
79 return X == Y;
80}
81
Douglas Gregorf67875d2009-06-12 18:26:56 +000082static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000083DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000084 TemplateParameterList *TemplateParams,
85 const TemplateArgument &Param,
Douglas Gregor77d6bb92011-01-11 22:21:24 +000086 TemplateArgument Arg,
John McCall2a7fb272010-08-25 05:32:35 +000087 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +000088 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000089
Douglas Gregorb939a192011-01-21 17:29:42 +000090/// \brief Whether template argument deduction for two reference parameters
91/// resulted in the argument type, parameter type, or neither type being more
92/// qualified than the other.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000093enum DeductionQualifierComparison {
94 NeitherMoreQualified = 0,
95 ParamMoreQualified,
96 ArgMoreQualified
Douglas Gregor5c7bf422011-01-11 17:34:58 +000097};
98
Douglas Gregorb939a192011-01-21 17:29:42 +000099/// \brief Stores the result of comparing two reference parameters while
100/// performing template argument deduction for partial ordering of function
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000101/// templates.
Douglas Gregorb939a192011-01-21 17:29:42 +0000102struct RefParamPartialOrderingComparison {
103 /// \brief Whether the parameter type is an rvalue reference type.
104 bool ParamIsRvalueRef;
105 /// \brief Whether the argument type is an rvalue reference type.
106 bool ArgIsRvalueRef;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000107
Douglas Gregorb939a192011-01-21 17:29:42 +0000108 /// \brief Whether the parameter or argument (or neither) is more qualified.
109 DeductionQualifierComparison Qualifiers;
110};
111
112
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000113
Douglas Gregor20a55e22010-12-22 18:17:10 +0000114static Sema::TemplateDeductionResult
Sebastian Redlbb95e512012-01-17 22:49:52 +0000115DeduceTemplateArgumentsByTypeMatch(Sema &S,
116 TemplateParameterList *TemplateParams,
117 QualType Param,
118 QualType Arg,
119 TemplateDeductionInfo &Info,
120 SmallVectorImpl<DeducedTemplateArgument> &
121 Deduced,
122 unsigned TDF,
123 bool PartialOrdering = false,
124 SmallVectorImpl<RefParamPartialOrderingComparison> *
Douglas Gregorb939a192011-01-21 17:29:42 +0000125 RefParamComparisons = 0);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000126
127static Sema::TemplateDeductionResult
128DeduceTemplateArguments(Sema &S,
129 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +0000130 const TemplateArgument *Params, unsigned NumParams,
131 const TemplateArgument *Args, unsigned NumArgs,
132 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor0972c862010-12-22 18:55:49 +0000134 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000135
Douglas Gregor199d9912009-06-05 00:53:49 +0000136/// \brief If the given expression is of a form that permits the deduction
137/// of a non-type template parameter, return the declaration of that
138/// non-type template parameter.
139static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
Richard Smith5a343d72012-07-08 04:37:51 +0000140 // If we are within an alias template, the expression may have undergone
141 // any number of parameter substitutions already.
142 while (1) {
143 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
144 E = IC->getSubExpr();
145 else if (SubstNonTypeTemplateParmExpr *Subst =
146 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
147 E = Subst->getReplacement();
148 else
149 break;
150 }
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Douglas Gregor199d9912009-06-05 00:53:49 +0000152 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
153 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000154
Douglas Gregor199d9912009-06-05 00:53:49 +0000155 return 0;
156}
157
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000158/// \brief Determine whether two declaration pointers refer to the same
159/// declaration.
160static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000161 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
162 X = NX->getUnderlyingDecl();
163 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
164 Y = NY->getUnderlyingDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000165
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000166 return X->getCanonicalDecl() == Y->getCanonicalDecl();
167}
168
169/// \brief Verify that the given, deduced template arguments are compatible.
170///
171/// \returns The deduced template argument, or a NULL template argument if
172/// the deduced template arguments were incompatible.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000173static DeducedTemplateArgument
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000174checkDeducedTemplateArguments(ASTContext &Context,
175 const DeducedTemplateArgument &X,
176 const DeducedTemplateArgument &Y) {
177 // We have no deduction for one or both of the arguments; they're compatible.
178 if (X.isNull())
179 return Y;
180 if (Y.isNull())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000181 return X;
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000182
183 switch (X.getKind()) {
184 case TemplateArgument::Null:
185 llvm_unreachable("Non-deduced template arguments handled above");
186
187 case TemplateArgument::Type:
188 // If two template type arguments have the same type, they're compatible.
189 if (Y.getKind() == TemplateArgument::Type &&
190 Context.hasSameType(X.getAsType(), Y.getAsType()))
191 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000192
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000193 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000194
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000195 case TemplateArgument::Integral:
196 // If we deduced a constant in one case and either a dependent expression or
197 // declaration in another case, keep the integral constant.
198 // If both are integral constants with the same value, keep that value.
199 if (Y.getKind() == TemplateArgument::Expression ||
200 Y.getKind() == TemplateArgument::Declaration ||
201 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer85524372012-06-07 15:09:51 +0000202 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000203 return DeducedTemplateArgument(X,
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000204 X.wasDeducedFromArrayBound() &&
205 Y.wasDeducedFromArrayBound());
206
207 // All other combinations are incompatible.
208 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000209
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000210 case TemplateArgument::Template:
211 if (Y.getKind() == TemplateArgument::Template &&
212 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
213 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000214
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000215 // All other combinations are incompatible.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000216 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000217
218 case TemplateArgument::TemplateExpansion:
219 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000220 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregora7fc9012011-01-05 18:58:31 +0000221 Y.getAsTemplateOrTemplatePattern()))
222 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000223
Douglas Gregora7fc9012011-01-05 18:58:31 +0000224 // All other combinations are incompatible.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000225 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000226
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000227 case TemplateArgument::Expression:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000228 // If we deduced a dependent expression in one case and either an integral
229 // constant or a declaration in another case, keep the integral constant
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000230 // or declaration.
231 if (Y.getKind() == TemplateArgument::Integral ||
232 Y.getKind() == TemplateArgument::Declaration)
233 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
234 Y.wasDeducedFromArrayBound());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000235
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000236 if (Y.getKind() == TemplateArgument::Expression) {
237 // Compare the expressions for equality
238 llvm::FoldingSetNodeID ID1, ID2;
239 X.getAsExpr()->Profile(ID1, Context, true);
240 Y.getAsExpr()->Profile(ID2, Context, true);
241 if (ID1 == ID2)
242 return X;
243 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000244
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000245 // All other combinations are incompatible.
246 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000247
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000248 case TemplateArgument::Declaration:
249 // If we deduced a declaration and a dependent expression, keep the
250 // declaration.
251 if (Y.getKind() == TemplateArgument::Expression)
252 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000253
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000254 // If we deduced a declaration and an integral constant, keep the
255 // integral constant.
256 if (Y.getKind() == TemplateArgument::Integral)
257 return Y;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000258
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000259 // If we deduced two declarations, make sure they they refer to the
260 // same declaration.
261 if (Y.getKind() == TemplateArgument::Declaration &&
Eli Friedmand7a6b162012-09-26 02:36:12 +0000262 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) &&
263 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam())
264 return X;
265
266 // All other combinations are incompatible.
267 return DeducedTemplateArgument();
268
269 case TemplateArgument::NullPtr:
270 // If we deduced a null pointer and a dependent expression, keep the
271 // null pointer.
272 if (Y.getKind() == TemplateArgument::Expression)
273 return X;
274
275 // If we deduced a null pointer and an integral constant, keep the
276 // integral constant.
277 if (Y.getKind() == TemplateArgument::Integral)
278 return Y;
279
280 // If we deduced two null pointers, make sure they have the same type.
281 if (Y.getKind() == TemplateArgument::NullPtr &&
282 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000283 return X;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000284
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000285 // All other combinations are incompatible.
286 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000287
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000288 case TemplateArgument::Pack:
289 if (Y.getKind() != TemplateArgument::Pack ||
290 X.pack_size() != Y.pack_size())
291 return DeducedTemplateArgument();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000292
293 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000294 XAEnd = X.pack_end(),
295 YA = Y.pack_begin();
296 XA != XAEnd; ++XA, ++YA) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000297 if (checkDeducedTemplateArguments(Context,
298 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregor135ffa72011-01-05 21:00:53 +0000299 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
300 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000301 return DeducedTemplateArgument();
302 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000303
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000304 return X;
305 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000306
David Blaikie30263482012-01-20 21:50:17 +0000307 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000308}
309
Mike Stump1eb44332009-09-09 15:08:12 +0000310/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000311/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000312static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000313DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000314 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000315 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000316 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000317 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000318 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000319 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000320 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Benjamin Kramer85524372012-06-07 15:09:51 +0000322 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
323 DeducedFromArrayBound);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000324 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000325 Deduced[NTTP->getIndex()],
326 NewDeduced);
327 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000328 Info.Param = NTTP;
329 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000330 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000331 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000332 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000333
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000334 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000335 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000336}
337
Mike Stump1eb44332009-09-09 15:08:12 +0000338/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000339/// from the given type- or value-dependent expression.
340///
341/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000342static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000343DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000344 NonTypeTemplateParmDecl *NTTP,
345 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000346 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000347 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000348 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000349 "Cannot deduce non-type template argument with depth > 0");
350 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
351 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000353 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000354 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
355 Deduced[NTTP->getIndex()],
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000356 NewDeduced);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000357
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000358 if (Result.isNull()) {
359 Info.Param = NTTP;
360 Info.FirstArg = Deduced[NTTP->getIndex()];
361 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000362 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000363 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000364
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000365 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000366 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000367}
368
Douglas Gregor15755cb2009-11-13 23:45:44 +0000369/// \brief Deduce the value of the given non-type template parameter
370/// from the given declaration.
371///
372/// \returns true if deduction succeeded, false otherwise.
373static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000374DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000375 NonTypeTemplateParmDecl *NTTP,
Eli Friedmand7a6b162012-09-26 02:36:12 +0000376 ValueDecl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000377 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000378 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000379 assert(NTTP->getDepth() == 0 &&
380 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000381
Eli Friedmand7a6b162012-09-26 02:36:12 +0000382 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : 0;
383 TemplateArgument New(D, NTTP->getType()->isReferenceType());
384 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000385 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000386 Deduced[NTTP->getIndex()],
387 NewDeduced);
388 if (Result.isNull()) {
389 Info.Param = NTTP;
390 Info.FirstArg = Deduced[NTTP->getIndex()];
391 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000392 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000393 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000394
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000395 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000396 return Sema::TDK_Success;
397}
398
Douglas Gregorf67875d2009-06-12 18:26:56 +0000399static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000400DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000401 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000402 TemplateName Param,
403 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000404 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000405 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000406 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000407 if (!ParamDecl) {
408 // The parameter type is dependent and is not a template template parameter,
409 // so there is nothing that we can deduce.
410 return Sema::TDK_Success;
411 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000412
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000413 if (TemplateTemplateParmDecl *TempParam
414 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000415 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000416 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000417 Deduced[TempParam->getIndex()],
418 NewDeduced);
419 if (Result.isNull()) {
420 Info.Param = TempParam;
421 Info.FirstArg = Deduced[TempParam->getIndex()];
422 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000424 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000425
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000426 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000427 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000428 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000429
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000430 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000431 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000432 return Sema::TDK_Success;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000433
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000434 // Mismatch of non-dependent template parameter to argument.
435 Info.FirstArg = TemplateArgument(Param);
436 Info.SecondArg = TemplateArgument(Arg);
437 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000438}
439
Mike Stump1eb44332009-09-09 15:08:12 +0000440/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000441/// type (which is a template-id) with the template argument type.
442///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000443/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000444///
445/// \param TemplateParams the template parameters that we are deducing
446///
447/// \param Param the parameter type
448///
449/// \param Arg the argument type
450///
451/// \param Info information about the template argument deduction itself
452///
453/// \param Deduced the deduced template arguments
454///
455/// \returns the result of template argument deduction so far. Note that a
456/// "success" result means that template argument deduction has not yet failed,
457/// but it may still fail, later, for other reasons.
458static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000459DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000460 TemplateParameterList *TemplateParams,
461 const TemplateSpecializationType *Param,
462 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000463 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000464 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000465 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000467 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000468 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000469 = dyn_cast<TemplateSpecializationType>(Arg)) {
470 // Perform template argument deduction for the template name.
471 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000472 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000473 Param->getTemplateName(),
474 SpecArg->getTemplateName(),
475 Info, Deduced))
476 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000479 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000480 // argument. Ignore any missing/extra arguments, since they could be
481 // filled in by default arguments.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000482 return DeduceTemplateArguments(S, TemplateParams,
483 Param->getArgs(), Param->getNumArgs(),
Douglas Gregor0972c862010-12-22 18:55:49 +0000484 SpecArg->getArgs(), SpecArg->getNumArgs(),
485 Info, Deduced,
486 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000489 // If the argument type is a class template specialization, we
490 // perform template argument deduction using its template
491 // arguments.
492 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
493 if (!RecordArg)
494 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
496 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000497 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
498 if (!SpecArg)
499 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000501 // Perform template argument deduction for the template name.
502 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000503 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000504 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000505 Param->getTemplateName(),
506 TemplateName(SpecArg->getSpecializedTemplate()),
507 Info, Deduced))
508 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Douglas Gregor20a55e22010-12-22 18:17:10 +0000510 // Perform template argument deduction for the template arguments.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000511 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +0000512 Param->getArgs(), Param->getNumArgs(),
513 SpecArg->getTemplateArgs().data(),
514 SpecArg->getTemplateArgs().size(),
515 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000516}
517
John McCallcd05e812010-08-28 22:14:41 +0000518/// \brief Determines whether the given type is an opaque type that
519/// might be more qualified when instantiated.
520static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
521 switch (T->getTypeClass()) {
522 case Type::TypeOfExpr:
523 case Type::TypeOf:
524 case Type::DependentName:
525 case Type::Decltype:
526 case Type::UnresolvedUsing:
John McCall62c28c82011-01-18 07:41:22 +0000527 case Type::TemplateTypeParm:
John McCallcd05e812010-08-28 22:14:41 +0000528 return true;
529
530 case Type::ConstantArray:
531 case Type::IncompleteArray:
532 case Type::VariableArray:
533 case Type::DependentSizedArray:
534 return IsPossiblyOpaquelyQualifiedType(
535 cast<ArrayType>(T)->getElementType());
536
537 default:
538 return false;
539 }
540}
541
Douglas Gregord3731192011-01-10 07:32:04 +0000542/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000543static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000544getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor603cfb42011-01-05 23:12:31 +0000545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
546 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000547
Douglas Gregor603cfb42011-01-05 23:12:31 +0000548 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
549 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550
Douglas Gregor603cfb42011-01-05 23:12:31 +0000551 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
552 return std::make_pair(TTP->getDepth(), TTP->getIndex());
553}
554
Douglas Gregord3731192011-01-10 07:32:04 +0000555/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000557getDepthAndIndex(UnexpandedParameterPack UPP) {
558 if (const TemplateTypeParmType *TTP
559 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
560 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000561
Douglas Gregord3731192011-01-10 07:32:04 +0000562 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
563}
564
Douglas Gregor603cfb42011-01-05 23:12:31 +0000565/// \brief Helper function to build a TemplateParameter when we don't
566/// know its type statically.
567static TemplateParameter makeTemplateParameter(Decl *D) {
568 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
569 return TemplateParameter(TTP);
570 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
571 return TemplateParameter(NTTP);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000572
Douglas Gregor603cfb42011-01-05 23:12:31 +0000573 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
574}
575
Douglas Gregor54293852011-01-10 17:35:05 +0000576/// \brief Prepare to perform template argument deduction for all of the
577/// arguments in a set of argument packs.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578static void PrepareArgumentPackDeduction(Sema &S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000579 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Bill Wendling4fe5be02012-02-22 09:38:11 +0000580 ArrayRef<unsigned> PackIndices,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000581 SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
582 SmallVectorImpl<
583 SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
Douglas Gregor54293852011-01-10 17:35:05 +0000584 // Save the deduced template arguments for each parameter pack expanded
585 // by this pack expansion, then clear out the deduction.
586 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
587 // Save the previously-deduced argument pack, then clear it out so that we
588 // can deduce a new argument pack.
589 SavedPacks[I] = Deduced[PackIndices[I]];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590 Deduced[PackIndices[I]] = TemplateArgument();
591
Richard Smitha8eaf002012-08-23 06:16:52 +0000592 if (!S.CurrentInstantiationScope)
593 continue;
594
Richard Smith6964b3f2012-09-07 02:06:42 +0000595 // If the template argument pack was explicitly specified, add that to
Douglas Gregor54293852011-01-10 17:35:05 +0000596 // the set of deduced arguments.
597 const TemplateArgument *ExplicitArgs;
598 unsigned NumExplicitArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000599 if (NamedDecl *PartiallySubstitutedPack
Douglas Gregor54293852011-01-10 17:35:05 +0000600 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
601 &ExplicitArgs,
602 &NumExplicitArgs)) {
603 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000604 NewlyDeducedPacks[I].append(ExplicitArgs,
Douglas Gregor54293852011-01-10 17:35:05 +0000605 ExplicitArgs + NumExplicitArgs);
606 }
607 }
608}
609
Douglas Gregor0216f812011-01-10 17:53:52 +0000610/// \brief Finish template argument deduction for a set of argument packs,
611/// producing the argument packs and checking for consistency with prior
612/// deductions.
613static Sema::TemplateDeductionResult
614FinishArgumentPackDeduction(Sema &S,
615 TemplateParameterList *TemplateParams,
616 bool HasAnyArguments,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000617 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Bill Wendling341785e2012-02-22 09:51:33 +0000618 ArrayRef<unsigned> PackIndices,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000619 SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
620 SmallVectorImpl<
621 SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
Douglas Gregor0216f812011-01-10 17:53:52 +0000622 TemplateDeductionInfo &Info) {
623 // Build argument packs for each of the parameter packs expanded by this
624 // pack expansion.
625 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
626 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
627 // We were not able to deduce anything for this parameter pack,
628 // so just restore the saved argument pack.
629 Deduced[PackIndices[I]] = SavedPacks[I];
630 continue;
631 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000632
Douglas Gregor0216f812011-01-10 17:53:52 +0000633 DeducedTemplateArgument NewPack;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000634
Douglas Gregor0216f812011-01-10 17:53:52 +0000635 if (NewlyDeducedPacks[I].empty()) {
636 // If we deduced an empty argument pack, create it now.
Eli Friedmand7a6b162012-09-26 02:36:12 +0000637 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
Douglas Gregor0216f812011-01-10 17:53:52 +0000638 } else {
639 TemplateArgument *ArgumentPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000640 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
Douglas Gregor0216f812011-01-10 17:53:52 +0000641 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
642 ArgumentPack);
643 NewPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000644 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
645 NewlyDeducedPacks[I].size()),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000646 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
Douglas Gregor0216f812011-01-10 17:53:52 +0000647 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000648
Douglas Gregor0216f812011-01-10 17:53:52 +0000649 DeducedTemplateArgument Result
650 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
651 if (Result.isNull()) {
652 Info.Param
653 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
654 Info.FirstArg = SavedPacks[I];
655 Info.SecondArg = NewPack;
656 return Sema::TDK_Inconsistent;
657 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000658
Douglas Gregor0216f812011-01-10 17:53:52 +0000659 Deduced[PackIndices[I]] = Result;
660 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661
Douglas Gregor0216f812011-01-10 17:53:52 +0000662 return Sema::TDK_Success;
663}
664
Douglas Gregor603cfb42011-01-05 23:12:31 +0000665/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000666/// types to the list of argument types, as in the parameter-type-lists of
667/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor603cfb42011-01-05 23:12:31 +0000668///
669/// \param S The semantic analysis object within which we are deducing
670///
671/// \param TemplateParams The template parameters that we are deducing
672///
673/// \param Params The list of parameter types
674///
675/// \param NumParams The number of types in \c Params
676///
677/// \param Args The list of argument types
678///
679/// \param NumArgs The number of types in \c Args
680///
681/// \param Info information about the template argument deduction itself
682///
683/// \param Deduced the deduced template arguments
684///
685/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
686/// how template argument deduction is performed.
687///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000688/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689/// deduction for during partial ordering for a call
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000690/// (C++0x [temp.deduct.partial]).
691///
Douglas Gregorb939a192011-01-21 17:29:42 +0000692/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000693/// in the context of partial ordering, the set of qualifier comparisons.
694///
Douglas Gregor603cfb42011-01-05 23:12:31 +0000695/// \returns the result of template argument deduction so far. Note that a
696/// "success" result means that template argument deduction has not yet failed,
697/// but it may still fail, later, for other reasons.
698static Sema::TemplateDeductionResult
699DeduceTemplateArguments(Sema &S,
700 TemplateParameterList *TemplateParams,
701 const QualType *Params, unsigned NumParams,
702 const QualType *Args, unsigned NumArgs,
703 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000704 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000705 unsigned TDF,
706 bool PartialOrdering = false,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000707 SmallVectorImpl<RefParamPartialOrderingComparison> *
Douglas Gregorb939a192011-01-21 17:29:42 +0000708 RefParamComparisons = 0) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000709 // Fast-path check to see if we have too many/too few arguments.
710 if (NumParams != NumArgs &&
711 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
712 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000713 return Sema::TDK_NonDeducedMismatch;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000714
Douglas Gregor603cfb42011-01-05 23:12:31 +0000715 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716 // Similarly, if P has a form that contains (T), then each parameter type
717 // Pi of the respective parameter-type- list of P is compared with the
718 // corresponding parameter type Ai of the corresponding parameter-type-list
719 // of A. [...]
Douglas Gregor603cfb42011-01-05 23:12:31 +0000720 unsigned ArgIdx = 0, ParamIdx = 0;
721 for (; ParamIdx != NumParams; ++ParamIdx) {
722 // Check argument types.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000723 const PackExpansionType *Expansion
Douglas Gregor603cfb42011-01-05 23:12:31 +0000724 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
725 if (!Expansion) {
726 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000727
Douglas Gregor603cfb42011-01-05 23:12:31 +0000728 // Make sure we have an argument.
729 if (ArgIdx >= NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000730 return Sema::TDK_NonDeducedMismatch;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000731
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000732 if (isa<PackExpansionType>(Args[ArgIdx])) {
733 // C++0x [temp.deduct.type]p22:
734 // If the original function parameter associated with A is a function
735 // parameter pack and the function parameter associated with P is not
736 // a function parameter pack, then template argument deduction fails.
737 return Sema::TDK_NonDeducedMismatch;
738 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000739
Douglas Gregor603cfb42011-01-05 23:12:31 +0000740 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +0000741 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
742 Params[ParamIdx], Args[ArgIdx],
743 Info, Deduced, TDF,
744 PartialOrdering,
745 RefParamComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000746 return Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000747
Douglas Gregor603cfb42011-01-05 23:12:31 +0000748 ++ArgIdx;
749 continue;
750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000751
Douglas Gregor7d5c0c12011-01-11 01:52:23 +0000752 // C++0x [temp.deduct.type]p5:
753 // The non-deduced contexts are:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000754 // - A function parameter pack that does not occur at the end of the
Douglas Gregor7d5c0c12011-01-11 01:52:23 +0000755 // parameter-declaration-clause.
756 if (ParamIdx + 1 < NumParams)
757 return Sema::TDK_Success;
758
Douglas Gregor603cfb42011-01-05 23:12:31 +0000759 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000760 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor603cfb42011-01-05 23:12:31 +0000761 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000762 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor603cfb42011-01-05 23:12:31 +0000763 // comparison deduces template arguments for subsequent positions in the
764 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000765
Douglas Gregor603cfb42011-01-05 23:12:31 +0000766 // Compute the set of template parameter indices that correspond to
767 // parameter packs expanded by the pack expansion.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000768 SmallVector<unsigned, 2> PackIndices;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000769 QualType Pattern = Expansion->getPattern();
770 {
Benjamin Kramer013b3662012-01-30 16:17:39 +0000771 llvm::SmallBitVector SawIndices(TemplateParams->size());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000772 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000773 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
774 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
775 unsigned Depth, Index;
776 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
777 if (Depth == 0 && !SawIndices[Index]) {
778 SawIndices[Index] = true;
779 PackIndices.push_back(Index);
780 }
781 }
782 }
783 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
784
Douglas Gregord3731192011-01-10 07:32:04 +0000785 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000786 // expanded by this pack expansion (the outer index) and for each
Douglas Gregord3731192011-01-10 07:32:04 +0000787 // template argument (the inner SmallVectors).
Chris Lattner5f9e2722011-07-23 10:55:15 +0000788 SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +0000789 NewlyDeducedPacks(PackIndices.size());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000790 SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000791 SavedPacks(PackIndices.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000792 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
Douglas Gregor54293852011-01-10 17:35:05 +0000793 NewlyDeducedPacks);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000794
Douglas Gregor603cfb42011-01-05 23:12:31 +0000795 bool HasAnyArguments = false;
796 for (; ArgIdx < NumArgs; ++ArgIdx) {
797 HasAnyArguments = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000798
Douglas Gregor603cfb42011-01-05 23:12:31 +0000799 // Deduce template arguments from the pattern.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000800 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +0000801 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
802 Args[ArgIdx], Info, Deduced,
803 TDF, PartialOrdering,
804 RefParamComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000805 return Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000806
Douglas Gregor603cfb42011-01-05 23:12:31 +0000807 // Capture the deduced template arguments for each parameter pack expanded
808 // by this pack expansion, add them to the list of arguments we've deduced
809 // for that pack, then clear out the deduced argument.
810 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
811 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
812 if (!DeducedArg.isNull()) {
813 NewlyDeducedPacks[I].push_back(DeducedArg);
814 DeducedArg = DeducedTemplateArgument();
815 }
816 }
817 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000818
Douglas Gregor603cfb42011-01-05 23:12:31 +0000819 // Build argument packs for each of the parameter packs expanded by this
820 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +0000821 if (Sema::TemplateDeductionResult Result
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000822 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
Douglas Gregor0216f812011-01-10 17:53:52 +0000823 Deduced, PackIndices, SavedPacks,
824 NewlyDeducedPacks, Info))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000825 return Result;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000826 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000827
Douglas Gregor603cfb42011-01-05 23:12:31 +0000828 // Make sure we don't have any extra arguments.
829 if (ArgIdx < NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000830 return Sema::TDK_NonDeducedMismatch;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000831
Douglas Gregor603cfb42011-01-05 23:12:31 +0000832 return Sema::TDK_Success;
833}
834
Douglas Gregor61d0b6b2011-04-28 00:56:09 +0000835/// \brief Determine whether the parameter has qualifiers that are either
836/// inconsistent with or a superset of the argument's qualifiers.
837static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
838 QualType ArgType) {
839 Qualifiers ParamQs = ParamType.getQualifiers();
840 Qualifiers ArgQs = ArgType.getQualifiers();
841
842 if (ParamQs == ArgQs)
843 return false;
844
845 // Mismatched (but not missing) Objective-C GC attributes.
846 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
847 ParamQs.hasObjCGCAttr())
848 return true;
849
850 // Mismatched (but not missing) address spaces.
851 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
852 ParamQs.hasAddressSpace())
853 return true;
854
John McCallf85e1932011-06-15 23:02:42 +0000855 // Mismatched (but not missing) Objective-C lifetime qualifiers.
856 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
857 ParamQs.hasObjCLifetime())
858 return true;
859
Douglas Gregor61d0b6b2011-04-28 00:56:09 +0000860 // CVR qualifier superset.
861 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
862 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
863 == ParamQs.getCVRQualifiers());
864}
865
Douglas Gregor500d3312009-06-26 18:27:22 +0000866/// \brief Deduce the template arguments by comparing the parameter type and
867/// the argument type (C++ [temp.deduct.type]).
868///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000869/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000870///
871/// \param TemplateParams the template parameters that we are deducing
872///
873/// \param ParamIn the parameter type
874///
875/// \param ArgIn the argument type
876///
877/// \param Info information about the template argument deduction itself
878///
879/// \param Deduced the deduced template arguments
880///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000881/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000882/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000883///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000884/// \param PartialOrdering Whether we're performing template argument deduction
885/// in the context of partial ordering (C++0x [temp.deduct.partial]).
886///
Douglas Gregorb939a192011-01-21 17:29:42 +0000887/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000888/// in the context of partial ordering, the set of qualifier comparisons.
889///
Douglas Gregor500d3312009-06-26 18:27:22 +0000890/// \returns the result of template argument deduction so far. Note that a
891/// "success" result means that template argument deduction has not yet failed,
892/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000893static Sema::TemplateDeductionResult
Sebastian Redlbb95e512012-01-17 22:49:52 +0000894DeduceTemplateArgumentsByTypeMatch(Sema &S,
895 TemplateParameterList *TemplateParams,
896 QualType ParamIn, QualType ArgIn,
897 TemplateDeductionInfo &Info,
898 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
899 unsigned TDF,
900 bool PartialOrdering,
901 SmallVectorImpl<RefParamPartialOrderingComparison> *
902 RefParamComparisons) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000903 // We only want to look at the canonical types, since typedefs and
904 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000905 QualType Param = S.Context.getCanonicalType(ParamIn);
906 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000907
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000908 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000909 // This isn't explicitly called out
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000910 if (const PackExpansionType *ArgExpansion
911 = dyn_cast<PackExpansionType>(Arg))
912 Arg = ArgExpansion->getPattern();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000913
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000914 if (PartialOrdering) {
915 // C++0x [temp.deduct.partial]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000916 // Before the partial ordering is done, certain transformations are
917 // performed on the types used for partial ordering:
918 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000919 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
920 if (ParamRef)
921 Param = ParamRef->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000922
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000923 // - If A is a reference type, A is replaced by the type referred to.
924 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
925 if (ArgRef)
926 Arg = ArgRef->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000927
Douglas Gregorb939a192011-01-21 17:29:42 +0000928 if (RefParamComparisons && ParamRef && ArgRef) {
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000929 // C++0x [temp.deduct.partial]p6:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000930 // If both P and A were reference types (before being replaced with the
931 // type referred to above), determine which of the two types (if any) is
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000932 // more cv-qualified than the other; otherwise the types are considered
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933 // to be equally cv-qualified for partial ordering purposes. The result
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000934 // of this determination will be used below.
935 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000936 // We save this information for later, using it only when deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000937 // succeeds in both directions.
Douglas Gregorb939a192011-01-21 17:29:42 +0000938 RefParamPartialOrderingComparison Comparison;
939 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
940 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
941 Comparison.Qualifiers = NeitherMoreQualified;
Douglas Gregor769d0cc2011-04-30 17:07:52 +0000942
943 Qualifiers ParamQuals = Param.getQualifiers();
944 Qualifiers ArgQuals = Arg.getQualifiers();
945 if (ParamQuals.isStrictSupersetOf(ArgQuals))
Douglas Gregorb939a192011-01-21 17:29:42 +0000946 Comparison.Qualifiers = ParamMoreQualified;
Douglas Gregor769d0cc2011-04-30 17:07:52 +0000947 else if (ArgQuals.isStrictSupersetOf(ParamQuals))
Douglas Gregorb939a192011-01-21 17:29:42 +0000948 Comparison.Qualifiers = ArgMoreQualified;
949 RefParamComparisons->push_back(Comparison);
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000950 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000951
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000952 // C++0x [temp.deduct.partial]p7:
953 // Remove any top-level cv-qualifiers:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000954 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000955 // version of P.
956 Param = Param.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000957 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000958 // version of A.
959 Arg = Arg.getUnqualifiedType();
960 } else {
961 // C++0x [temp.deduct.call]p4 bullet 1:
962 // - If the original P is a reference type, the deduced A (i.e., the type
963 // referred to by the reference) can be more cv-qualified than the
964 // transformed A.
965 if (TDF & TDF_ParamWithReferenceType) {
966 Qualifiers Quals;
967 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
968 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall62c28c82011-01-18 07:41:22 +0000969 Arg.getCVRQualifiers());
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000970 Param = S.Context.getQualifiedType(UnqualParam, Quals);
971 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000972
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000973 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
974 // C++0x [temp.deduct.type]p10:
975 // If P and A are function types that originated from deduction when
976 // taking the address of a function template (14.8.2.2) or when deducing
977 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000978 // Ai are parameters of the top-level parameter-type-list of P and A,
979 // respectively, Pi is adjusted if it is an rvalue reference to a
980 // cv-unqualified template parameter and Ai is an lvalue reference, in
981 // which case the type of Pi is changed to be the template parameter
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000982 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
983 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi00995302011-01-27 07:09:49 +0000984 // deduced as X&. - end note ]
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000985 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000986
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000987 if (const RValueReferenceType *ParamRef
988 = Param->getAs<RValueReferenceType>()) {
989 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
990 !ParamRef->getPointeeType().getQualifiers())
991 if (Arg->isLValueReferenceType())
992 Param = ParamRef->getPointeeType();
993 }
994 }
Douglas Gregor500d3312009-06-26 18:27:22 +0000995 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000996
Douglas Gregor199d9912009-06-05 00:53:49 +0000997 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000998 // A template type argument T, a template template argument TT or a
999 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +00001000 // the following forms:
1001 //
1002 // T
1003 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +00001004 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +00001005 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregoraf1308232011-09-22 15:57:07 +00001006 // Just skip any attempts to deduce from a placeholder type.
1007 if (Arg->isPlaceholderType())
1008 return Sema::TDK_Success;
1009
Douglas Gregorf67875d2009-06-12 18:26:56 +00001010 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +00001011 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Douglas Gregor9e9fae42009-07-22 20:02:25 +00001013 // If the argument type is an array type, move the qualifiers up to the
1014 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregorf290e0d2009-07-22 21:30:48 +00001015 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +00001016 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001017 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +00001018 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001019 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +00001020 RecanonicalizeArg = true;
1021 }
1022 }
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001024 // The argument type can not be less qualified than the parameter
1025 // type.
Douglas Gregor61d0b6b2011-04-28 00:56:09 +00001026 if (!(TDF & TDF_IgnoreQualifiers) &&
1027 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +00001028 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +00001029 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +00001030 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +00001031 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +00001032 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001033
1034 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001035 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +00001036 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +00001037
Douglas Gregor61d0b6b2011-04-28 00:56:09 +00001038 // Remove any qualifiers on the parameter from the deduced type.
1039 // We checked the qualifiers for consistency above.
1040 Qualifiers DeducedQs = DeducedType.getQualifiers();
1041 Qualifiers ParamQs = Param.getQualifiers();
1042 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1043 if (ParamQs.hasObjCGCAttr())
1044 DeducedQs.removeObjCGCAttr();
1045 if (ParamQs.hasAddressSpace())
1046 DeducedQs.removeAddressSpace();
John McCallf85e1932011-06-15 23:02:42 +00001047 if (ParamQs.hasObjCLifetime())
1048 DeducedQs.removeObjCLifetime();
Douglas Gregore559ca12011-06-17 22:11:49 +00001049
1050 // Objective-C ARC:
Douglas Gregorda8b2492011-07-26 14:53:44 +00001051 // If template deduction would produce a lifetime qualifier on a type
1052 // that is not a lifetime type, template argument deduction fails.
1053 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1054 !DeducedType->isDependentType()) {
1055 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1056 Info.FirstArg = TemplateArgument(Param);
1057 Info.SecondArg = TemplateArgument(Arg);
1058 return Sema::TDK_Underqualified;
1059 }
1060
1061 // Objective-C ARC:
Douglas Gregore559ca12011-06-17 22:11:49 +00001062 // If template deduction would produce an argument type with lifetime type
1063 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikie4e4d0842012-03-11 07:00:24 +00001064 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore559ca12011-06-17 22:11:49 +00001065 DeducedType->isObjCLifetimeType() &&
1066 !DeducedQs.hasObjCLifetime())
1067 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1068
Douglas Gregor61d0b6b2011-04-28 00:56:09 +00001069 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1070 DeducedQs);
1071
Douglas Gregorf290e0d2009-07-22 21:30:48 +00001072 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001073 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001075 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001076 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001077 Deduced[Index],
1078 NewDeduced);
1079 if (Result.isNull()) {
1080 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1081 Info.FirstArg = Deduced[Index];
1082 Info.SecondArg = NewDeduced;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001083 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001084 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001086 Deduced[Index] = Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001087 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001088 }
1089
Douglas Gregorf67875d2009-06-12 18:26:56 +00001090 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +00001091 Info.FirstArg = TemplateArgument(ParamIn);
1092 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001093
Douglas Gregor0bc15d92011-01-14 05:11:40 +00001094 // If the parameter is an already-substituted template parameter
1095 // pack, do nothing: we don't know which of its arguments to look
1096 // at, so we have to wait until all of the parameter packs in this
1097 // expansion have arguments.
1098 if (isa<SubstTemplateTypeParmPackType>(Param))
1099 return Sema::TDK_Success;
1100
Douglas Gregor508f1c82009-06-26 23:10:12 +00001101 // Check the cv-qualifiers on the parameter and argument types.
1102 if (!(TDF & TDF_IgnoreQualifiers)) {
1103 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor61d0b6b2011-04-28 00:56:09 +00001104 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregor508f1c82009-06-26 23:10:12 +00001105 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +00001106 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +00001107 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +00001108 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +00001109 }
Douglas Gregorfc55a822012-03-11 03:29:50 +00001110
1111 // If the parameter type is not dependent, there is nothing to deduce.
1112 if (!Param->isDependentType()) {
1113 if (!(TDF & TDF_SkipNonDependent) && Param != Arg)
1114 return Sema::TDK_NonDeducedMismatch;
1115
1116 return Sema::TDK_Success;
1117 }
1118 } else if (!Param->isDependentType() &&
1119 Param.getUnqualifiedType() == Arg.getUnqualifiedType()) {
1120 return Sema::TDK_Success;
Douglas Gregor508f1c82009-06-26 23:10:12 +00001121 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001122
Douglas Gregord560d502009-06-04 00:21:18 +00001123 switch (Param->getTypeClass()) {
Douglas Gregor4ac01402011-06-15 16:02:29 +00001124 // Non-canonical types cannot appear here.
1125#define NON_CANONICAL_TYPE(Class, Base) \
1126 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1127#define TYPE(Class, Base)
1128#include "clang/AST/TypeNodes.def"
1129
1130 case Type::TemplateTypeParm:
1131 case Type::SubstTemplateTypeParmPack:
1132 llvm_unreachable("Type nodes handled above");
Douglas Gregorfc55a822012-03-11 03:29:50 +00001133
1134 // These types cannot be dependent, so simply check whether the types are
1135 // the same.
Douglas Gregor199d9912009-06-05 00:53:49 +00001136 case Type::Builtin:
Douglas Gregor4ac01402011-06-15 16:02:29 +00001137 case Type::VariableArray:
1138 case Type::Vector:
1139 case Type::FunctionNoProto:
1140 case Type::Record:
1141 case Type::Enum:
1142 case Type::ObjCObject:
1143 case Type::ObjCInterface:
Douglas Gregorfc55a822012-03-11 03:29:50 +00001144 case Type::ObjCObjectPointer: {
1145 if (TDF & TDF_SkipNonDependent)
1146 return Sema::TDK_Success;
1147
1148 if (TDF & TDF_IgnoreQualifiers) {
1149 Param = Param.getUnqualifiedType();
1150 Arg = Arg.getUnqualifiedType();
1151 }
1152
1153 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1154 }
1155
Douglas Gregor4ac01402011-06-15 16:02:29 +00001156 // _Complex T [placeholder extension]
1157 case Type::Complex:
1158 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlbb95e512012-01-17 22:49:52 +00001159 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor4ac01402011-06-15 16:02:29 +00001160 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlbb95e512012-01-17 22:49:52 +00001161 ComplexArg->getElementType(),
1162 Info, Deduced, TDF);
Douglas Gregor4ac01402011-06-15 16:02:29 +00001163
1164 return Sema::TDK_NonDeducedMismatch;
Eli Friedmanb001de72011-10-06 23:00:33 +00001165
1166 // _Atomic T [extension]
1167 case Type::Atomic:
1168 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlbb95e512012-01-17 22:49:52 +00001169 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedmanb001de72011-10-06 23:00:33 +00001170 cast<AtomicType>(Param)->getValueType(),
1171 AtomicArg->getValueType(),
1172 Info, Deduced, TDF);
1173
1174 return Sema::TDK_NonDeducedMismatch;
1175
Douglas Gregor199d9912009-06-05 00:53:49 +00001176 // T *
Douglas Gregord560d502009-06-04 00:21:18 +00001177 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +00001178 QualType PointeeType;
1179 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1180 PointeeType = PointerArg->getPointeeType();
1181 } else if (const ObjCObjectPointerType *PointerArg
1182 = Arg->getAs<ObjCObjectPointerType>()) {
1183 PointeeType = PointerArg->getPointeeType();
1184 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +00001185 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +00001186 }
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Douglas Gregor41128772009-06-26 23:27:24 +00001188 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlbb95e512012-01-17 22:49:52 +00001189 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1190 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +00001191 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +00001192 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +00001193 }
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Douglas Gregor199d9912009-06-05 00:53:49 +00001195 // T &
Douglas Gregord560d502009-06-04 00:21:18 +00001196 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +00001197 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +00001198 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001199 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Sebastian Redlbb95e512012-01-17 22:49:52 +00001201 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001202 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlbb95e512012-01-17 22:49:52 +00001203 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001204 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001205
Douglas Gregor199d9912009-06-05 00:53:49 +00001206 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +00001207 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +00001208 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +00001209 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001210 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Sebastian Redlbb95e512012-01-17 22:49:52 +00001212 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1213 cast<RValueReferenceType>(Param)->getPointeeType(),
1214 ReferenceArg->getPointeeType(),
1215 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001216 }
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Douglas Gregor199d9912009-06-05 00:53:49 +00001218 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001219 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001220 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001221 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001222 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001223 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001224
John McCalle4f26e52010-08-19 00:20:19 +00001225 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlbb95e512012-01-17 22:49:52 +00001226 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1227 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1228 IncompleteArrayArg->getElementType(),
1229 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001230 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001231
1232 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001233 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001234 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001235 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001236 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001237 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001238
1239 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001240 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001241 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001242 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001243
John McCalle4f26e52010-08-19 00:20:19 +00001244 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlbb95e512012-01-17 22:49:52 +00001245 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1246 ConstantArrayParm->getElementType(),
1247 ConstantArrayArg->getElementType(),
1248 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001249 }
1250
Douglas Gregor199d9912009-06-05 00:53:49 +00001251 // type [i]
1252 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001253 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +00001254 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001255 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001256
John McCalle4f26e52010-08-19 00:20:19 +00001257 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1258
Douglas Gregor199d9912009-06-05 00:53:49 +00001259 // Check the element type of the arrays
1260 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001261 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001262 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001263 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1264 DependentArrayParm->getElementType(),
1265 ArrayArg->getElementType(),
1266 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001267 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Douglas Gregor199d9912009-06-05 00:53:49 +00001269 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +00001270 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001271 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1272 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001273 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +00001274
1275 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +00001276 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001277 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +00001278 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +00001279 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +00001280 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1281 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001282 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001283 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001284 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001285 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +00001286 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001287 if (const DependentSizedArrayType *DependentArrayArg
1288 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +00001289 if (DependentArrayArg->getSizeExpr())
1290 return DeduceNonTypeTemplateArgument(S, NTTP,
1291 DependentArrayArg->getSizeExpr(),
1292 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Douglas Gregor199d9912009-06-05 00:53:49 +00001294 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +00001295 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001296 }
Mike Stump1eb44332009-09-09 15:08:12 +00001297
1298 // type(*)(T)
1299 // T(*)()
1300 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +00001301 case Type::FunctionProto: {
Douglas Gregor73b3cf62011-01-25 17:19:08 +00001302 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump1eb44332009-09-09 15:08:12 +00001303 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +00001304 dyn_cast<FunctionProtoType>(Arg);
1305 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001306 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001307
1308 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +00001309 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001310
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001311 if (FunctionProtoParam->getTypeQuals()
Douglas Gregore3c7a7c2011-01-26 16:50:54 +00001312 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001313 FunctionProtoParam->getRefQualifier()
Douglas Gregore3c7a7c2011-01-26 16:50:54 +00001314 != FunctionProtoArg->getRefQualifier() ||
1315 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001316 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001317
Anders Carlssona27fad52009-06-08 15:19:08 +00001318 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001319 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001320 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1321 FunctionProtoParam->getResultType(),
1322 FunctionProtoArg->getResultType(),
1323 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001324 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Douglas Gregor603cfb42011-01-05 23:12:31 +00001326 return DeduceTemplateArguments(S, TemplateParams,
1327 FunctionProtoParam->arg_type_begin(),
1328 FunctionProtoParam->getNumArgs(),
1329 FunctionProtoArg->arg_type_begin(),
1330 FunctionProtoArg->getNumArgs(),
Douglas Gregor73b3cf62011-01-25 17:19:08 +00001331 Info, Deduced, SubTDF);
Anders Carlssona27fad52009-06-08 15:19:08 +00001332 }
Mike Stump1eb44332009-09-09 15:08:12 +00001333
John McCall3cb0ebd2010-03-10 03:28:59 +00001334 case Type::InjectedClassName: {
1335 // Treat a template's injected-class-name as if the template
1336 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001337 Param = cast<InjectedClassNameType>(Param)
1338 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001339 assert(isa<TemplateSpecializationType>(Param) &&
1340 "injected class name is not a template specialization type");
1341 // fall through
1342 }
1343
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001344 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001345 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001346 // TT<T>
1347 // TT<i>
1348 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001349 case Type::TemplateSpecialization: {
1350 const TemplateSpecializationType *SpecParam
1351 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001353 // Try to deduce template arguments from the template-id.
1354 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001355 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001356 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001358 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001359 // C++ [temp.deduct.call]p3b3:
1360 // If P is a class, and P has the form template-id, then A can be a
1361 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001362 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001363 // class pointed to by the deduced A.
1364 //
1365 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001366 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001367 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001368 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1369 // We cannot inspect base classes as part of deduction when the type
1370 // is incomplete, so either instantiate any templates necessary to
1371 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001372 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001373 return Result;
1374
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001375 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001376 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001377 // ToVisit is our stack of records that we still need to visit.
1378 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001379 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001380 ToVisit.push_back(RecordT);
1381 bool Successful = false;
Benjamin Kramer74fe6612012-01-20 16:39:18 +00001382 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1383 Deduced.end());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001384 while (!ToVisit.empty()) {
1385 // Retrieve the next class in the inheritance hierarchy.
1386 const RecordType *NextT = ToVisit.back();
1387 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001389 // If we have already seen this type, skip it.
1390 if (!Visited.insert(NextT))
1391 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001393 // If this is a base class, try to perform template argument
1394 // deduction from it.
1395 if (NextT != RecordT) {
1396 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001397 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001398 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001400 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001401 // note that we had some success. Otherwise, ignore any deductions
1402 // from this base class.
1403 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001404 Successful = true;
Benjamin Kramer74fe6612012-01-20 16:39:18 +00001405 DeducedOrig.clear();
1406 DeducedOrig.append(Deduced.begin(), Deduced.end());
Douglas Gregor053105d2010-11-02 00:02:34 +00001407 }
1408 else
1409 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001410 }
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001412 // Visit base classes
1413 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1414 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1415 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001416 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001417 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001418 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001419 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001420 }
1421 }
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001423 if (Successful)
1424 return Sema::TDK_Success;
1425 }
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001427 }
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001429 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001430 }
1431
Douglas Gregor637a4092009-06-10 23:47:09 +00001432 // T type::*
1433 // T T::*
1434 // T (type::*)()
1435 // type (T::*)()
1436 // type (type::*)(T)
1437 // type (T::*)(T)
1438 // T (type::*)(T)
1439 // T (T::*)()
1440 // T (T::*)(T)
1441 case Type::MemberPointer: {
1442 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1443 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1444 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001445 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001446
Douglas Gregorf67875d2009-06-12 18:26:56 +00001447 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001448 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1449 MemPtrParam->getPointeeType(),
1450 MemPtrArg->getPointeeType(),
1451 Info, Deduced,
1452 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001453 return Result;
1454
Sebastian Redlbb95e512012-01-17 22:49:52 +00001455 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1456 QualType(MemPtrParam->getClass(), 0),
1457 QualType(MemPtrArg->getClass(), 0),
Douglas Gregorfc55a822012-03-11 03:29:50 +00001458 Info, Deduced,
1459 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637a4092009-06-10 23:47:09 +00001460 }
1461
Anders Carlsson9a917e42009-06-12 22:56:54 +00001462 // (clang extension)
1463 //
Mike Stump1eb44332009-09-09 15:08:12 +00001464 // type(^)(T)
1465 // T(^)()
1466 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001467 case Type::BlockPointer: {
1468 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1469 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Anders Carlsson859ba502009-06-12 16:23:10 +00001471 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001472 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Sebastian Redlbb95e512012-01-17 22:49:52 +00001474 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1475 BlockPtrParam->getPointeeType(),
1476 BlockPtrArg->getPointeeType(),
1477 Info, Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001478 }
1479
Douglas Gregor4ac01402011-06-15 16:02:29 +00001480 // (clang extension)
1481 //
1482 // T __attribute__(((ext_vector_type(<integral constant>))))
1483 case Type::ExtVector: {
1484 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1485 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1486 // Make sure that the vectors have the same number of elements.
1487 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1488 return Sema::TDK_NonDeducedMismatch;
1489
1490 // Perform deduction on the element types.
Sebastian Redlbb95e512012-01-17 22:49:52 +00001491 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1492 VectorParam->getElementType(),
1493 VectorArg->getElementType(),
1494 Info, Deduced, TDF);
Douglas Gregor4ac01402011-06-15 16:02:29 +00001495 }
1496
1497 if (const DependentSizedExtVectorType *VectorArg
1498 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1499 // We can't check the number of elements, since the argument has a
1500 // dependent number of elements. This can only occur during partial
1501 // ordering.
1502
1503 // Perform deduction on the element types.
Sebastian Redlbb95e512012-01-17 22:49:52 +00001504 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1505 VectorParam->getElementType(),
1506 VectorArg->getElementType(),
1507 Info, Deduced, TDF);
Douglas Gregor4ac01402011-06-15 16:02:29 +00001508 }
1509
1510 return Sema::TDK_NonDeducedMismatch;
1511 }
1512
1513 // (clang extension)
1514 //
1515 // T __attribute__(((ext_vector_type(N))))
1516 case Type::DependentSizedExtVector: {
1517 const DependentSizedExtVectorType *VectorParam
1518 = cast<DependentSizedExtVectorType>(Param);
1519
1520 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1521 // Perform deduction on the element types.
1522 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001523 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1524 VectorParam->getElementType(),
1525 VectorArg->getElementType(),
1526 Info, Deduced, TDF))
Douglas Gregor4ac01402011-06-15 16:02:29 +00001527 return Result;
1528
1529 // Perform deduction on the vector size, if we can.
1530 NonTypeTemplateParmDecl *NTTP
1531 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1532 if (!NTTP)
1533 return Sema::TDK_Success;
1534
1535 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1536 ArgSize = VectorArg->getNumElements();
1537 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1538 false, Info, Deduced);
1539 }
1540
1541 if (const DependentSizedExtVectorType *VectorArg
1542 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1543 // Perform deduction on the element types.
1544 if (Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00001545 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1546 VectorParam->getElementType(),
1547 VectorArg->getElementType(),
1548 Info, Deduced, TDF))
Douglas Gregor4ac01402011-06-15 16:02:29 +00001549 return Result;
1550
1551 // Perform deduction on the vector size, if we can.
1552 NonTypeTemplateParmDecl *NTTP
1553 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1554 if (!NTTP)
1555 return Sema::TDK_Success;
1556
1557 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1558 Info, Deduced);
1559 }
1560
1561 return Sema::TDK_NonDeducedMismatch;
1562 }
1563
Douglas Gregor637a4092009-06-10 23:47:09 +00001564 case Type::TypeOfExpr:
1565 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001566 case Type::DependentName:
Douglas Gregor4ac01402011-06-15 16:02:29 +00001567 case Type::UnresolvedUsing:
1568 case Type::Decltype:
1569 case Type::UnaryTransform:
1570 case Type::Auto:
1571 case Type::DependentTemplateSpecialization:
1572 case Type::PackExpansion:
Douglas Gregor637a4092009-06-10 23:47:09 +00001573 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001574 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001575 }
1576
David Blaikie30263482012-01-20 21:50:17 +00001577 llvm_unreachable("Invalid Type Class!");
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001578}
1579
Douglas Gregorf67875d2009-06-12 18:26:56 +00001580static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001581DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001582 TemplateParameterList *TemplateParams,
1583 const TemplateArgument &Param,
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001584 TemplateArgument Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001585 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001586 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001587 // If the template argument is a pack expansion, perform template argument
1588 // deduction against the pattern of that expansion. This only occurs during
1589 // partial ordering.
1590 if (Arg.isPackExpansion())
1591 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001592
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001593 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001594 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00001595 llvm_unreachable("Null template argument in parameter list");
Mike Stump1eb44332009-09-09 15:08:12 +00001596
1597 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001598 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlbb95e512012-01-17 22:49:52 +00001599 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1600 Param.getAsType(),
1601 Arg.getAsType(),
1602 Info, Deduced, 0);
Douglas Gregor788cd062009-11-11 01:00:40 +00001603 Info.FirstArg = Param;
1604 Info.SecondArg = Arg;
1605 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001606
Douglas Gregor788cd062009-11-11 01:00:40 +00001607 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001608 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001609 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001610 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001611 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001612 Info.FirstArg = Param;
1613 Info.SecondArg = Arg;
1614 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001615
1616 case TemplateArgument::TemplateExpansion:
1617 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001618
Douglas Gregor199d9912009-06-05 00:53:49 +00001619 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001620 if (Arg.getKind() == TemplateArgument::Declaration &&
Eli Friedmand7a6b162012-09-26 02:36:12 +00001621 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()) &&
1622 Param.isDeclForReferenceParam() == Arg.isDeclForReferenceParam())
1623 return Sema::TDK_Success;
1624
1625 Info.FirstArg = Param;
1626 Info.SecondArg = Arg;
1627 return Sema::TDK_NonDeducedMismatch;
1628
1629 case TemplateArgument::NullPtr:
1630 if (Arg.getKind() == TemplateArgument::NullPtr &&
1631 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor788cd062009-11-11 01:00:40 +00001632 return Sema::TDK_Success;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633
Douglas Gregorf67875d2009-06-12 18:26:56 +00001634 Info.FirstArg = Param;
1635 Info.SecondArg = Arg;
1636 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor199d9912009-06-05 00:53:49 +00001638 case TemplateArgument::Integral:
1639 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer85524372012-06-07 15:09:51 +00001640 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001641 return Sema::TDK_Success;
1642
1643 Info.FirstArg = Param;
1644 Info.SecondArg = Arg;
1645 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001646 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001647
1648 if (Arg.getKind() == TemplateArgument::Expression) {
1649 Info.FirstArg = Param;
1650 Info.SecondArg = Arg;
1651 return Sema::TDK_NonDeducedMismatch;
1652 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001653
Douglas Gregorf67875d2009-06-12 18:26:56 +00001654 Info.FirstArg = Param;
1655 Info.SecondArg = Arg;
1656 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Douglas Gregor199d9912009-06-05 00:53:49 +00001658 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001659 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001660 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1661 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001662 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer85524372012-06-07 15:09:51 +00001663 Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001664 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001665 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001666 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001667 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001668 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001669 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001670 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001671 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001672 Info, Deduced);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001673
Douglas Gregorf67875d2009-06-12 18:26:56 +00001674 Info.FirstArg = Param;
1675 Info.SecondArg = Arg;
1676 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001677 }
Mike Stump1eb44332009-09-09 15:08:12 +00001678
Douglas Gregor199d9912009-06-05 00:53:49 +00001679 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001680 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001681 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001682 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001683 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001684 }
Mike Stump1eb44332009-09-09 15:08:12 +00001685
David Blaikie30263482012-01-20 21:50:17 +00001686 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001687}
1688
Douglas Gregor20a55e22010-12-22 18:17:10 +00001689/// \brief Determine whether there is a template argument to be used for
1690/// deduction.
1691///
1692/// This routine "expands" argument packs in-place, overriding its input
1693/// parameters so that \c Args[ArgIdx] will be the available template argument.
1694///
1695/// \returns true if there is another template argument (which will be at
1696/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001697static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor20a55e22010-12-22 18:17:10 +00001698 unsigned &ArgIdx,
1699 unsigned &NumArgs) {
1700 if (ArgIdx == NumArgs)
1701 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001702
Douglas Gregor20a55e22010-12-22 18:17:10 +00001703 const TemplateArgument &Arg = Args[ArgIdx];
1704 if (Arg.getKind() != TemplateArgument::Pack)
1705 return true;
1706
1707 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1708 Args = Arg.pack_begin();
1709 NumArgs = Arg.pack_size();
1710 ArgIdx = 0;
1711 return ArgIdx < NumArgs;
1712}
1713
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001714/// \brief Determine whether the given set of template arguments has a pack
1715/// expansion that is not the last template argument.
1716static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1717 unsigned NumArgs) {
1718 unsigned ArgIdx = 0;
1719 while (ArgIdx < NumArgs) {
1720 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001721
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001722 // Unwrap argument packs.
1723 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1724 Args = Arg.pack_begin();
1725 NumArgs = Arg.pack_size();
1726 ArgIdx = 0;
1727 continue;
1728 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001729
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001730 ++ArgIdx;
1731 if (ArgIdx == NumArgs)
1732 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001733
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001734 if (Arg.isPackExpansion())
1735 return true;
1736 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001737
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001738 return false;
1739}
1740
Douglas Gregor20a55e22010-12-22 18:17:10 +00001741static Sema::TemplateDeductionResult
1742DeduceTemplateArguments(Sema &S,
1743 TemplateParameterList *TemplateParams,
1744 const TemplateArgument *Params, unsigned NumParams,
1745 const TemplateArgument *Args, unsigned NumArgs,
1746 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001747 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor0972c862010-12-22 18:55:49 +00001748 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001749 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001750 // If the template argument list of P contains a pack expansion that is not
1751 // the last template argument, the entire template argument list is a
Douglas Gregore02e2622010-12-22 21:19:48 +00001752 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001753 if (hasPackExpansionBeforeEnd(Params, NumParams))
1754 return Sema::TDK_Success;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001755
Douglas Gregore02e2622010-12-22 21:19:48 +00001756 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001757 // If P has a form that contains <T> or <i>, then each argument Pi of the
1758 // respective template argument list P is compared with the corresponding
Douglas Gregore02e2622010-12-22 21:19:48 +00001759 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001760 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001761 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor20a55e22010-12-22 18:17:10 +00001762 ++ParamIdx) {
1763 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001764 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001765
Douglas Gregor20a55e22010-12-22 18:17:10 +00001766 // Check whether we have enough arguments.
1767 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001768 return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
Douglas Gregor0972c862010-12-22 18:55:49 +00001769 : Sema::TDK_Success;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001770
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001771 if (Args[ArgIdx].isPackExpansion()) {
1772 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1773 // but applied to pack expansions that are template arguments.
1774 return Sema::TDK_NonDeducedMismatch;
1775 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001776
Douglas Gregore02e2622010-12-22 21:19:48 +00001777 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001778 if (Sema::TemplateDeductionResult Result
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001779 = DeduceTemplateArguments(S, TemplateParams,
1780 Params[ParamIdx], Args[ArgIdx],
1781 Info, Deduced))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782 return Result;
1783
Douglas Gregor20a55e22010-12-22 18:17:10 +00001784 // Move to the next argument.
1785 ++ArgIdx;
1786 continue;
1787 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001788
Douglas Gregore02e2622010-12-22 21:19:48 +00001789 // The parameter is a pack expansion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001790
Douglas Gregore02e2622010-12-22 21:19:48 +00001791 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001792 // If Pi is a pack expansion, then the pattern of Pi is compared with
1793 // each remaining argument in the template argument list of A. Each
1794 // comparison deduces template arguments for subsequent positions in the
Douglas Gregore02e2622010-12-22 21:19:48 +00001795 // template parameter packs expanded by Pi.
1796 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001797
Douglas Gregore02e2622010-12-22 21:19:48 +00001798 // Compute the set of template parameter indices that correspond to
1799 // parameter packs expanded by the pack expansion.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001800 SmallVector<unsigned, 2> PackIndices;
Douglas Gregore02e2622010-12-22 21:19:48 +00001801 {
Benjamin Kramer013b3662012-01-30 16:17:39 +00001802 llvm::SmallBitVector SawIndices(TemplateParams->size());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001803 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregore02e2622010-12-22 21:19:48 +00001804 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1805 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1806 unsigned Depth, Index;
1807 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1808 if (Depth == 0 && !SawIndices[Index]) {
1809 SawIndices[Index] = true;
1810 PackIndices.push_back(Index);
1811 }
1812 }
1813 }
1814 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001815
Douglas Gregore02e2622010-12-22 21:19:48 +00001816 // FIXME: If there are no remaining arguments, we can bail out early
1817 // and set any deduced parameter packs to an empty argument pack.
1818 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001819
Douglas Gregore02e2622010-12-22 21:19:48 +00001820 // Save the deduced template arguments for each parameter pack expanded
1821 // by this pack expansion, then clear out the deduction.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001822 SmallVector<DeducedTemplateArgument, 2>
Douglas Gregore02e2622010-12-22 21:19:48 +00001823 SavedPacks(PackIndices.size());
Chris Lattner5f9e2722011-07-23 10:55:15 +00001824 SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregor54293852011-01-10 17:35:05 +00001825 NewlyDeducedPacks(PackIndices.size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001826 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
Douglas Gregor54293852011-01-10 17:35:05 +00001827 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001828
1829 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001830 // expanded by this pack expansion (the outer index) and for each
Douglas Gregore02e2622010-12-22 21:19:48 +00001831 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001832 bool HasAnyArguments = false;
1833 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1834 HasAnyArguments = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001835
Douglas Gregore02e2622010-12-22 21:19:48 +00001836 // Deduce template arguments from the pattern.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001837 if (Sema::TemplateDeductionResult Result
Douglas Gregore02e2622010-12-22 21:19:48 +00001838 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1839 Info, Deduced))
1840 return Result;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001841
Douglas Gregore02e2622010-12-22 21:19:48 +00001842 // Capture the deduced template arguments for each parameter pack expanded
1843 // by this pack expansion, add them to the list of arguments we've deduced
1844 // for that pack, then clear out the deduced argument.
1845 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1846 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1847 if (!DeducedArg.isNull()) {
1848 NewlyDeducedPacks[I].push_back(DeducedArg);
1849 DeducedArg = DeducedTemplateArgument();
1850 }
1851 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001852
Douglas Gregore02e2622010-12-22 21:19:48 +00001853 ++ArgIdx;
1854 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001855
Douglas Gregore02e2622010-12-22 21:19:48 +00001856 // Build argument packs for each of the parameter packs expanded by this
1857 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00001858 if (Sema::TemplateDeductionResult Result
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001859 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
Douglas Gregor0216f812011-01-10 17:53:52 +00001860 Deduced, PackIndices, SavedPacks,
1861 NewlyDeducedPacks, Info))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001862 return Result;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001863 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001864
Douglas Gregor20a55e22010-12-22 18:17:10 +00001865 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001866 if (NumberOfArgumentsMustMatch &&
1867 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001868 return Sema::TDK_NonDeducedMismatch;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001869
Douglas Gregor20a55e22010-12-22 18:17:10 +00001870 return Sema::TDK_Success;
1871}
1872
Mike Stump1eb44332009-09-09 15:08:12 +00001873static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001874DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001875 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001876 const TemplateArgumentList &ParamList,
1877 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001878 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001879 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001880 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +00001881 ParamList.data(), ParamList.size(),
1882 ArgList.data(), ArgList.size(),
1883 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001884}
1885
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001886/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001887static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001888 const TemplateArgument &X,
1889 const TemplateArgument &Y) {
1890 if (X.getKind() != Y.getKind())
1891 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001893 switch (X.getKind()) {
1894 case TemplateArgument::Null:
David Blaikieb219cfc2011-09-23 05:06:16 +00001895 llvm_unreachable("Comparing NULL template argument");
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001897 case TemplateArgument::Type:
1898 return Context.getCanonicalType(X.getAsType()) ==
1899 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001901 case TemplateArgument::Declaration:
Eli Friedmand7a6b162012-09-26 02:36:12 +00001902 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) &&
1903 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam();
1904
1905 case TemplateArgument::NullPtr:
1906 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump1eb44332009-09-09 15:08:12 +00001907
Douglas Gregor788cd062009-11-11 01:00:40 +00001908 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001909 case TemplateArgument::TemplateExpansion:
1910 return Context.getCanonicalTemplateName(
1911 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1912 Context.getCanonicalTemplateName(
1913 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001914
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001915 case TemplateArgument::Integral:
Benjamin Kramer85524372012-06-07 15:09:51 +00001916 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Douglas Gregor788cd062009-11-11 01:00:40 +00001918 case TemplateArgument::Expression: {
1919 llvm::FoldingSetNodeID XID, YID;
1920 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001922 return XID == YID;
1923 }
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001925 case TemplateArgument::Pack:
1926 if (X.pack_size() != Y.pack_size())
1927 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001928
1929 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1930 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001931 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001932 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001933 if (!isSameTemplateArg(Context, *XP, *YP))
1934 return false;
1935
1936 return true;
1937 }
1938
David Blaikie30263482012-01-20 21:50:17 +00001939 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001940}
1941
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001942/// \brief Allocate a TemplateArgumentLoc where all locations have
1943/// been initialized to the given location.
1944///
1945/// \param S The semantic analysis object.
1946///
James Dennett1dfbd922012-06-14 21:40:34 +00001947/// \param Arg The template argument we are producing template argument
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001948/// location information for.
1949///
1950/// \param NTTPType For a declaration template argument, the type of
1951/// the non-type template parameter that corresponds to this template
1952/// argument.
1953///
1954/// \param Loc The source location to use for the resulting template
1955/// argument.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001956static TemplateArgumentLoc
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001957getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001958 const TemplateArgument &Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001959 QualType NTTPType,
1960 SourceLocation Loc) {
1961 switch (Arg.getKind()) {
1962 case TemplateArgument::Null:
1963 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001964
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001965 case TemplateArgument::Type:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001966 return TemplateArgumentLoc(Arg,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001967 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001968
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001969 case TemplateArgument::Declaration: {
1970 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001971 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregord2008e22012-04-06 22:40:38 +00001972 .takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001973 return TemplateArgumentLoc(TemplateArgument(E), E);
1974 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001975
Eli Friedmand7a6b162012-09-26 02:36:12 +00001976 case TemplateArgument::NullPtr: {
1977 Expr *E
1978 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1979 .takeAs<Expr>();
1980 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
1981 E);
1982 }
1983
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001984 case TemplateArgument::Integral: {
1985 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001986 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001987 return TemplateArgumentLoc(TemplateArgument(E), E);
1988 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001989
Douglas Gregorb6744ef2011-03-02 17:09:35 +00001990 case TemplateArgument::Template:
1991 case TemplateArgument::TemplateExpansion: {
1992 NestedNameSpecifierLocBuilder Builder;
1993 TemplateName Template = Arg.getAsTemplate();
1994 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
1995 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
1996 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1997 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
1998
1999 if (Arg.getKind() == TemplateArgument::Template)
2000 return TemplateArgumentLoc(Arg,
2001 Builder.getWithLocInContext(S.Context),
2002 Loc);
2003
2004
2005 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2006 Loc, Loc);
2007 }
Douglas Gregora7fc9012011-01-05 18:58:31 +00002008
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002009 case TemplateArgument::Expression:
2010 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002011
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002012 case TemplateArgument::Pack:
2013 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2014 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002015
David Blaikie30263482012-01-20 21:50:17 +00002016 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002017}
2018
2019
2020/// \brief Convert the given deduced template argument and add it to the set of
2021/// fully-converted template arguments.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002022static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002023 DeducedTemplateArgument Arg,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002024 NamedDecl *Template,
2025 QualType NTTPType,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002026 unsigned ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002027 TemplateDeductionInfo &Info,
2028 bool InFunctionTemplate,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002029 SmallVectorImpl<TemplateArgument> &Output) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002030 if (Arg.getKind() == TemplateArgument::Pack) {
2031 // This is a template argument pack, so check each of its arguments against
2032 // the template parameter.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002033 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002034 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00002035 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002036 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00002037 // When converting the deduced template argument, append it to the
2038 // general output list. We need to do this so that the template argument
2039 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002040 DeducedTemplateArgument InnerArg(*PA);
2041 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002042 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002043 NTTPType, PackedArgsBuilder.size(),
2044 Info, InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002045 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002046
Douglas Gregord53e16a2011-01-05 20:52:18 +00002047 // Move the converted template argument into our argument pack.
2048 PackedArgsBuilder.push_back(Output.back());
2049 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002050 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002051
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002052 // Create the resulting argument pack.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002053 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
Douglas Gregor203e6a32011-01-11 23:09:57 +00002054 PackedArgsBuilder.data(),
2055 PackedArgsBuilder.size()));
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002056 return false;
2057 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002058
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002059 // Convert the deduced template argument into a template
2060 // argument that we can check, almost as if the user had written
2061 // the template argument explicitly.
2062 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2063 Info.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002064
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002065 // Check the template argument, converting it as necessary.
2066 return S.CheckTemplateArgument(Param, ArgLoc,
2067 Template,
2068 Template->getLocation(),
2069 Template->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002070 ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002071 Output,
2072 InFunctionTemplate
2073 ? (Arg.wasDeducedFromArrayBound()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002074 ? Sema::CTAK_DeducedFromArrayBound
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002075 : Sema::CTAK_Deduced)
2076 : Sema::CTAK_Specified);
2077}
2078
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002079/// Complete template argument deduction for a class template partial
2080/// specialization.
2081static Sema::TemplateDeductionResult
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002082FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002083 ClassTemplatePartialSpecializationDecl *Partial,
2084 const TemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002085 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00002086 TemplateDeductionInfo &Info) {
Eli Friedman59a839c2012-02-08 03:07:05 +00002087 // Unevaluated SFINAE context.
2088 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002089 Sema::SFINAETrap Trap(S);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002090
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002091 Sema::ContextRAII SavedContext(S, Partial);
2092
2093 // C++ [temp.deduct.type]p2:
2094 // [...] or if any template argument remains neither deduced nor
2095 // explicitly specified, template argument deduction fails.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002096 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00002097 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2098 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002099 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002100 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002101 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002102 return Sema::TDK_Incomplete;
2103 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002104
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002105 // We have deduced this argument, so it still needs to be
2106 // checked and converted.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002107
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002108 // First, for a non-type template parameter type that is
2109 // initialized by a declaration, we need the type of the
2110 // corresponding non-type template parameter.
2111 QualType NTTPType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002112 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00002113 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002114 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00002115 if (NTTPType->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002116 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregord53e16a2011-01-05 20:52:18 +00002117 Builder.data(), Builder.size());
2118 NTTPType = S.SubstType(NTTPType,
2119 MultiLevelTemplateArgumentList(TemplateArgs),
2120 NTTP->getLocation(),
2121 NTTP->getDeclName());
2122 if (NTTPType.isNull()) {
2123 Info.Param = makeTemplateParameter(Param);
2124 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002125 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2126 Builder.data(),
Douglas Gregord53e16a2011-01-05 20:52:18 +00002127 Builder.size()));
2128 return Sema::TDK_SubstitutionFailure;
2129 }
2130 }
2131 }
2132
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002133 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002134 Partial, NTTPType, 0, Info, false,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002135 Builder)) {
2136 Info.Param = makeTemplateParameter(Param);
2137 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002138 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2139 Builder.size()));
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002140 return Sema::TDK_SubstitutionFailure;
2141 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002142 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002143
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002144 // Form the template argument list from the deduced template arguments.
2145 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002147 Builder.size());
2148
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002149 Info.reset(DeducedArgumentList);
2150
2151 // Substitute the deduced template arguments into the template
2152 // arguments of the class template partial specialization, and
2153 // verify that the instantiated template arguments are both valid
2154 // and are equivalent to the template arguments originally provided
2155 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00002156 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002157 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
2158 const TemplateArgumentLoc *PartialTemplateArgs
2159 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002160
2161 // Note that we don't provide the langle and rangle locations.
2162 TemplateArgumentListInfo InstArgs;
2163
Douglas Gregore02e2622010-12-22 21:19:48 +00002164 if (S.Subst(PartialTemplateArgs,
2165 Partial->getNumTemplateArgsAsWritten(),
2166 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2167 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2168 if (ParamIdx >= Partial->getTemplateParameters()->size())
2169 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2170
2171 Decl *Param
2172 = const_cast<NamedDecl *>(
2173 Partial->getTemplateParameters()->getParam(ParamIdx));
2174 Info.Param = makeTemplateParameter(Param);
2175 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2176 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002177 }
2178
Chris Lattner5f9e2722011-07-23 10:55:15 +00002179 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002180 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002181 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002182 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002183
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002184 TemplateParameterList *TemplateParams
2185 = ClassTemplate->getTemplateParameters();
2186 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002187 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002188 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00002189 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002190 Info.FirstArg = TemplateArgs[I];
2191 Info.SecondArg = InstArg;
2192 return Sema::TDK_NonDeducedMismatch;
2193 }
2194 }
2195
2196 if (Trap.hasErrorOccurred())
2197 return Sema::TDK_SubstitutionFailure;
2198
2199 return Sema::TDK_Success;
2200}
2201
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002202/// \brief Perform template argument deduction to determine whether
2203/// the given template arguments match the given class template
2204/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00002205Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00002206Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002207 const TemplateArgumentList &TemplateArgs,
2208 TemplateDeductionInfo &Info) {
Douglas Gregorae19fbb2012-09-13 21:01:57 +00002209 if (Partial->isInvalidDecl())
2210 return TDK_Invalid;
2211
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002212 // C++ [temp.class.spec.match]p2:
2213 // A partial specialization matches a given actual template
2214 // argument list if the template arguments of the partial
2215 // specialization can be deduced from the actual template argument
2216 // list (14.8.2).
Eli Friedman59a839c2012-02-08 03:07:05 +00002217
2218 // Unevaluated SFINAE context.
2219 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregorbb260412009-06-14 08:02:22 +00002220 SFINAETrap Trap(*this);
Eli Friedman59a839c2012-02-08 03:07:05 +00002221
Chris Lattner5f9e2722011-07-23 10:55:15 +00002222 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00002223 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00002224 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002225 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002226 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00002227 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00002228 TemplateArgs, Info, Deduced))
2229 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00002230
Richard Smith7e54fb52012-07-16 01:09:10 +00002231 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Douglas Gregor637a4092009-06-10 23:47:09 +00002232 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Richard Smith7e54fb52012-07-16 01:09:10 +00002233 DeducedArgs, Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00002234 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00002235 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00002236
Douglas Gregorbb260412009-06-14 08:02:22 +00002237 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002238 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002239
2240 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002241 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00002242}
Douglas Gregor031a5882009-06-13 00:26:55 +00002243
Douglas Gregor41128772009-06-26 23:27:24 +00002244/// \brief Determine whether the given type T is a simple-template-id type.
2245static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00002246 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00002247 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00002248 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Douglas Gregor41128772009-06-26 23:27:24 +00002250 return false;
2251}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002252
2253/// \brief Substitute the explicitly-provided template arguments into the
2254/// given function template according to C++ [temp.arg.explicit].
2255///
2256/// \param FunctionTemplate the function template into which the explicit
2257/// template arguments will be substituted.
2258///
James Dennett1dfbd922012-06-14 21:40:34 +00002259/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002260/// arguments.
2261///
Mike Stump1eb44332009-09-09 15:08:12 +00002262/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00002263/// with the converted and checked explicit template arguments.
2264///
Mike Stump1eb44332009-09-09 15:08:12 +00002265/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00002266/// parameters.
2267///
2268/// \param FunctionType if non-NULL, the result type of the function template
2269/// will also be instantiated and the pointed-to value will be updated with
2270/// the instantiated function type.
2271///
2272/// \param Info if substitution fails for any reason, this object will be
2273/// populated with more information about the failure.
2274///
2275/// \returns TDK_Success if substitution was successful, or some failure
2276/// condition.
2277Sema::TemplateDeductionResult
2278Sema::SubstituteExplicitTemplateArguments(
2279 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor67714232011-03-03 02:41:12 +00002280 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002281 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2282 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002283 QualType *FunctionType,
2284 TemplateDeductionInfo &Info) {
2285 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2286 TemplateParameterList *TemplateParams
2287 = FunctionTemplate->getTemplateParameters();
2288
John McCalld5532b62009-11-23 01:53:49 +00002289 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002290 // No arguments to substitute; just copy over the parameter types and
2291 // fill in the function type.
2292 for (FunctionDecl::param_iterator P = Function->param_begin(),
2293 PEnd = Function->param_end();
2294 P != PEnd;
2295 ++P)
2296 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Douglas Gregor83314aa2009-07-08 20:55:45 +00002298 if (FunctionType)
2299 *FunctionType = Function->getType();
2300 return TDK_Success;
2301 }
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Eli Friedman59a839c2012-02-08 03:07:05 +00002303 // Unevaluated SFINAE context.
2304 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +00002305 SFINAETrap Trap(*this);
2306
Douglas Gregor83314aa2009-07-08 20:55:45 +00002307 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002308 // Template arguments that are present shall be specified in the
2309 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00002310 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00002311 // there are corresponding template-parameters.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002312 SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00002313
2314 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002315 // explicitly-specified template arguments against this function template,
2316 // and then substitute them into the function parameter types.
Richard Smith7e54fb52012-07-16 01:09:10 +00002317 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002318 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Richard Smith7e54fb52012-07-16 01:09:10 +00002319 FunctionTemplate, DeducedArgs,
Douglas Gregor9b623632010-10-12 23:32:35 +00002320 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2321 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002322 if (Inst)
2323 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Douglas Gregor83314aa2009-07-08 20:55:45 +00002325 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002326 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002327 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002328 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00002329 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002330 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00002331 if (Index >= TemplateParams->size())
2332 Index = TemplateParams->size() - 1;
2333 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002334 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00002335 }
Mike Stump1eb44332009-09-09 15:08:12 +00002336
Douglas Gregor83314aa2009-07-08 20:55:45 +00002337 // Form the template argument list from the explicitly-specified
2338 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002339 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002340 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002341 Info.reset(ExplicitArgumentList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002342
John McCalldf41f182010-10-12 19:40:14 +00002343 // Template argument deduction and the final substitution should be
2344 // done in the context of the templated declaration. Explicit
2345 // argument substitution, on the other hand, needs to happen in the
2346 // calling context.
2347 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2348
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002349 // If we deduced template arguments for a template parameter pack,
Douglas Gregord3731192011-01-10 07:32:04 +00002350 // note that the template argument pack is partially substituted and record
2351 // the explicit template arguments. They'll be used as part of deduction
2352 // for this template parameter pack.
Douglas Gregord3731192011-01-10 07:32:04 +00002353 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2354 const TemplateArgument &Arg = Builder[I];
2355 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregord3731192011-01-10 07:32:04 +00002356 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002357 TemplateParams->getParam(I),
Douglas Gregord3731192011-01-10 07:32:04 +00002358 Arg.pack_begin(),
2359 Arg.pack_size());
2360 break;
2361 }
2362 }
2363
Richard Smitheefb3d52012-02-10 09:58:53 +00002364 const FunctionProtoType *Proto
2365 = Function->getType()->getAs<FunctionProtoType>();
2366 assert(Proto && "Function template does not have a prototype?");
2367
Douglas Gregor83314aa2009-07-08 20:55:45 +00002368 // Instantiate the types of each of the function parameters given the
Richard Smitheefb3d52012-02-10 09:58:53 +00002369 // explicitly-specified template arguments. If the function has a trailing
2370 // return type, substitute it after the arguments to ensure we substitute
2371 // in lexical order.
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002372 if (Proto->hasTrailingReturn()) {
2373 if (SubstParmTypes(Function->getLocation(),
2374 Function->param_begin(), Function->getNumParams(),
2375 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2376 ParamTypes))
2377 return TDK_SubstitutionFailure;
2378 }
2379
Richard Smitheefb3d52012-02-10 09:58:53 +00002380 // Instantiate the return type.
2381 // FIXME: exception-specifications?
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002382 QualType ResultType;
2383 {
2384 // C++11 [expr.prim.general]p3:
2385 // If a declaration declares a member function or member function
2386 // template of a class X, the expression this is a prvalue of type
2387 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2388 // and the end of the function-definition, member-declarator, or
2389 // declarator.
2390 unsigned ThisTypeQuals = 0;
2391 CXXRecordDecl *ThisContext = 0;
2392 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2393 ThisContext = Method->getParent();
2394 ThisTypeQuals = Method->getTypeQualifiers();
2395 }
2396
2397 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
2398 getLangOpts().CPlusPlus0x);
2399
2400 ResultType = SubstType(Proto->getResultType(),
2401 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2402 Function->getTypeSpecStartLoc(),
2403 Function->getDeclName());
2404 if (ResultType.isNull() || Trap.hasErrorOccurred())
2405 return TDK_SubstitutionFailure;
2406 }
2407
Richard Smitheefb3d52012-02-10 09:58:53 +00002408 // Instantiate the types of each of the function parameters given the
2409 // explicitly-specified template arguments if we didn't do so earlier.
2410 if (!Proto->hasTrailingReturn() &&
2411 SubstParmTypes(Function->getLocation(),
2412 Function->param_begin(), Function->getNumParams(),
2413 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2414 ParamTypes))
2415 return TDK_SubstitutionFailure;
2416
Douglas Gregor83314aa2009-07-08 20:55:45 +00002417 if (FunctionType) {
Mike Stump1eb44332009-09-09 15:08:12 +00002418 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002419 ParamTypes.data(), ParamTypes.size(),
2420 Proto->isVariadic(),
Richard Smitheefb3d52012-02-10 09:58:53 +00002421 Proto->hasTrailingReturn(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002422 Proto->getTypeQuals(),
Douglas Gregorc938c162011-01-26 05:01:58 +00002423 Proto->getRefQualifier(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002424 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00002425 Function->getDeclName(),
2426 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002427 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2428 return TDK_SubstitutionFailure;
2429 }
Mike Stump1eb44332009-09-09 15:08:12 +00002430
Douglas Gregor83314aa2009-07-08 20:55:45 +00002431 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002432 // Trailing template arguments that can be deduced (14.8.2) may be
2433 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002434 // template arguments can be deduced, they may all be omitted; in this
2435 // case, the empty template argument list <> itself may also be omitted.
2436 //
Douglas Gregord3731192011-01-10 07:32:04 +00002437 // Take all of the explicitly-specified arguments and put them into
2438 // the set of deduced template arguments. Explicitly-specified
2439 // parameter packs, however, will be set to NULL since the deduction
2440 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002441 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00002442 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2443 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2444 if (Arg.getKind() == TemplateArgument::Pack)
2445 Deduced.push_back(DeducedTemplateArgument());
2446 else
2447 Deduced.push_back(Arg);
2448 }
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Douglas Gregor83314aa2009-07-08 20:55:45 +00002450 return TDK_Success;
2451}
2452
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002453/// \brief Check whether the deduced argument type for a call to a function
2454/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2455static bool
2456CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2457 QualType DeducedA) {
2458 ASTContext &Context = S.Context;
2459
2460 QualType A = OriginalArg.OriginalArgType;
2461 QualType OriginalParamType = OriginalArg.OriginalParamType;
2462
2463 // Check for type equality (top-level cv-qualifiers are ignored).
2464 if (Context.hasSameUnqualifiedType(A, DeducedA))
2465 return false;
2466
2467 // Strip off references on the argument types; they aren't needed for
2468 // the following checks.
2469 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2470 DeducedA = DeducedARef->getPointeeType();
2471 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2472 A = ARef->getPointeeType();
2473
2474 // C++ [temp.deduct.call]p4:
2475 // [...] However, there are three cases that allow a difference:
2476 // - If the original P is a reference type, the deduced A (i.e., the
2477 // type referred to by the reference) can be more cv-qualified than
2478 // the transformed A.
2479 if (const ReferenceType *OriginalParamRef
2480 = OriginalParamType->getAs<ReferenceType>()) {
2481 // We don't want to keep the reference around any more.
2482 OriginalParamType = OriginalParamRef->getPointeeType();
2483
2484 Qualifiers AQuals = A.getQualifiers();
2485 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregorb2513022012-07-18 00:14:59 +00002486
2487 // Under Objective-C++ ARC, the deduced type may have implicitly been
2488 // given strong lifetime. If so, update the original qualifiers to
2489 // include this strong lifetime.
2490 if (S.getLangOpts().ObjCAutoRefCount &&
2491 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2492 AQuals.getObjCLifetime() == Qualifiers::OCL_None) {
2493 AQuals.setObjCLifetime(Qualifiers::OCL_Strong);
2494 }
2495
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002496 if (AQuals == DeducedAQuals) {
2497 // Qualifiers match; there's nothing to do.
2498 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorc99f0ec2011-06-17 14:36:00 +00002499 return true;
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002500 } else {
2501 // Qualifiers are compatible, so have the argument type adopt the
2502 // deduced argument type's qualifiers as if we had performed the
2503 // qualification conversion.
2504 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2505 }
2506 }
2507
2508 // - The transformed A can be another pointer or pointer to member
2509 // type that can be converted to the deduced A via a qualification
2510 // conversion.
Chandler Carruth18e04612011-06-18 01:19:03 +00002511 //
2512 // Also allow conversions which merely strip [[noreturn]] from function types
2513 // (recursively) as an extension.
2514 // FIXME: Currently, this doesn't place nicely with qualfication conversions.
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002515 bool ObjCLifetimeConversion = false;
Chandler Carruth18e04612011-06-18 01:19:03 +00002516 QualType ResultTy;
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002517 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth18e04612011-06-18 01:19:03 +00002518 (S.IsQualificationConversion(A, DeducedA, false,
2519 ObjCLifetimeConversion) ||
2520 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002521 return false;
2522
2523
2524 // - If P is a class and P has the form simple-template-id, then the
2525 // transformed A can be a derived class of the deduced A. [...]
2526 // [...] Likewise, if P is a pointer to a class of the form
2527 // simple-template-id, the transformed A can be a pointer to a
2528 // derived class pointed to by the deduced A.
2529 if (const PointerType *OriginalParamPtr
2530 = OriginalParamType->getAs<PointerType>()) {
2531 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2532 if (const PointerType *APtr = A->getAs<PointerType>()) {
2533 if (A->getPointeeType()->isRecordType()) {
2534 OriginalParamType = OriginalParamPtr->getPointeeType();
2535 DeducedA = DeducedAPtr->getPointeeType();
2536 A = APtr->getPointeeType();
2537 }
2538 }
2539 }
2540 }
2541
2542 if (Context.hasSameUnqualifiedType(A, DeducedA))
2543 return false;
2544
2545 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2546 S.IsDerivedFrom(A, DeducedA))
2547 return false;
2548
2549 return true;
2550}
2551
Mike Stump1eb44332009-09-09 15:08:12 +00002552/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002553/// checking the deduced template arguments for completeness and forming
2554/// the function template specialization.
Douglas Gregordbfb3712011-06-16 16:50:48 +00002555///
2556/// \param OriginalCallArgs If non-NULL, the original call arguments against
2557/// which the deduced argument types should be compared.
Mike Stump1eb44332009-09-09 15:08:12 +00002558Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00002559Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002560 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002561 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002562 FunctionDecl *&Specialization,
Douglas Gregordbfb3712011-06-16 16:50:48 +00002563 TemplateDeductionInfo &Info,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002564 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002565 TemplateParameterList *TemplateParams
2566 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Eli Friedman59a839c2012-02-08 03:07:05 +00002568 // Unevaluated SFINAE context.
2569 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +00002570 SFINAETrap Trap(*this);
2571
Douglas Gregor83314aa2009-07-08 20:55:45 +00002572 // Enter a new template instantiation context while we instantiate the
2573 // actual function declaration.
Richard Smith7e54fb52012-07-16 01:09:10 +00002574 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Mike Stump1eb44332009-09-09 15:08:12 +00002575 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Richard Smith7e54fb52012-07-16 01:09:10 +00002576 FunctionTemplate, DeducedArgs,
Douglas Gregor9b623632010-10-12 23:32:35 +00002577 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2578 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002579 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002580 return TDK_InstantiationDepth;
2581
John McCall96db3102010-04-29 01:18:58 +00002582 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002583
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002584 // C++ [temp.deduct.type]p2:
2585 // [...] or if any template argument remains neither deduced nor
2586 // explicitly specified, template argument deduction fails.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002587 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002588 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2589 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002590
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002591 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002592 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002593 // We have already fully type-checked and converted this
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002594 // argument, because it was explicitly-specified. Just record the
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002595 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002596 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002597 continue;
2598 }
2599
2600 // We have deduced this argument, so it still needs to be
2601 // checked and converted.
2602
2603 // First, for a non-type template parameter type that is
2604 // initialized by a declaration, we need the type of the
2605 // corresponding non-type template parameter.
2606 QualType NTTPType;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002607 if (NonTypeTemplateParmDecl *NTTP
2608 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002609 NTTPType = NTTP->getType();
2610 if (NTTPType->isDependentType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002611 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002612 Builder.data(), Builder.size());
2613 NTTPType = SubstType(NTTPType,
2614 MultiLevelTemplateArgumentList(TemplateArgs),
2615 NTTP->getLocation(),
2616 NTTP->getDeclName());
2617 if (NTTPType.isNull()) {
2618 Info.Param = makeTemplateParameter(Param);
2619 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002620 Info.reset(TemplateArgumentList::CreateCopy(Context,
2621 Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002622 Builder.size()));
2623 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002624 }
2625 }
2626 }
2627
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002628 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002629 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002630 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002631 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002632 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002633 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2634 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002635 return TDK_SubstitutionFailure;
2636 }
2637
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002638 continue;
2639 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002640
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002641 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002642 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002643 // be deduced to an empty sequence of template arguments.
2644 // FIXME: Where did the word "trailing" come from?
2645 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002646 // We may have had explicitly-specified template arguments for this
2647 // template parameter pack. If so, our empty deduction extends the
2648 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2649 const TemplateArgument *ExplicitArgs;
2650 unsigned NumExplicitArgs;
Richard Smitha8eaf002012-08-23 06:16:52 +00002651 if (CurrentInstantiationScope &&
2652 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002653 &NumExplicitArgs)
2654 == Param)
2655 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002656 else
Eli Friedmand7a6b162012-09-26 02:36:12 +00002657 Builder.push_back(TemplateArgument::getEmptyPack());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002658
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002659 continue;
2660 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002661
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002662 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002663 TemplateArgumentLoc DefArg
2664 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2665 FunctionTemplate->getLocation(),
2666 FunctionTemplate->getSourceRange().getEnd(),
2667 Param,
2668 Builder);
2669
2670 // If there was no default argument, deduction is incomplete.
2671 if (DefArg.getArgument().isNull()) {
2672 Info.Param = makeTemplateParameter(
2673 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2674 return TDK_Incomplete;
2675 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002676
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002677 // Check whether we can actually use the default argument.
2678 if (CheckTemplateArgument(Param, DefArg,
2679 FunctionTemplate,
2680 FunctionTemplate->getLocation(),
2681 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002682 0, Builder,
Douglas Gregor8735b292011-06-03 02:59:40 +00002683 CTAK_Specified)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002684 Info.Param = makeTemplateParameter(
2685 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002686 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002687 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor910f8002010-11-07 23:05:16 +00002688 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002689 return TDK_SubstitutionFailure;
2690 }
2691
2692 // If we get here, we successfully used the default template argument.
2693 }
2694
2695 // Form the template argument list from the deduced template arguments.
2696 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002697 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002698 Info.reset(DeducedArgumentList);
2699
Mike Stump1eb44332009-09-09 15:08:12 +00002700 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002701 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002702 DeclContext *Owner = FunctionTemplate->getDeclContext();
2703 if (FunctionTemplate->getFriendObjectKind())
2704 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002705 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002706 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002707 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor5fad9b82011-10-12 20:35:48 +00002708 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002709 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002710
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002711 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregorf8825742009-09-15 18:26:13 +00002712 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002713
Mike Stump1eb44332009-09-09 15:08:12 +00002714 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002715 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002716 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2717 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002718 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Douglas Gregor5fad9b82011-10-12 20:35:48 +00002720 // There may have been an error that did not prevent us from constructing a
2721 // declaration. Mark the declaration invalid and return with a substitution
2722 // failure.
2723 if (Trap.hasErrorOccurred()) {
2724 Specialization->setInvalidDecl(true);
2725 return TDK_SubstitutionFailure;
2726 }
2727
Douglas Gregordbfb3712011-06-16 16:50:48 +00002728 if (OriginalCallArgs) {
2729 // C++ [temp.deduct.call]p4:
2730 // In general, the deduction process attempts to find template argument
2731 // values that will make the deduced A identical to A (after the type A
2732 // is transformed as described above). [...]
2733 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2734 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregordbfb3712011-06-16 16:50:48 +00002735 unsigned ParamIdx = OriginalArg.ArgIdx;
2736
2737 if (ParamIdx >= Specialization->getNumParams())
2738 continue;
2739
2740 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Douglas Gregorb7edc4f2011-06-17 05:18:17 +00002741 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2742 return Sema::TDK_SubstitutionFailure;
Douglas Gregordbfb3712011-06-16 16:50:48 +00002743 }
2744 }
2745
Douglas Gregor9b623632010-10-12 23:32:35 +00002746 // If we suppressed any diagnostics while performing template argument
2747 // deduction, and if we haven't already instantiated this declaration,
2748 // keep track of these diagnostics. They'll be emitted if this specialization
2749 // is actually used.
2750 if (Info.diag_begin() != Info.diag_end()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002751 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor9b623632010-10-12 23:32:35 +00002752 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2753 if (Pos == SuppressedDiagnostics.end())
2754 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2755 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002756 }
Douglas Gregor9b623632010-10-12 23:32:35 +00002757
Mike Stump1eb44332009-09-09 15:08:12 +00002758 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002759}
2760
John McCall9c72c602010-08-27 09:08:28 +00002761/// Gets the type of a function for template-argument-deducton
2762/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002763static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002764 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002765 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002766 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002767 if (Method->isInstance()) {
2768 // An instance method that's referenced in a form that doesn't
2769 // look like a member pointer is just invalid.
2770 if (!R.HasFormOfMemberPointer) return QualType();
2771
John McCalleff92132010-02-02 02:21:27 +00002772 return Context.getMemberPointerType(Fn->getType(),
2773 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002774 }
2775
2776 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002777 return Context.getPointerType(Fn->getType());
2778}
2779
2780/// Apply the deduction rules for overload sets.
2781///
2782/// \return the null type if this argument should be treated as an
2783/// undeduced context
2784static QualType
2785ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002786 Expr *Arg, QualType ParamType,
2787 bool ParamWasReference) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002788
John McCall9c72c602010-08-27 09:08:28 +00002789 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002790
John McCall9c72c602010-08-27 09:08:28 +00002791 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002792
Douglas Gregor75f21af2010-08-30 21:04:23 +00002793 // C++0x [temp.deduct.call]p4
2794 unsigned TDF = 0;
2795 if (ParamWasReference)
2796 TDF |= TDF_ParamWithReferenceType;
2797 if (R.IsAddressOfOperand)
2798 TDF |= TDF_IgnoreQualifiers;
2799
John McCalleff92132010-02-02 02:21:27 +00002800 // C++0x [temp.deduct.call]p6:
2801 // When P is a function type, pointer to function type, or pointer
2802 // to member function type:
2803
2804 if (!ParamType->isFunctionType() &&
2805 !ParamType->isFunctionPointerType() &&
Douglas Gregor860d9b72012-03-12 21:09:16 +00002806 !ParamType->isMemberFunctionPointerType()) {
2807 if (Ovl->hasExplicitTemplateArgs()) {
2808 // But we can still look for an explicit specialization.
2809 if (FunctionDecl *ExplicitSpec
2810 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
2811 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
2812 }
John McCalleff92132010-02-02 02:21:27 +00002813
Douglas Gregor860d9b72012-03-12 21:09:16 +00002814 return QualType();
2815 }
2816
2817 // Gather the explicit template arguments, if any.
2818 TemplateArgumentListInfo ExplicitTemplateArgs;
2819 if (Ovl->hasExplicitTemplateArgs())
2820 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
John McCalleff92132010-02-02 02:21:27 +00002821 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002822 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2823 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002824 NamedDecl *D = (*I)->getUnderlyingDecl();
2825
Douglas Gregor860d9b72012-03-12 21:09:16 +00002826 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2827 // - If the argument is an overload set containing one or more
2828 // function templates, the parameter is treated as a
2829 // non-deduced context.
2830 if (!Ovl->hasExplicitTemplateArgs())
2831 return QualType();
2832
2833 // Otherwise, see if we can resolve a function type
2834 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00002835 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor860d9b72012-03-12 21:09:16 +00002836 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
2837 Specialization, Info))
2838 continue;
2839
2840 D = Specialization;
2841 }
John McCalleff92132010-02-02 02:21:27 +00002842
2843 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002844 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2845 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002846
Douglas Gregor75f21af2010-08-30 21:04:23 +00002847 // Function-to-pointer conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002848 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor75f21af2010-08-30 21:04:23 +00002849 ArgType->isFunctionType())
2850 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002851
John McCalleff92132010-02-02 02:21:27 +00002852 // - If the argument is an overload set (not containing function
2853 // templates), trial argument deduction is attempted using each
2854 // of the members of the set. If deduction succeeds for only one
2855 // of the overload set members, that member is used as the
2856 // argument value for the deduction. If deduction succeeds for
2857 // more than one member of the overload set the parameter is
2858 // treated as a non-deduced context.
2859
2860 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2861 // Type deduction is done independently for each P/A pair, and
2862 // the deduced template argument values are then combined.
2863 // So we do not reject deductions which were made elsewhere.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002864 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregor02024a92010-03-28 02:42:43 +00002865 Deduced(TemplateParams->size());
Craig Topper93e45992012-09-19 02:26:47 +00002866 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002867 Sema::TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00002868 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
2869 ArgType, Info, Deduced, TDF);
John McCalleff92132010-02-02 02:21:27 +00002870 if (Result) continue;
2871 if (!Match.isNull()) return QualType();
2872 Match = ArgType;
2873 }
2874
2875 return Match;
2876}
2877
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002878/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002879/// described in C++ [temp.deduct.call].
2880///
2881/// \returns true if the caller should not attempt to perform any template
2882/// argument deduction based on this P/A pair.
2883static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2884 TemplateParameterList *TemplateParams,
2885 QualType &ParamType,
2886 QualType &ArgType,
2887 Expr *Arg,
2888 unsigned &TDF) {
2889 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002890 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002891 // are ignored for type deduction.
Douglas Gregora459cc22011-04-27 23:34:22 +00002892 if (ParamType.hasQualifiers())
2893 ParamType = ParamType.getUnqualifiedType();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002894 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2895 if (ParamRefType) {
Richard Smith34b41d92011-02-20 03:19:35 +00002896 QualType PointeeType = ParamRefType->getPointeeType();
2897
Douglas Gregorf15748a2011-06-03 03:35:07 +00002898 // If the argument has incomplete array type, try to complete it's type.
Douglas Gregord10099e2012-05-04 16:32:21 +00002899 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
Douglas Gregorf15748a2011-06-03 03:35:07 +00002900 ArgType = Arg->getType();
2901
Douglas Gregor2ad746a2011-01-21 05:18:22 +00002902 // [C++0x] If P is an rvalue reference to a cv-unqualified
2903 // template parameter and the argument is an lvalue, the type
2904 // "lvalue reference to A" is used in place of A for type
2905 // deduction.
Richard Smith34b41d92011-02-20 03:19:35 +00002906 if (isa<RValueReferenceType>(ParamType)) {
2907 if (!PointeeType.getQualifiers() &&
2908 isa<TemplateTypeParmType>(PointeeType) &&
Douglas Gregor9625e442011-05-21 22:16:50 +00002909 Arg->Classify(S.Context).isLValue() &&
2910 Arg->getType() != S.Context.OverloadTy &&
2911 Arg->getType() != S.Context.BoundMemberTy)
Douglas Gregor2ad746a2011-01-21 05:18:22 +00002912 ArgType = S.Context.getLValueReferenceType(ArgType);
2913 }
2914
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002915 // [...] If P is a reference type, the type referred to by P is used
2916 // for type deduction.
Richard Smith34b41d92011-02-20 03:19:35 +00002917 ParamType = PointeeType;
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002918 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002919
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002920 // Overload sets usually make this parameter an undeduced
2921 // context, but there are sometimes special circumstances.
2922 if (ArgType == S.Context.OverloadTy) {
2923 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2924 Arg, ParamType,
2925 ParamRefType != 0);
2926 if (ArgType.isNull())
2927 return true;
2928 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002929
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002930 if (ParamRefType) {
2931 // C++0x [temp.deduct.call]p3:
2932 // [...] If P is of the form T&&, where T is a template parameter, and
2933 // the argument is an lvalue, the type A& is used in place of A for
2934 // type deduction.
2935 if (ParamRefType->isRValueReferenceType() &&
2936 ParamRefType->getAs<TemplateTypeParmType>() &&
2937 Arg->isLValue())
2938 ArgType = S.Context.getLValueReferenceType(ArgType);
2939 } else {
2940 // C++ [temp.deduct.call]p2:
2941 // If P is not a reference type:
2942 // - If A is an array type, the pointer type produced by the
2943 // array-to-pointer standard conversion (4.2) is used in place of
2944 // A for type deduction; otherwise,
2945 if (ArgType->isArrayType())
2946 ArgType = S.Context.getArrayDecayedType(ArgType);
2947 // - If A is a function type, the pointer type produced by the
2948 // function-to-pointer standard conversion (4.3) is used in place
2949 // of A for type deduction; otherwise,
2950 else if (ArgType->isFunctionType())
2951 ArgType = S.Context.getPointerType(ArgType);
2952 else {
NAKAMURA Takumi00995302011-01-27 07:09:49 +00002953 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002954 // type are ignored for type deduction.
Douglas Gregora459cc22011-04-27 23:34:22 +00002955 ArgType = ArgType.getUnqualifiedType();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002956 }
2957 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002958
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002959 // C++0x [temp.deduct.call]p4:
2960 // In general, the deduction process attempts to find template argument
2961 // values that will make the deduced A identical to A (after the type A
2962 // is transformed as described above). [...]
2963 TDF = TDF_SkipNonDependent;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002964
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002965 // - If the original P is a reference type, the deduced A (i.e., the
2966 // type referred to by the reference) can be more cv-qualified than
2967 // the transformed A.
2968 if (ParamRefType)
2969 TDF |= TDF_ParamWithReferenceType;
2970 // - The transformed A can be another pointer or pointer to member
2971 // type that can be converted to the deduced A via a qualification
2972 // conversion (4.4).
2973 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2974 ArgType->isObjCObjectPointerType())
2975 TDF |= TDF_IgnoreQualifiers;
2976 // - If P is a class and P has the form simple-template-id, then the
2977 // transformed A can be a derived class of the deduced A. Likewise,
2978 // if P is a pointer to a class of the form simple-template-id, the
2979 // transformed A can be a pointer to a derived class pointed to by
2980 // the deduced A.
2981 if (isSimpleTemplateIdType(ParamType) ||
2982 (isa<PointerType>(ParamType) &&
2983 isSimpleTemplateIdType(
2984 ParamType->getAs<PointerType>()->getPointeeType())))
2985 TDF |= TDF_DerivedClass;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002986
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002987 return false;
2988}
2989
Douglas Gregordbfb3712011-06-16 16:50:48 +00002990static bool hasDeducibleTemplateParameters(Sema &S,
2991 FunctionTemplateDecl *FunctionTemplate,
2992 QualType T);
2993
Sebastian Redl4b911e62012-03-15 21:40:51 +00002994/// \brief Perform template argument deduction by matching a parameter type
2995/// against a single expression, where the expression is an element of
2996/// an initializer list that was originally matched against the argument
2997/// type.
2998static Sema::TemplateDeductionResult
2999DeduceTemplateArgumentByListElement(Sema &S,
3000 TemplateParameterList *TemplateParams,
3001 QualType ParamType, Expr *Arg,
3002 TemplateDeductionInfo &Info,
3003 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3004 unsigned TDF) {
3005 // Handle the case where an init list contains another init list as the
3006 // element.
3007 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3008 QualType X;
3009 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X))
3010 return Sema::TDK_Success; // Just ignore this expression.
3011
3012 // Recurse down into the init list.
3013 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3014 if (Sema::TemplateDeductionResult Result =
3015 DeduceTemplateArgumentByListElement(S, TemplateParams, X,
3016 ILE->getInit(i),
3017 Info, Deduced, TDF))
3018 return Result;
3019 }
3020 return Sema::TDK_Success;
3021 }
3022
3023 // For all other cases, just match by type.
Douglas Gregord2803892012-04-04 05:10:53 +00003024 QualType ArgType = Arg->getType();
3025 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
3026 ArgType, Arg, TDF))
3027 return Sema::TDK_FailedOverloadResolution;
Sebastian Redl4b911e62012-03-15 21:40:51 +00003028 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregord2803892012-04-04 05:10:53 +00003029 ArgType, Info, Deduced, TDF);
Sebastian Redl4b911e62012-03-15 21:40:51 +00003030}
3031
Douglas Gregore53060f2009-06-25 22:08:12 +00003032/// \brief Perform template argument deduction from a function call
3033/// (C++ [temp.deduct.call]).
3034///
3035/// \param FunctionTemplate the function template for which we are performing
3036/// template argument deduction.
3037///
James Dennett40ae6662012-06-22 08:52:37 +00003038/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregor48026d22010-01-11 18:40:55 +00003039/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003040///
Douglas Gregore53060f2009-06-25 22:08:12 +00003041/// \param Args the function call arguments
3042///
Douglas Gregor48026d22010-01-11 18:40:55 +00003043/// \param Name the name of the function being called. This is only significant
3044/// when the function template is a conversion function template, in which
3045/// case this routine will also perform template argument deduction based on
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003046/// the function to which
Douglas Gregor48026d22010-01-11 18:40:55 +00003047///
Douglas Gregore53060f2009-06-25 22:08:12 +00003048/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00003049/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00003050/// template argument deduction.
3051///
3052/// \param Info the argument will be updated to provide additional information
3053/// about template argument deduction.
3054///
3055/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00003056Sema::TemplateDeductionResult
3057Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor67714232011-03-03 02:41:12 +00003058 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003059 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00003060 FunctionDecl *&Specialization,
3061 TemplateDeductionInfo &Info) {
Douglas Gregorae19fbb2012-09-13 21:01:57 +00003062 if (FunctionTemplate->isInvalidDecl())
3063 return TDK_Invalid;
3064
Douglas Gregore53060f2009-06-25 22:08:12 +00003065 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003066
Douglas Gregore53060f2009-06-25 22:08:12 +00003067 // C++ [temp.deduct.call]p1:
3068 // Template argument deduction is done by comparing each function template
3069 // parameter type (call it P) with the type of the corresponding argument
3070 // of the call (call it A) as described below.
Ahmed Charles13a140c2012-02-25 11:00:22 +00003071 unsigned CheckArgs = Args.size();
3072 if (Args.size() < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00003073 return TDK_TooFewArguments;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003074 else if (Args.size() > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003075 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00003076 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003077 if (Proto->isTemplateVariadic())
3078 /* Do nothing */;
3079 else if (Proto->isVariadic())
3080 CheckArgs = Function->getNumParams();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003081 else
Douglas Gregore53060f2009-06-25 22:08:12 +00003082 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00003083 }
Mike Stump1eb44332009-09-09 15:08:12 +00003084
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003085 // The types of the parameters from which we will perform template argument
3086 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00003087 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00003088 TemplateParameterList *TemplateParams
3089 = FunctionTemplate->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003090 SmallVector<DeducedTemplateArgument, 4> Deduced;
3091 SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00003092 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00003093 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00003094 TemplateDeductionResult Result =
3095 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00003096 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00003097 Deduced,
3098 ParamTypes,
3099 0,
3100 Info);
3101 if (Result)
3102 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00003103
3104 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003105 } else {
3106 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003107 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003108 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3109 }
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003111 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00003112 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003113 unsigned ArgIdx = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003114 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003115 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003116 ParamIdx != NumParams; ++ParamIdx) {
Douglas Gregordbfb3712011-06-16 16:50:48 +00003117 QualType OrigParamType = ParamTypes[ParamIdx];
3118 QualType ParamType = OrigParamType;
3119
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003120 const PackExpansionType *ParamExpansion
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003121 = dyn_cast<PackExpansionType>(ParamType);
3122 if (!ParamExpansion) {
3123 // Simple case: matching a function parameter to a function argument.
3124 if (ArgIdx >= CheckArgs)
3125 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003126
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003127 Expr *Arg = Args[ArgIdx++];
3128 QualType ArgType = Arg->getType();
Douglas Gregordbfb3712011-06-16 16:50:48 +00003129
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003130 unsigned TDF = 0;
3131 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3132 ParamType, ArgType, Arg,
3133 TDF))
3134 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003135
Douglas Gregord8f5b332011-10-09 22:06:46 +00003136 // If we have nothing to deduce, we're done.
3137 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3138 continue;
3139
Sebastian Redl84760e32012-01-17 22:49:58 +00003140 // If the argument is an initializer list ...
3141 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3142 // ... then the parameter is an undeduced context, unless the parameter
3143 // type is (reference to cv) std::initializer_list<P'>, in which case
3144 // deduction is done for each element of the initializer list, and the
3145 // result is the deduced type if it's the same for all elements.
3146 QualType X;
3147 // Removing references was already done.
3148 if (!isStdInitializerList(ParamType, &X))
3149 continue;
3150
3151 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3152 if (TemplateDeductionResult Result =
Sebastian Redl4b911e62012-03-15 21:40:51 +00003153 DeduceTemplateArgumentByListElement(*this, TemplateParams, X,
3154 ILE->getInit(i),
3155 Info, Deduced, TDF))
Sebastian Redl84760e32012-01-17 22:49:58 +00003156 return Result;
3157 }
3158 // Don't track the argument type, since an initializer list has none.
3159 continue;
3160 }
3161
Douglas Gregordbfb3712011-06-16 16:50:48 +00003162 // Keep track of the argument type and corresponding parameter index,
3163 // so we can check for compatibility between the deduced A and A.
Douglas Gregord8f5b332011-10-09 22:06:46 +00003164 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3165 ArgType));
Douglas Gregordbfb3712011-06-16 16:50:48 +00003166
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003167 if (TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00003168 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3169 ParamType, ArgType,
3170 Info, Deduced, TDF))
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003171 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00003172
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003173 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00003174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003175
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003176 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003177 // For a function parameter pack that occurs at the end of the
3178 // parameter-declaration-list, the type A of each remaining argument of
3179 // the call is compared with the type P of the declarator-id of the
3180 // function parameter pack. Each comparison deduces template arguments
3181 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00003182 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00003184 // the parameter pack is a non-deduced context.
3185 if (ParamIdx + 1 < NumParams)
3186 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003187
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003188 QualType ParamPattern = ParamExpansion->getPattern();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003189 SmallVector<unsigned, 2> PackIndices;
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003190 {
Benjamin Kramer013b3662012-01-30 16:17:39 +00003191 llvm::SmallBitVector SawIndices(TemplateParams->size());
Chris Lattner5f9e2722011-07-23 10:55:15 +00003192 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003193 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
3194 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
3195 unsigned Depth, Index;
3196 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
3197 if (Depth == 0 && !SawIndices[Index]) {
3198 SawIndices[Index] = true;
3199 PackIndices.push_back(Index);
3200 }
Douglas Gregore53060f2009-06-25 22:08:12 +00003201 }
3202 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003203 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003204
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003205 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003206 // expanded by this pack expansion (the outer index) and for each
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003207 // template argument (the inner SmallVectors).
Chris Lattner5f9e2722011-07-23 10:55:15 +00003208 SmallVector<SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00003209 NewlyDeducedPacks(PackIndices.size());
Chris Lattner5f9e2722011-07-23 10:55:15 +00003210 SmallVector<DeducedTemplateArgument, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00003211 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00003212 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003213 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003214 bool HasAnyArguments = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003215 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003216 HasAnyArguments = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003217
Douglas Gregordbfb3712011-06-16 16:50:48 +00003218 QualType OrigParamType = ParamPattern;
3219 ParamType = OrigParamType;
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003220 Expr *Arg = Args[ArgIdx];
3221 QualType ArgType = Arg->getType();
Douglas Gregordbfb3712011-06-16 16:50:48 +00003222
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003223 unsigned TDF = 0;
3224 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3225 ParamType, ArgType, Arg,
3226 TDF)) {
3227 // We can't actually perform any deduction for this argument, so stop
3228 // deduction at this point.
3229 ++ArgIdx;
3230 break;
3231 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003232
Sebastian Redl84760e32012-01-17 22:49:58 +00003233 // As above, initializer lists need special handling.
3234 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3235 QualType X;
3236 if (!isStdInitializerList(ParamType, &X)) {
3237 ++ArgIdx;
3238 break;
3239 }
Douglas Gregordbfb3712011-06-16 16:50:48 +00003240
Sebastian Redl84760e32012-01-17 22:49:58 +00003241 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3242 if (TemplateDeductionResult Result =
3243 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X,
3244 ILE->getInit(i)->getType(),
3245 Info, Deduced, TDF))
3246 return Result;
3247 }
3248 } else {
3249
3250 // Keep track of the argument type and corresponding argument index,
3251 // so we can check for compatibility between the deduced A and A.
3252 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3253 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3254 ArgType));
3255
3256 if (TemplateDeductionResult Result
3257 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3258 ParamType, ArgType, Info,
3259 Deduced, TDF))
3260 return Result;
3261 }
Mike Stump1eb44332009-09-09 15:08:12 +00003262
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003263 // Capture the deduced template arguments for each parameter pack expanded
3264 // by this pack expansion, add them to the list of arguments we've deduced
3265 // for that pack, then clear out the deduced argument.
3266 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
3267 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
3268 if (!DeducedArg.isNull()) {
3269 NewlyDeducedPacks[I].push_back(DeducedArg);
3270 DeducedArg = DeducedTemplateArgument();
3271 }
3272 }
3273 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003274
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003275 // Build argument packs for each of the parameter packs expanded by this
3276 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00003277 if (Sema::TemplateDeductionResult Result
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003278 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
Douglas Gregor0216f812011-01-10 17:53:52 +00003279 Deduced, PackIndices, SavedPacks,
3280 NewlyDeducedPacks, Info))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003281 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00003283 // After we've matching against a parameter pack, we're done.
3284 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00003285 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003286
Mike Stump1eb44332009-09-09 15:08:12 +00003287 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00003288 NumExplicitlySpecified,
Douglas Gregordbfb3712011-06-16 16:50:48 +00003289 Specialization, Info, &OriginalCallArgs);
Douglas Gregore53060f2009-06-25 22:08:12 +00003290}
3291
Douglas Gregor83314aa2009-07-08 20:55:45 +00003292/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00003293/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3294/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003295///
3296/// \param FunctionTemplate the function template for which we are performing
3297/// template argument deduction.
3298///
James Dennett40ae6662012-06-22 08:52:37 +00003299/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor4b52e252009-12-21 23:17:24 +00003300/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003301///
3302/// \param ArgFunctionType the function type that will be used as the
3303/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00003304/// function template's function type. This type may be NULL, if there is no
3305/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00003306///
3307/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00003308/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00003309/// template argument deduction.
3310///
3311/// \param Info the argument will be updated to provide additional information
3312/// about template argument deduction.
3313///
3314/// \returns the result of template argument deduction.
3315Sema::TemplateDeductionResult
3316Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor67714232011-03-03 02:41:12 +00003317 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00003318 QualType ArgFunctionType,
3319 FunctionDecl *&Specialization,
3320 TemplateDeductionInfo &Info) {
Douglas Gregorae19fbb2012-09-13 21:01:57 +00003321 if (FunctionTemplate->isInvalidDecl())
3322 return TDK_Invalid;
3323
Douglas Gregor83314aa2009-07-08 20:55:45 +00003324 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3325 TemplateParameterList *TemplateParams
3326 = FunctionTemplate->getTemplateParameters();
3327 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003328
Douglas Gregor83314aa2009-07-08 20:55:45 +00003329 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00003330 LocalInstantiationScope InstScope(*this);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003331 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor02024a92010-03-28 02:42:43 +00003332 unsigned NumExplicitlySpecified = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003333 SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00003334 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003335 if (TemplateDeductionResult Result
3336 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00003337 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00003338 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00003339 &FunctionType, Info))
3340 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00003341
3342 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00003343 }
3344
Eli Friedman59a839c2012-02-08 03:07:05 +00003345 // Unevaluated SFINAE context.
3346 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +00003347 SFINAETrap Trap(*this);
3348
John McCalleff92132010-02-02 02:21:27 +00003349 Deduced.resize(TemplateParams->size());
3350
Douglas Gregor4b52e252009-12-21 23:17:24 +00003351 if (!ArgFunctionType.isNull()) {
3352 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00003353 if (TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00003354 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00003355 FunctionType, ArgFunctionType, Info,
Douglas Gregor73b3cf62011-01-25 17:19:08 +00003356 Deduced, TDF_TopLevelParameterTypeList))
Douglas Gregor4b52e252009-12-21 23:17:24 +00003357 return Result;
3358 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00003359
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 if (TemplateDeductionResult Result
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00003361 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3362 NumExplicitlySpecified,
3363 Specialization, Info))
3364 return Result;
3365
3366 // If the requested function type does not match the actual type of the
3367 // specialization, template argument deduction fails.
3368 if (!ArgFunctionType.isNull() &&
3369 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
3370 return TDK_NonDeducedMismatch;
3371
3372 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00003373}
3374
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003375/// \brief Deduce template arguments for a templated conversion
3376/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3377/// conversion function template specialization.
3378Sema::TemplateDeductionResult
3379Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
3380 QualType ToType,
3381 CXXConversionDecl *&Specialization,
3382 TemplateDeductionInfo &Info) {
Douglas Gregorae19fbb2012-09-13 21:01:57 +00003383 if (FunctionTemplate->isInvalidDecl())
3384 return TDK_Invalid;
3385
Mike Stump1eb44332009-09-09 15:08:12 +00003386 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003387 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
3388 QualType FromType = Conv->getConversionType();
3389
3390 // Canonicalize the types for deduction.
3391 QualType P = Context.getCanonicalType(FromType);
3392 QualType A = Context.getCanonicalType(ToType);
3393
Douglas Gregor5453d932011-03-06 09:03:20 +00003394 // C++0x [temp.deduct.conv]p2:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003395 // If P is a reference type, the type referred to by P is used for
3396 // type deduction.
3397 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3398 P = PRef->getPointeeType();
3399
Douglas Gregor5453d932011-03-06 09:03:20 +00003400 // C++0x [temp.deduct.conv]p4:
3401 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003402 // for type deduction.
3403 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregor5453d932011-03-06 09:03:20 +00003404 A = ARef->getPointeeType().getUnqualifiedType();
3405 // C++ [temp.deduct.conv]p3:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003406 //
Mike Stump1eb44332009-09-09 15:08:12 +00003407 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003408 else {
3409 assert(!A->isReferenceType() && "Reference types were handled above");
3410
3411 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00003412 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003413 // of P for type deduction; otherwise,
3414 if (P->isArrayType())
3415 P = Context.getArrayDecayedType(P);
3416 // - If P is a function type, the pointer type produced by the
3417 // function-to-pointer standard conversion (4.3) is used in
3418 // place of P for type deduction; otherwise,
3419 else if (P->isFunctionType())
3420 P = Context.getPointerType(P);
3421 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003422 // P's type are ignored for type deduction.
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003423 else
3424 P = P.getUnqualifiedType();
3425
Douglas Gregor5453d932011-03-06 09:03:20 +00003426 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003427 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor5453d932011-03-06 09:03:20 +00003428 // type are ignored for type deduction. If A is a reference type, the type
3429 // referred to by A is used for type deduction.
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003430 A = A.getUnqualifiedType();
3431 }
3432
Eli Friedman59a839c2012-02-08 03:07:05 +00003433 // Unevaluated SFINAE context.
3434 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +00003435 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003436
3437 // C++ [temp.deduct.conv]p1:
3438 // Template argument deduction is done by comparing the return
3439 // type of the template conversion function (call it P) with the
3440 // type that is required as the result of the conversion (call it
3441 // A) as described in 14.8.2.4.
3442 TemplateParameterList *TemplateParams
3443 = FunctionTemplate->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003444 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00003445 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003446
3447 // C++0x [temp.deduct.conv]p4:
3448 // In general, the deduction process attempts to find template
3449 // argument values that will make the deduced A identical to
3450 // A. However, there are two cases that allow a difference:
3451 unsigned TDF = 0;
3452 // - If the original A is a reference type, A can be more
3453 // cv-qualified than the deduced A (i.e., the type referred to
3454 // by the reference)
3455 if (ToType->isReferenceType())
3456 TDF |= TDF_ParamWithReferenceType;
3457 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003458 // type that can be converted to A via a qualification
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003459 // conversion.
3460 //
3461 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3462 // both P and A are pointers or member pointers. In this case, we
3463 // just ignore cv-qualifiers completely).
3464 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor2cae1e22011-08-30 00:37:54 +00003465 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003466 TDF |= TDF_IgnoreQualifiers;
3467 if (TemplateDeductionResult Result
Sebastian Redlbb95e512012-01-17 22:49:52 +00003468 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3469 P, A, Info, Deduced, TDF))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003470 return Result;
3471
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003472 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00003473 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003474 FunctionDecl *Spec = 0;
3475 TemplateDeductionResult Result
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003476 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
Douglas Gregor02024a92010-03-28 02:42:43 +00003477 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003478 Specialization = cast_or_null<CXXConversionDecl>(Spec);
3479 return Result;
3480}
3481
Douglas Gregor4b52e252009-12-21 23:17:24 +00003482/// \brief Deduce template arguments for a function template when there is
3483/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3484///
3485/// \param FunctionTemplate the function template for which we are performing
3486/// template argument deduction.
3487///
James Dennett40ae6662012-06-22 08:52:37 +00003488/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor4b52e252009-12-21 23:17:24 +00003489/// arguments.
3490///
3491/// \param Specialization if template argument deduction was successful,
3492/// this will be set to the function template specialization produced by
3493/// template argument deduction.
3494///
3495/// \param Info the argument will be updated to provide additional information
3496/// about template argument deduction.
3497///
3498/// \returns the result of template argument deduction.
3499Sema::TemplateDeductionResult
3500Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor67714232011-03-03 02:41:12 +00003501 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor4b52e252009-12-21 23:17:24 +00003502 FunctionDecl *&Specialization,
3503 TemplateDeductionInfo &Info) {
3504 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3505 QualType(), Specialization, Info);
3506}
3507
Richard Smith34b41d92011-02-20 03:19:35 +00003508namespace {
3509 /// Substitute the 'auto' type specifier within a type for a given replacement
3510 /// type.
3511 class SubstituteAutoTransform :
3512 public TreeTransform<SubstituteAutoTransform> {
3513 QualType Replacement;
3514 public:
3515 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) :
3516 TreeTransform<SubstituteAutoTransform>(SemaRef), Replacement(Replacement) {
3517 }
3518 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3519 // If we're building the type pattern to deduce against, don't wrap the
3520 // substituted type in an AutoType. Certain template deduction rules
3521 // apply only when a template type parameter appears directly (and not if
3522 // the parameter is found through desugaring). For instance:
3523 // auto &&lref = lvalue;
3524 // must transform into "rvalue reference to T" not "rvalue reference to
3525 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
3526 if (isa<TemplateTypeParmType>(Replacement)) {
3527 QualType Result = Replacement;
3528 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
3529 NewTL.setNameLoc(TL.getNameLoc());
3530 return Result;
3531 } else {
3532 QualType Result = RebuildAutoType(Replacement);
3533 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3534 NewTL.setNameLoc(TL.getNameLoc());
3535 return Result;
3536 }
3537 }
Douglas Gregordfca6f52012-02-13 22:00:16 +00003538
3539 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3540 // Lambdas never need to be transformed.
3541 return E;
3542 }
Richard Smith34b41d92011-02-20 03:19:35 +00003543 };
Richard Smith8ad6c862012-07-08 04:13:07 +00003544
3545 /// Determine whether the specified type (which contains an 'auto' type
3546 /// specifier) is dependent. This is not trivial, because the 'auto' specifier
3547 /// itself claims to be type-dependent.
3548 bool isDependentAutoType(QualType Ty) {
3549 while (1) {
3550 QualType Pointee = Ty->getPointeeType();
3551 if (!Pointee.isNull()) {
3552 Ty = Pointee;
3553 } else if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()){
3554 if (MPT->getClass()->isDependentType())
3555 return true;
3556 Ty = MPT->getPointeeType();
3557 } else if (const FunctionProtoType *FPT = Ty->getAs<FunctionProtoType>()){
3558 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
3559 E = FPT->arg_type_end();
3560 I != E; ++I)
3561 if ((*I)->isDependentType())
3562 return true;
3563 Ty = FPT->getResultType();
3564 } else if (Ty->isDependentSizedArrayType()) {
3565 return true;
3566 } else if (const ArrayType *AT = Ty->getAsArrayTypeUnsafe()) {
3567 Ty = AT->getElementType();
3568 } else if (Ty->getAs<DependentSizedExtVectorType>()) {
3569 return true;
3570 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
3571 Ty = VT->getElementType();
3572 } else {
3573 break;
3574 }
3575 }
3576 assert(Ty->getAs<AutoType>() && "didn't find 'auto' in auto type");
3577 return false;
3578 }
Richard Smith34b41d92011-02-20 03:19:35 +00003579}
3580
3581/// \brief Deduce the type for an auto type-specifier (C++0x [dcl.spec.auto]p6)
3582///
3583/// \param Type the type pattern using the auto type-specifier.
3584///
3585/// \param Init the initializer for the variable whose type is to be deduced.
3586///
3587/// \param Result if type deduction was successful, this will be set to the
3588/// deduced type. This may still contain undeduced autos if the type is
Richard Smitha085da82011-03-17 16:11:59 +00003589/// dependent. This will be set to null if deduction succeeded, but auto
3590/// substitution failed; the appropriate diagnostic will already have been
3591/// produced in that case.
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003592Sema::DeduceAutoResult
John McCall32509f12011-11-15 01:35:18 +00003593Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init,
Richard Smitha085da82011-03-17 16:11:59 +00003594 TypeSourceInfo *&Result) {
John McCall32509f12011-11-15 01:35:18 +00003595 if (Init->getType()->isNonOverloadPlaceholderType()) {
3596 ExprResult result = CheckPlaceholderExpr(Init);
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003597 if (result.isInvalid()) return DAR_FailedAlreadyDiagnosed;
John McCall32509f12011-11-15 01:35:18 +00003598 Init = result.take();
3599 }
3600
Richard Smith8ad6c862012-07-08 04:13:07 +00003601 if (Init->isTypeDependent() || isDependentAutoType(Type->getType())) {
Richard Smith34b41d92011-02-20 03:19:35 +00003602 Result = Type;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003603 return DAR_Succeeded;
Richard Smith34b41d92011-02-20 03:19:35 +00003604 }
3605
3606 SourceLocation Loc = Init->getExprLoc();
3607
3608 LocalInstantiationScope InstScope(*this);
3609
3610 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth4fb86f82011-05-01 00:51:33 +00003611 TemplateTypeParmDecl *TemplParam =
3612 TemplateTypeParmDecl::Create(Context, 0, SourceLocation(), Loc, 0, 0, 0,
3613 false, false);
3614 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
3615 NamedDecl *TemplParamPtr = TemplParam;
Richard Smith483b9f32011-02-21 20:05:19 +00003616 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
3617 Loc);
3618
Richard Smitha085da82011-03-17 16:11:59 +00003619 TypeSourceInfo *FuncParamInfo =
Richard Smith34b41d92011-02-20 03:19:35 +00003620 SubstituteAutoTransform(*this, TemplArg).TransformType(Type);
Richard Smitha085da82011-03-17 16:11:59 +00003621 assert(FuncParamInfo && "substituting template parameter for 'auto' failed");
3622 QualType FuncParam = FuncParamInfo->getType();
Richard Smith34b41d92011-02-20 03:19:35 +00003623
3624 // Deduce type of TemplParam in Func(Init)
Chris Lattner5f9e2722011-07-23 10:55:15 +00003625 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith34b41d92011-02-20 03:19:35 +00003626 Deduced.resize(1);
3627 QualType InitType = Init->getType();
3628 unsigned TDF = 0;
Richard Smith34b41d92011-02-20 03:19:35 +00003629
Craig Topper93e45992012-09-19 02:26:47 +00003630 TemplateDeductionInfo Info(Loc);
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003631
Richard Smith8ad6c862012-07-08 04:13:07 +00003632 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003633 if (InitList) {
3634 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith8ad6c862012-07-08 04:13:07 +00003635 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
Douglas Gregord2803892012-04-04 05:10:53 +00003636 TemplArg,
3637 InitList->getInit(i),
3638 Info, Deduced, TDF))
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003639 return DAR_Failed;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003640 }
3641 } else {
Douglas Gregord2803892012-04-04 05:10:53 +00003642 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
3643 FuncParam, InitType, Init,
3644 TDF))
3645 return DAR_Failed;
Richard Smith8ad6c862012-07-08 04:13:07 +00003646
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003647 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
3648 InitType, Info, Deduced, TDF))
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003649 return DAR_Failed;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003650 }
Richard Smith34b41d92011-02-20 03:19:35 +00003651
Eli Friedman70a01892012-11-06 23:56:42 +00003652 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003653 return DAR_Failed;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003654
Eli Friedman70a01892012-11-06 23:56:42 +00003655 QualType DeducedType = Deduced[0].getAsType();
3656
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003657 if (InitList) {
3658 DeducedType = BuildStdInitializerList(DeducedType, Loc);
3659 if (DeducedType.isNull())
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003660 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003661 }
3662
Richard Smith34b41d92011-02-20 03:19:35 +00003663 Result = SubstituteAutoTransform(*this, DeducedType).TransformType(Type);
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003664
Douglas Gregor9a636e82011-06-17 05:31:46 +00003665 // Check that the deduced argument type is compatible with the original
3666 // argument type per C++ [temp.deduct.call]p4.
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003667 if (!InitList && Result &&
Douglas Gregor9a636e82011-06-17 05:31:46 +00003668 CheckOriginalCallArgDeduction(*this,
3669 Sema::OriginalCallArg(FuncParam,0,InitType),
3670 Result->getType())) {
3671 Result = 0;
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003672 return DAR_Failed;
Douglas Gregor9a636e82011-06-17 05:31:46 +00003673 }
3674
Sebastian Redlb832f6d2012-01-23 22:09:39 +00003675 return DAR_Succeeded;
Richard Smith34b41d92011-02-20 03:19:35 +00003676}
3677
Sebastian Redl62b7cfb2012-01-17 22:50:08 +00003678void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
3679 if (isa<InitListExpr>(Init))
3680 Diag(VDecl->getLocation(),
3681 diag::err_auto_var_deduction_failure_from_init_list)
3682 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
3683 else
3684 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
3685 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
3686 << Init->getSourceRange();
3687}
3688
Douglas Gregor8a514912009-09-14 18:39:43 +00003689static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003690MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore73bb602009-09-14 21:25:05 +00003691 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003692 unsigned Level,
Benjamin Kramer013b3662012-01-30 16:17:39 +00003693 llvm::SmallBitVector &Deduced);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003694
3695/// \brief If this is a non-static member function,
Eli Friedman407c8472012-09-19 23:52:13 +00003696static void AddImplicitObjectParameterType(ASTContext &Context,
Douglas Gregor77bc5722010-11-12 23:44:13 +00003697 CXXMethodDecl *Method,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003698 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedman407c8472012-09-19 23:52:13 +00003699 // C++11 [temp.func.order]p3:
3700 // [...] The new parameter is of type "reference to cv A," where cv are
3701 // the cv-qualifiers of the function template (if any) and A is
3702 // the class of which the function template is a member.
Douglas Gregor77bc5722010-11-12 23:44:13 +00003703 //
Eli Friedman407c8472012-09-19 23:52:13 +00003704 // The standard doesn't say explicitly, but we pick the appropriate kind of
3705 // reference type based on [over.match.funcs]p4.
Douglas Gregor77bc5722010-11-12 23:44:13 +00003706 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
3707 ArgTy = Context.getQualifiedType(ArgTy,
3708 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedman407c8472012-09-19 23:52:13 +00003709 if (Method->getRefQualifier() == RQ_RValue)
3710 ArgTy = Context.getRValueReferenceType(ArgTy);
3711 else
3712 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor77bc5722010-11-12 23:44:13 +00003713 ArgTypes.push_back(ArgTy);
3714}
3715
Douglas Gregor8a514912009-09-14 18:39:43 +00003716/// \brief Determine whether the function template \p FT1 is at least as
3717/// specialized as \p FT2.
3718static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00003719 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003720 FunctionTemplateDecl *FT1,
3721 FunctionTemplateDecl *FT2,
3722 TemplatePartialOrderingContext TPOC,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003723 unsigned NumCallArguments,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003724 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003725 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003726 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor8a514912009-09-14 18:39:43 +00003727 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
3728 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003729
Douglas Gregor8a514912009-09-14 18:39:43 +00003730 assert(Proto1 && Proto2 && "Function templates must have prototypes");
3731 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003732 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00003733 Deduced.resize(TemplateParams->size());
3734
3735 // C++0x [temp.deduct.partial]p3:
3736 // The types used to determine the ordering depend on the context in which
3737 // the partial ordering is done:
Craig Topper93e45992012-09-19 02:26:47 +00003738 TemplateDeductionInfo Info(Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003739 CXXMethodDecl *Method1 = 0;
3740 CXXMethodDecl *Method2 = 0;
3741 bool IsNonStatic2 = false;
3742 bool IsNonStatic1 = false;
3743 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003744 switch (TPOC) {
3745 case TPOC_Call: {
3746 // - In the context of a function call, the function parameter types are
3747 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003748 Method1 = dyn_cast<CXXMethodDecl>(FD1);
3749 Method2 = dyn_cast<CXXMethodDecl>(FD2);
3750 IsNonStatic1 = Method1 && !Method1->isStatic();
3751 IsNonStatic2 = Method2 && !Method2->isStatic();
3752
Eli Friedman9cef0062012-09-19 23:27:04 +00003753 // C++11 [temp.func.order]p3:
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003754 // [...] If only one of the function templates is a non-static
3755 // member, that function template is considered to have a new
3756 // first parameter inserted in its function parameter list. The
3757 // new parameter is of type "reference to cv A," where cv are
3758 // the cv-qualifiers of the function template (if any) and A is
3759 // the class of which the function template is a member.
3760 //
Eli Friedman9cef0062012-09-19 23:27:04 +00003761 // Note that we interpret this to mean "if one of the function
3762 // templates is a non-static member and the other is a non-member";
3763 // otherwise, the ordering rules for static functions against non-static
3764 // functions don't make any sense.
3765 //
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003766 // C++98/03 doesn't have this provision, so instead we drop the
Eli Friedman9cef0062012-09-19 23:27:04 +00003767 // first argument of the free function, which seems to match
3768 // existing practice.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003769 SmallVector<QualType, 4> Args1;
Eli Friedman9cef0062012-09-19 23:27:04 +00003770 unsigned Skip1 = !S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !Method1;
3771 if (S.getLangOpts().CPlusPlus0x && IsNonStatic1 && !Method2)
Eli Friedman407c8472012-09-19 23:52:13 +00003772 AddImplicitObjectParameterType(S.Context, Method1, Args1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003773 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003774 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00003775
Chris Lattner5f9e2722011-07-23 10:55:15 +00003776 SmallVector<QualType, 4> Args2;
Eli Friedman9cef0062012-09-19 23:27:04 +00003777 Skip2 = !S.getLangOpts().CPlusPlus0x && IsNonStatic1 && !Method2;
3778 if (S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !Method1)
Eli Friedman407c8472012-09-19 23:52:13 +00003779 AddImplicitObjectParameterType(S.Context, Method2, Args2);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003780 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003781 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003782
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003783 // C++ [temp.func.order]p5:
3784 // The presence of unused ellipsis and default arguments has no effect on
3785 // the partial ordering of function templates.
3786 if (Args1.size() > NumCallArguments)
3787 Args1.resize(NumCallArguments);
3788 if (Args2.size() > NumCallArguments)
3789 Args2.resize(NumCallArguments);
3790 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
3791 Args1.data(), Args1.size(), Info, Deduced,
3792 TDF_None, /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003793 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003794 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003795
Douglas Gregor8a514912009-09-14 18:39:43 +00003796 break;
3797 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003798
Douglas Gregor8a514912009-09-14 18:39:43 +00003799 case TPOC_Conversion:
3800 // - In the context of a call to a conversion operator, the return types
3801 // of the conversion function templates are used.
Sebastian Redlbb95e512012-01-17 22:49:52 +00003802 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
3803 Proto2->getResultType(),
3804 Proto1->getResultType(),
3805 Info, Deduced, TDF_None,
3806 /*PartialOrdering=*/true,
3807 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003808 return false;
3809 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003810
Douglas Gregor8a514912009-09-14 18:39:43 +00003811 case TPOC_Other:
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003812 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor8a514912009-09-14 18:39:43 +00003813 // is used.
Sebastian Redlbb95e512012-01-17 22:49:52 +00003814 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
3815 FD2->getType(), FD1->getType(),
3816 Info, Deduced, TDF_None,
3817 /*PartialOrdering=*/true,
3818 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003819 return false;
3820 break;
3821 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003822
Douglas Gregor8a514912009-09-14 18:39:43 +00003823 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003824 // In most cases, all template parameters must have values in order for
3825 // deduction to succeed, but for partial ordering purposes a template
3826 // parameter may remain without a value provided it is not used in the
Douglas Gregor8a514912009-09-14 18:39:43 +00003827 // types being used for partial ordering. [ Note: a template parameter used
3828 // in a non-deduced context is considered used. -end note]
3829 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3830 for (; ArgIdx != NumArgs; ++ArgIdx)
3831 if (Deduced[ArgIdx].isNull())
3832 break;
3833
3834 if (ArgIdx == NumArgs) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003835 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor8a514912009-09-14 18:39:43 +00003836 // as FT2.
3837 return true;
3838 }
3839
Douglas Gregore73bb602009-09-14 21:25:05 +00003840 // Figure out which template parameters were used.
Benjamin Kramer013b3662012-01-30 16:17:39 +00003841 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor8a514912009-09-14 18:39:43 +00003842 switch (TPOC) {
3843 case TPOC_Call: {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844 unsigned NumParams = std::min(NumCallArguments,
3845 std::min(Proto1->getNumArgs(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003846 Proto2->getNumArgs()));
David Blaikie4e4d0842012-03-11 07:00:24 +00003847 if (S.getLangOpts().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003848 ::MarkUsedTemplateParameters(S.Context, Method2->getThisType(S.Context),
3849 false,
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003850 TemplateParams->getDepth(), UsedParameters);
3851 for (unsigned I = Skip2; I < NumParams; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003852 ::MarkUsedTemplateParameters(S.Context, Proto2->getArgType(I), false,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003853 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003854 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003855 break;
3856 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857
Douglas Gregor8a514912009-09-14 18:39:43 +00003858 case TPOC_Conversion:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003859 ::MarkUsedTemplateParameters(S.Context, Proto2->getResultType(), false,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003860 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003861 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003862 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003863
Douglas Gregor8a514912009-09-14 18:39:43 +00003864 case TPOC_Other:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00003865 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003866 TemplateParams->getDepth(),
3867 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003868 break;
3869 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003870
Douglas Gregor8a514912009-09-14 18:39:43 +00003871 for (; ArgIdx != NumArgs; ++ArgIdx)
3872 // If this argument had no value deduced but was used in one of the types
3873 // used for partial ordering, then deduction fails.
3874 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3875 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003876
Douglas Gregor8a514912009-09-14 18:39:43 +00003877 return true;
3878}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003879
Douglas Gregor9da95e62011-01-16 16:03:23 +00003880/// \brief Determine whether this a function template whose parameter-type-list
3881/// ends with a function parameter pack.
3882static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
3883 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3884 unsigned NumParams = Function->getNumParams();
3885 if (NumParams == 0)
3886 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887
Douglas Gregor9da95e62011-01-16 16:03:23 +00003888 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
3889 if (!Last->isParameterPack())
3890 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003891
Douglas Gregor9da95e62011-01-16 16:03:23 +00003892 // Make sure that no previous parameter is a parameter pack.
3893 while (--NumParams > 0) {
3894 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
3895 return false;
3896 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003897
Douglas Gregor9da95e62011-01-16 16:03:23 +00003898 return true;
3899}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003900
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003901/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003902/// to the rules of function template partial ordering (C++ [temp.func.order]).
3903///
3904/// \param FT1 the first function template
3905///
3906/// \param FT2 the second function template
3907///
Douglas Gregor8a514912009-09-14 18:39:43 +00003908/// \param TPOC the context in which we are performing partial ordering of
3909/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003910///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003911/// \param NumCallArguments The number of arguments in a call, used only
3912/// when \c TPOC is \c TPOC_Call.
3913///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003914/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003915/// template is more specialized, returns NULL.
3916FunctionTemplateDecl *
3917Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3918 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003919 SourceLocation Loc,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003920 TemplatePartialOrderingContext TPOC,
3921 unsigned NumCallArguments) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003922 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003923 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003924 NumCallArguments, 0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003925 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003926 NumCallArguments,
Douglas Gregorb939a192011-01-21 17:29:42 +00003927 &RefParamComparisons);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003928
Douglas Gregor8a514912009-09-14 18:39:43 +00003929 if (Better1 != Better2) // We have a clear winner
3930 return Better1? FT1 : FT2;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003931
Douglas Gregor8a514912009-09-14 18:39:43 +00003932 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003933 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003934
Douglas Gregor8a514912009-09-14 18:39:43 +00003935 // C++0x [temp.deduct.partial]p10:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003936 // If for each type being considered a given template is at least as
Douglas Gregor8a514912009-09-14 18:39:43 +00003937 // specialized for all types and more specialized for some set of types and
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938 // the other template is not more specialized for any types or is not at
Douglas Gregor8a514912009-09-14 18:39:43 +00003939 // least as specialized for any types, then the given template is more
3940 // specialized than the other template. Otherwise, neither template is more
3941 // specialized than the other.
3942 Better1 = false;
3943 Better2 = false;
Douglas Gregorb939a192011-01-21 17:29:42 +00003944 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003945 // C++0x [temp.deduct.partial]p9:
3946 // If, for a given type, deduction succeeds in both directions (i.e., the
Douglas Gregorb939a192011-01-21 17:29:42 +00003947 // types are identical after the transformations above) and both P and A
3948 // were reference types (before being replaced with the type referred to
3949 // above):
3950
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003951 // -- if the type from the argument template was an lvalue reference
Douglas Gregorb939a192011-01-21 17:29:42 +00003952 // and the type from the parameter template was not, the argument
3953 // type is considered to be more specialized than the other;
3954 // otherwise,
3955 if (!RefParamComparisons[I].ArgIsRvalueRef &&
3956 RefParamComparisons[I].ParamIsRvalueRef) {
3957 Better2 = true;
3958 if (Better1)
3959 return 0;
3960 continue;
3961 } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
3962 RefParamComparisons[I].ArgIsRvalueRef) {
3963 Better1 = true;
3964 if (Better2)
3965 return 0;
3966 continue;
Douglas Gregor8a514912009-09-14 18:39:43 +00003967 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003968
Douglas Gregorb939a192011-01-21 17:29:42 +00003969 // -- if the type from the argument template is more cv-qualified than
3970 // the type from the parameter template (as described above), the
3971 // argument type is considered to be more specialized than the
3972 // other; otherwise,
3973 switch (RefParamComparisons[I].Qualifiers) {
3974 case NeitherMoreQualified:
3975 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003976
Douglas Gregorb939a192011-01-21 17:29:42 +00003977 case ParamMoreQualified:
3978 Better1 = true;
3979 if (Better2)
3980 return 0;
3981 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003982
Douglas Gregorb939a192011-01-21 17:29:42 +00003983 case ArgMoreQualified:
3984 Better2 = true;
3985 if (Better1)
3986 return 0;
3987 continue;
3988 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003989
Douglas Gregorb939a192011-01-21 17:29:42 +00003990 // -- neither type is more specialized than the other.
Douglas Gregor8a514912009-09-14 18:39:43 +00003991 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003992
Douglas Gregor8a514912009-09-14 18:39:43 +00003993 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003994 if (Better1)
3995 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003996 else if (Better2)
3997 return FT2;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003998
Douglas Gregor9da95e62011-01-16 16:03:23 +00003999 // FIXME: This mimics what GCC implements, but doesn't match up with the
4000 // proposed resolution for core issue 692. This area needs to be sorted out,
4001 // but for now we attempt to maintain compatibility.
4002 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4003 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4004 if (Variadic1 != Variadic2)
4005 return Variadic1? FT2 : FT1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004006
Douglas Gregor9da95e62011-01-16 16:03:23 +00004007 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004008}
Douglas Gregor83314aa2009-07-08 20:55:45 +00004009
Douglas Gregord5a423b2009-09-25 18:43:00 +00004010/// \brief Determine if the two templates are equivalent.
4011static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4012 if (T1 == T2)
4013 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004014
Douglas Gregord5a423b2009-09-25 18:43:00 +00004015 if (!T1 || !T2)
4016 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004017
Douglas Gregord5a423b2009-09-25 18:43:00 +00004018 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4019}
4020
4021/// \brief Retrieve the most specialized of the given function template
4022/// specializations.
4023///
John McCallc373d482010-01-27 01:50:18 +00004024/// \param SpecBegin the start iterator of the function template
4025/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004026///
John McCallc373d482010-01-27 01:50:18 +00004027/// \param SpecEnd the end iterator of the function template
4028/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004029///
4030/// \param TPOC the partial ordering context to use to compare the function
4031/// template specializations.
4032///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004033/// \param NumCallArguments The number of arguments in a call, used only
4034/// when \c TPOC is \c TPOC_Call.
4035///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004036/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregord5a423b2009-09-25 18:43:00 +00004037/// diagnostic should occur.
4038///
4039/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4040/// no matching candidates.
4041///
4042/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4043/// occurs.
4044///
4045/// \param CandidateDiag partial diagnostic used for each function template
4046/// specialization that is a candidate in the ambiguous ordering. One parameter
4047/// in this diagnostic should be unbound, which will correspond to the string
4048/// describing the template arguments for the function template specialization.
4049///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004050/// \param Index if non-NULL and the result of this function is non-nULL,
Douglas Gregord5a423b2009-09-25 18:43:00 +00004051/// receives the index corresponding to the resulting function template
4052/// specialization.
4053///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004054/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00004055/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00004056///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004057/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
Douglas Gregord5a423b2009-09-25 18:43:00 +00004058/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00004059UnresolvedSetIterator
4060Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004061 UnresolvedSetIterator SpecEnd,
John McCallc373d482010-01-27 01:50:18 +00004062 TemplatePartialOrderingContext TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004063 unsigned NumCallArguments,
John McCallc373d482010-01-27 01:50:18 +00004064 SourceLocation Loc,
4065 const PartialDiagnostic &NoneDiag,
4066 const PartialDiagnostic &AmbigDiag,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004067 const PartialDiagnostic &CandidateDiag,
Richard Trieu6efd4c52011-11-23 22:32:32 +00004068 bool Complain,
4069 QualType TargetType) {
John McCallc373d482010-01-27 01:50:18 +00004070 if (SpecBegin == SpecEnd) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004071 if (Complain)
4072 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00004073 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004074 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004075
4076 if (SpecBegin + 1 == SpecEnd)
John McCallc373d482010-01-27 01:50:18 +00004077 return SpecBegin;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004078
Douglas Gregord5a423b2009-09-25 18:43:00 +00004079 // Find the function template that is better than all of the templates it
4080 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00004081 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004082 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00004083 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004084 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00004085 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4086 FunctionTemplateDecl *Challenger
4087 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004088 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00004089 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004090 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004091 Challenger)) {
4092 Best = I;
4093 BestTemplate = Challenger;
4094 }
4095 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004096
Douglas Gregord5a423b2009-09-25 18:43:00 +00004097 // Make sure that the "best" function template is more specialized than all
4098 // of the others.
4099 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00004100 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4101 FunctionTemplateDecl *Challenger
4102 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00004103 if (I != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004104 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004105 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00004106 BestTemplate)) {
4107 Ambiguous = true;
4108 break;
4109 }
4110 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004111
Douglas Gregord5a423b2009-09-25 18:43:00 +00004112 if (!Ambiguous) {
4113 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00004114 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004115 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004116
Douglas Gregord5a423b2009-09-25 18:43:00 +00004117 // Diagnose the ambiguity.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004118 if (Complain)
4119 Diag(Loc, AmbigDiag);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004120
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004121 if (Complain)
Douglas Gregord5a423b2009-09-25 18:43:00 +00004122 // FIXME: Can we order the candidates in some sane way?
Richard Trieu6efd4c52011-11-23 22:32:32 +00004123 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4124 PartialDiagnostic PD = CandidateDiag;
4125 PD << getTemplateArgumentBindingsText(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004126 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCallc373d482010-01-27 01:50:18 +00004127 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieu6efd4c52011-11-23 22:32:32 +00004128 if (!TargetType.isNull())
4129 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4130 TargetType);
4131 Diag((*I)->getLocation(), PD);
4132 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004133
John McCallc373d482010-01-27 01:50:18 +00004134 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00004135}
4136
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004137/// \brief Returns the more specialized class template partial specialization
4138/// according to the rules of partial ordering of class template partial
4139/// specializations (C++ [temp.class.order]).
4140///
4141/// \param PS1 the first class template partial specialization
4142///
4143/// \param PS2 the second class template partial specialization
4144///
4145/// \returns the more specialized class template partial specialization. If
4146/// neither partial specialization is more specialized, returns NULL.
4147ClassTemplatePartialSpecializationDecl *
4148Sema::getMoreSpecializedPartialSpecialization(
4149 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00004150 ClassTemplatePartialSpecializationDecl *PS2,
4151 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004152 // C++ [temp.class.order]p1:
4153 // For two class template partial specializations, the first is at least as
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004154 // specialized as the second if, given the following rewrite to two
4155 // function templates, the first function template is at least as
4156 // specialized as the second according to the ordering rules for function
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004157 // templates (14.6.6.2):
4158 // - the first function template has the same template parameters as the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004159 // first partial specialization and has a single function parameter
4160 // whose type is a class template specialization with the template
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004161 // arguments of the first partial specialization, and
4162 // - the second function template has the same template parameters as the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004163 // second partial specialization and has a single function parameter
4164 // whose type is a class template specialization with the template
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004165 // arguments of the second partial specialization.
4166 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00004167 // Rather than synthesize function templates, we merely perform the
4168 // equivalent partial ordering by performing deduction directly on
4169 // the template arguments of the class template partial
4170 // specializations. This computation is slightly simpler than the
4171 // general problem of function template partial ordering, because
4172 // class template partial specializations are more constrained. We
4173 // know that every template parameter is deducible from the class
4174 // template partial specialization's template arguments, for
4175 // example.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004176 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Topper93e45992012-09-19 02:26:47 +00004177 TemplateDeductionInfo Info(Loc);
John McCall31f17ec2010-04-27 00:57:59 +00004178
4179 QualType PT1 = PS1->getInjectedSpecializationType();
4180 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004181
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004182 // Determine whether PS1 is at least as specialized as PS2
4183 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlbb95e512012-01-17 22:49:52 +00004184 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4185 PS2->getTemplateParameters(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004186 PT2, PT1, Info, Deduced, TDF_None,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004187 /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00004188 /*RefParamComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004189 if (Better1) {
Richard Smith7e54fb52012-07-16 01:09:10 +00004190 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004191 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
Richard Smith7e54fb52012-07-16 01:09:10 +00004192 DeducedArgs, Info);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004193 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4194 PS1->getTemplateArgs(),
Douglas Gregor516e6e02010-04-29 06:31:36 +00004195 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004196 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004197
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004198 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00004199 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004200 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlbb95e512012-01-17 22:49:52 +00004201 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4202 PS1->getTemplateParameters(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00004203 PT1, PT2, Info, Deduced, TDF_None,
4204 /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00004205 /*RefParamComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004206 if (Better2) {
Richard Smith7e54fb52012-07-16 01:09:10 +00004207 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004208 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
Richard Smith7e54fb52012-07-16 01:09:10 +00004209 DeducedArgs, Info);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004210 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4211 PS2->getTemplateArgs(),
Douglas Gregor516e6e02010-04-29 06:31:36 +00004212 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00004213 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004214
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004215 if (Better1 == Better2)
4216 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004217
Douglas Gregorbf4ea562009-09-15 16:23:51 +00004218 return Better1? PS1 : PS2;
4219}
4220
Mike Stump1eb44332009-09-09 15:08:12 +00004221static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004222MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004223 const TemplateArgument &TemplateArg,
4224 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004225 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004226 llvm::SmallBitVector &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004227
Douglas Gregore73bb602009-09-14 21:25:05 +00004228/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00004229/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00004230static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004231MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004232 const Expr *E,
4233 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004234 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004235 llvm::SmallBitVector &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00004236 // We can deduce from a pack expansion.
4237 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4238 E = Expansion->getPattern();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004239
Richard Smith60983812012-07-09 03:07:20 +00004240 // Skip through any implicit casts we added while type-checking, and any
4241 // substitutions performed by template alias expansion.
4242 while (1) {
4243 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4244 E = ICE->getSubExpr();
4245 else if (const SubstNonTypeTemplateParmExpr *Subst =
4246 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4247 E = Subst->getReplacement();
4248 else
4249 break;
4250 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004251
4252 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore73bb602009-09-14 21:25:05 +00004253 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00004254 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00004255 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00004256 return;
4257
Mike Stump1eb44332009-09-09 15:08:12 +00004258 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00004259 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4260 if (!NTTP)
4261 return;
4262
Douglas Gregored9c0f92009-10-29 00:04:11 +00004263 if (NTTP->getDepth() == Depth)
4264 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00004265}
4266
Douglas Gregore73bb602009-09-14 21:25:05 +00004267/// \brief Mark the template parameters that are used by the given
4268/// nested name specifier.
4269static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004270MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004271 NestedNameSpecifier *NNS,
4272 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004273 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004274 llvm::SmallBitVector &Used) {
Douglas Gregore73bb602009-09-14 21:25:05 +00004275 if (!NNS)
4276 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004277
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004278 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004279 Used);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004280 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004281 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004282}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004283
Douglas Gregore73bb602009-09-14 21:25:05 +00004284/// \brief Mark the template parameters that are used by the given
4285/// template name.
4286static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004287MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004288 TemplateName Name,
4289 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004290 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004291 llvm::SmallBitVector &Used) {
Douglas Gregore73bb602009-09-14 21:25:05 +00004292 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4293 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00004294 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4295 if (TTP->getDepth() == Depth)
4296 Used[TTP->getIndex()] = true;
4297 }
Douglas Gregore73bb602009-09-14 21:25:05 +00004298 return;
4299 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004300
Douglas Gregor788cd062009-11-11 01:00:40 +00004301 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004302 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor788cd062009-11-11 01:00:40 +00004303 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004304 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004305 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004306 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004307}
4308
4309/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00004310/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004311static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004312MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore73bb602009-09-14 21:25:05 +00004313 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004314 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004315 llvm::SmallBitVector &Used) {
Douglas Gregore73bb602009-09-14 21:25:05 +00004316 if (T.isNull())
4317 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004318
Douglas Gregor031a5882009-06-13 00:26:55 +00004319 // Non-dependent types have nothing deducible
4320 if (!T->isDependentType())
4321 return;
4322
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004323 T = Ctx.getCanonicalType(T);
Douglas Gregor031a5882009-06-13 00:26:55 +00004324 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00004325 case Type::Pointer:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004326 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004327 cast<PointerType>(T)->getPointeeType(),
4328 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004329 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00004330 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004331 break;
4332
4333 case Type::BlockPointer:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004334 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004335 cast<BlockPointerType>(T)->getPointeeType(),
4336 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004337 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00004338 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004339 break;
4340
4341 case Type::LValueReference:
4342 case Type::RValueReference:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004343 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004344 cast<ReferenceType>(T)->getPointeeType(),
4345 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004346 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00004347 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004348 break;
4349
4350 case Type::MemberPointer: {
4351 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004352 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004353 Depth, Used);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004354 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004355 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004356 break;
4357 }
4358
4359 case Type::DependentSizedArray:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004360 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004361 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004362 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004363 // Fall through to check the element type
4364
4365 case Type::ConstantArray:
4366 case Type::IncompleteArray:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004367 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004368 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004369 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004370 break;
4371
4372 case Type::Vector:
4373 case Type::ExtVector:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004374 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004375 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004376 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004377 break;
4378
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004379 case Type::DependentSizedExtVector: {
4380 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00004381 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004382 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004383 Depth, Used);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004384 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004385 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00004386 break;
4387 }
4388
Douglas Gregor031a5882009-06-13 00:26:55 +00004389 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00004390 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004391 MarkUsedTemplateParameters(Ctx, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004392 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004393 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004394 MarkUsedTemplateParameters(Ctx, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004395 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004396 break;
4397 }
4398
Douglas Gregored9c0f92009-10-29 00:04:11 +00004399 case Type::TemplateTypeParm: {
4400 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4401 if (TTP->getDepth() == Depth)
4402 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00004403 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00004404 }
Douglas Gregor031a5882009-06-13 00:26:55 +00004405
Douglas Gregor0bc15d92011-01-14 05:11:40 +00004406 case Type::SubstTemplateTypeParmPack: {
4407 const SubstTemplateTypeParmPackType *Subst
4408 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004409 MarkUsedTemplateParameters(Ctx,
Douglas Gregor0bc15d92011-01-14 05:11:40 +00004410 QualType(Subst->getReplacedParameter(), 0),
4411 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004412 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregor0bc15d92011-01-14 05:11:40 +00004413 OnlyDeduced, Depth, Used);
4414 break;
4415 }
4416
John McCall31f17ec2010-04-27 00:57:59 +00004417 case Type::InjectedClassName:
4418 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4419 // fall through
4420
Douglas Gregor031a5882009-06-13 00:26:55 +00004421 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00004422 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00004423 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004424 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004425 Depth, Used);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004426
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004427 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004428 // If the template argument list of P contains a pack expansion that is not
4429 // the last template argument, the entire template argument list is a
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004430 // non-deduced context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004431 if (OnlyDeduced &&
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004432 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4433 break;
4434
Douglas Gregore73bb602009-09-14 21:25:05 +00004435 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004436 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004437 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004438 break;
4439 }
4440
Douglas Gregore73bb602009-09-14 21:25:05 +00004441 case Type::Complex:
4442 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004443 MarkUsedTemplateParameters(Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004444 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004445 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004446 break;
4447
Eli Friedmanb001de72011-10-06 23:00:33 +00004448 case Type::Atomic:
4449 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004450 MarkUsedTemplateParameters(Ctx,
Eli Friedmanb001de72011-10-06 23:00:33 +00004451 cast<AtomicType>(T)->getValueType(),
4452 OnlyDeduced, Depth, Used);
4453 break;
4454
Douglas Gregor4714c122010-03-31 17:34:00 +00004455 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00004456 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004457 MarkUsedTemplateParameters(Ctx,
Douglas Gregor4714c122010-03-31 17:34:00 +00004458 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004459 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00004460 break;
4461
John McCall33500952010-06-11 00:33:02 +00004462 case Type::DependentTemplateSpecialization: {
4463 const DependentTemplateSpecializationType *Spec
4464 = cast<DependentTemplateSpecializationType>(T);
4465 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004466 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00004467 OnlyDeduced, Depth, Used);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004468
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004469 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004470 // If the template argument list of P contains a pack expansion that is not
4471 // the last template argument, the entire template argument list is a
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004472 // non-deduced context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004473 if (OnlyDeduced &&
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004474 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4475 break;
4476
John McCall33500952010-06-11 00:33:02 +00004477 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004478 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCall33500952010-06-11 00:33:02 +00004479 Used);
4480 break;
4481 }
4482
John McCallad5e7382010-03-01 23:49:17 +00004483 case Type::TypeOf:
4484 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004485 MarkUsedTemplateParameters(Ctx,
John McCallad5e7382010-03-01 23:49:17 +00004486 cast<TypeOfType>(T)->getUnderlyingType(),
4487 OnlyDeduced, Depth, Used);
4488 break;
4489
4490 case Type::TypeOfExpr:
4491 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004492 MarkUsedTemplateParameters(Ctx,
John McCallad5e7382010-03-01 23:49:17 +00004493 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4494 OnlyDeduced, Depth, Used);
4495 break;
4496
4497 case Type::Decltype:
4498 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004499 MarkUsedTemplateParameters(Ctx,
John McCallad5e7382010-03-01 23:49:17 +00004500 cast<DecltypeType>(T)->getUnderlyingExpr(),
4501 OnlyDeduced, Depth, Used);
4502 break;
4503
Sean Huntca63c202011-05-24 22:41:36 +00004504 case Type::UnaryTransform:
4505 if (!OnlyDeduced)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004506 MarkUsedTemplateParameters(Ctx,
Sean Huntca63c202011-05-24 22:41:36 +00004507 cast<UnaryTransformType>(T)->getUnderlyingType(),
4508 OnlyDeduced, Depth, Used);
4509 break;
4510
Douglas Gregor7536dd52010-12-20 02:24:11 +00004511 case Type::PackExpansion:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004512 MarkUsedTemplateParameters(Ctx,
Douglas Gregor7536dd52010-12-20 02:24:11 +00004513 cast<PackExpansionType>(T)->getPattern(),
4514 OnlyDeduced, Depth, Used);
4515 break;
4516
Richard Smith34b41d92011-02-20 03:19:35 +00004517 case Type::Auto:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004518 MarkUsedTemplateParameters(Ctx,
Richard Smith34b41d92011-02-20 03:19:35 +00004519 cast<AutoType>(T)->getDeducedType(),
4520 OnlyDeduced, Depth, Used);
4521
Douglas Gregore73bb602009-09-14 21:25:05 +00004522 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00004523 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00004524 case Type::VariableArray:
4525 case Type::FunctionNoProto:
4526 case Type::Record:
4527 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00004528 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00004529 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00004530 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00004531 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00004532#define TYPE(Class, Base)
4533#define ABSTRACT_TYPE(Class, Base)
4534#define DEPENDENT_TYPE(Class, Base)
4535#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4536#include "clang/AST/TypeNodes.def"
4537 break;
4538 }
4539}
4540
Douglas Gregore73bb602009-09-14 21:25:05 +00004541/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00004542/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00004543static void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004544MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore73bb602009-09-14 21:25:05 +00004545 const TemplateArgument &TemplateArg,
4546 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004547 unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004548 llvm::SmallBitVector &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00004549 switch (TemplateArg.getKind()) {
4550 case TemplateArgument::Null:
4551 case TemplateArgument::Integral:
Douglas Gregord2008e22012-04-06 22:40:38 +00004552 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00004553 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004554
Eli Friedmand7a6b162012-09-26 02:36:12 +00004555 case TemplateArgument::NullPtr:
4556 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4557 Depth, Used);
4558 break;
4559
Douglas Gregor031a5882009-06-13 00:26:55 +00004560 case TemplateArgument::Type:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004561 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004562 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004563 break;
4564
Douglas Gregor788cd062009-11-11 01:00:40 +00004565 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00004566 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004567 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004568 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00004569 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004570 break;
4571
4572 case TemplateArgument::Expression:
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004573 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004574 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004575 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004576
Anders Carlssond01b1da2009-06-15 17:04:53 +00004577 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00004578 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
4579 PEnd = TemplateArg.pack_end();
4580 P != PEnd; ++P)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004581 MarkUsedTemplateParameters(Ctx, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00004582 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00004583 }
4584}
4585
James Dennett16ae9de2012-06-22 10:16:05 +00004586/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor031a5882009-06-13 00:26:55 +00004587/// template argument list.
4588///
4589/// \param TemplateArgs the template argument list from which template
4590/// parameters will be deduced.
4591///
James Dennett16ae9de2012-06-22 10:16:05 +00004592/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor031a5882009-06-13 00:26:55 +00004593/// to indicate when the corresponding template parameter will be
4594/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00004595void
Douglas Gregore73bb602009-09-14 21:25:05 +00004596Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004597 bool OnlyDeduced, unsigned Depth,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004598 llvm::SmallBitVector &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004599 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004600 // If the template argument list of P contains a pack expansion that is not
4601 // the last template argument, the entire template argument list is a
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004602 // non-deduced context.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004603 if (OnlyDeduced &&
Douglas Gregor7b976ec2010-12-23 01:24:45 +00004604 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
4605 return;
4606
Douglas Gregor031a5882009-06-13 00:26:55 +00004607 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004608 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004609 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00004610}
Douglas Gregor63f07c52009-09-18 23:21:38 +00004611
4612/// \brief Marks all of the template parameters that will be deduced by a
4613/// call to the given function template.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004614void
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004615Sema::MarkDeducedTemplateParameters(ASTContext &Ctx,
4616 FunctionTemplateDecl *FunctionTemplate,
Benjamin Kramer013b3662012-01-30 16:17:39 +00004617 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004618 TemplateParameterList *TemplateParams
Douglas Gregor63f07c52009-09-18 23:21:38 +00004619 = FunctionTemplate->getTemplateParameters();
4620 Deduced.clear();
4621 Deduced.resize(TemplateParams->size());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004622
Douglas Gregor63f07c52009-09-18 23:21:38 +00004623 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4624 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004625 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00004626 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00004627}
Douglas Gregordbfb3712011-06-16 16:50:48 +00004628
4629bool hasDeducibleTemplateParameters(Sema &S,
4630 FunctionTemplateDecl *FunctionTemplate,
4631 QualType T) {
4632 if (!T->isDependentType())
4633 return false;
4634
4635 TemplateParameterList *TemplateParams
4636 = FunctionTemplate->getTemplateParameters();
Benjamin Kramer013b3662012-01-30 16:17:39 +00004637 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidis6fc9e1d2012-01-17 02:15:41 +00004638 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregordbfb3712011-06-16 16:50:48 +00004639 Deduced);
4640
Benjamin Kramer013b3662012-01-30 16:17:39 +00004641 return Deduced.any();
Douglas Gregordbfb3712011-06-16 16:50:48 +00004642}