blob: 00d92bc6b535e7da4ac8e2ee1318adeb49fd678d [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"
Douglas Gregor20a55e22010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
Douglas Gregore02e2622010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.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
54 /// parameters and arguments in a top-level template argument
55 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,
Douglas Gregor0972c862010-12-22 18:55:49 +000088 llvm::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.
Douglas Gregor5c7bf422011-01-11 17:34:58 +000093enum DeductionQualifierComparison {
94 NeitherMoreQualified = 0,
95 ParamMoreQualified,
96 ArgMoreQualified
97};
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
101/// templates.
102struct 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;
107
108 /// \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
115DeduceTemplateArguments(Sema &S,
116 TemplateParameterList *TemplateParams,
Douglas Gregor603cfb42011-01-05 23:12:31 +0000117 QualType Param,
118 QualType Arg,
119 TemplateDeductionInfo &Info,
120 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000121 unsigned TDF,
122 bool PartialOrdering = false,
Douglas Gregorb939a192011-01-21 17:29:42 +0000123 llvm::SmallVectorImpl<RefParamPartialOrderingComparison> *
124 RefParamComparisons = 0);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000125
126static Sema::TemplateDeductionResult
127DeduceTemplateArguments(Sema &S,
128 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +0000129 const TemplateArgument *Params, unsigned NumParams,
130 const TemplateArgument *Args, unsigned NumArgs,
131 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000132 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
133 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000134
Douglas Gregor199d9912009-06-05 00:53:49 +0000135/// \brief If the given expression is of a form that permits the deduction
136/// of a non-type template parameter, return the declaration of that
137/// non-type template parameter.
138static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
139 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
140 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Douglas Gregor199d9912009-06-05 00:53:49 +0000142 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
143 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Douglas Gregor199d9912009-06-05 00:53:49 +0000145 return 0;
146}
147
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000148/// \brief Determine whether two declaration pointers refer to the same
149/// declaration.
150static bool isSameDeclaration(Decl *X, Decl *Y) {
151 if (!X || !Y)
152 return !X && !Y;
153
154 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
155 X = NX->getUnderlyingDecl();
156 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
157 Y = NY->getUnderlyingDecl();
158
159 return X->getCanonicalDecl() == Y->getCanonicalDecl();
160}
161
162/// \brief Verify that the given, deduced template arguments are compatible.
163///
164/// \returns The deduced template argument, or a NULL template argument if
165/// the deduced template arguments were incompatible.
166static DeducedTemplateArgument
167checkDeducedTemplateArguments(ASTContext &Context,
168 const DeducedTemplateArgument &X,
169 const DeducedTemplateArgument &Y) {
170 // We have no deduction for one or both of the arguments; they're compatible.
171 if (X.isNull())
172 return Y;
173 if (Y.isNull())
174 return X;
175
176 switch (X.getKind()) {
177 case TemplateArgument::Null:
178 llvm_unreachable("Non-deduced template arguments handled above");
179
180 case TemplateArgument::Type:
181 // If two template type arguments have the same type, they're compatible.
182 if (Y.getKind() == TemplateArgument::Type &&
183 Context.hasSameType(X.getAsType(), Y.getAsType()))
184 return X;
185
186 return DeducedTemplateArgument();
187
188 case TemplateArgument::Integral:
189 // If we deduced a constant in one case and either a dependent expression or
190 // declaration in another case, keep the integral constant.
191 // If both are integral constants with the same value, keep that value.
192 if (Y.getKind() == TemplateArgument::Expression ||
193 Y.getKind() == TemplateArgument::Declaration ||
194 (Y.getKind() == TemplateArgument::Integral &&
195 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
196 return DeducedTemplateArgument(X,
197 X.wasDeducedFromArrayBound() &&
198 Y.wasDeducedFromArrayBound());
199
200 // All other combinations are incompatible.
201 return DeducedTemplateArgument();
202
203 case TemplateArgument::Template:
204 if (Y.getKind() == TemplateArgument::Template &&
205 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
206 return X;
207
208 // All other combinations are incompatible.
209 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000210
211 case TemplateArgument::TemplateExpansion:
212 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
213 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
214 Y.getAsTemplateOrTemplatePattern()))
215 return X;
216
217 // All other combinations are incompatible.
218 return DeducedTemplateArgument();
219
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000220 case TemplateArgument::Expression:
221 // If we deduced a dependent expression in one case and either an integral
222 // constant or a declaration in another case, keep the integral constant
223 // or declaration.
224 if (Y.getKind() == TemplateArgument::Integral ||
225 Y.getKind() == TemplateArgument::Declaration)
226 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
227 Y.wasDeducedFromArrayBound());
228
229 if (Y.getKind() == TemplateArgument::Expression) {
230 // Compare the expressions for equality
231 llvm::FoldingSetNodeID ID1, ID2;
232 X.getAsExpr()->Profile(ID1, Context, true);
233 Y.getAsExpr()->Profile(ID2, Context, true);
234 if (ID1 == ID2)
235 return X;
236 }
237
238 // All other combinations are incompatible.
239 return DeducedTemplateArgument();
240
241 case TemplateArgument::Declaration:
242 // If we deduced a declaration and a dependent expression, keep the
243 // declaration.
244 if (Y.getKind() == TemplateArgument::Expression)
245 return X;
246
247 // If we deduced a declaration and an integral constant, keep the
248 // integral constant.
249 if (Y.getKind() == TemplateArgument::Integral)
250 return Y;
251
252 // If we deduced two declarations, make sure they they refer to the
253 // same declaration.
254 if (Y.getKind() == TemplateArgument::Declaration &&
255 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
256 return X;
257
258 // All other combinations are incompatible.
259 return DeducedTemplateArgument();
260
261 case TemplateArgument::Pack:
262 if (Y.getKind() != TemplateArgument::Pack ||
263 X.pack_size() != Y.pack_size())
264 return DeducedTemplateArgument();
265
266 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
267 XAEnd = X.pack_end(),
268 YA = Y.pack_begin();
269 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000270 if (checkDeducedTemplateArguments(Context,
271 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
272 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
273 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000274 return DeducedTemplateArgument();
275 }
276
277 return X;
278 }
279
280 return DeducedTemplateArgument();
281}
282
Mike Stump1eb44332009-09-09 15:08:12 +0000283/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000284/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000285static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000286DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000287 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000288 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000289 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000290 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000291 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000292 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000293 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000295 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
296 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
297 Deduced[NTTP->getIndex()],
298 NewDeduced);
299 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000300 Info.Param = NTTP;
301 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000302 Info.SecondArg = NewDeduced;
303 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000304 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000305
306 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000307 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53: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 type- or value-dependent expression.
312///
313/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000314static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000315DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000316 NonTypeTemplateParmDecl *NTTP,
317 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000318 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000319 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000320 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000321 "Cannot deduce non-type template argument with depth > 0");
322 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
323 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000324
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000325 DeducedTemplateArgument NewDeduced(Value);
326 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
327 Deduced[NTTP->getIndex()],
328 NewDeduced);
329
330 if (Result.isNull()) {
331 Info.Param = NTTP;
332 Info.FirstArg = Deduced[NTTP->getIndex()];
333 Info.SecondArg = NewDeduced;
334 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000335 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000336
337 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000338 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000339}
340
Douglas Gregor15755cb2009-11-13 23:45:44 +0000341/// \brief Deduce the value of the given non-type template parameter
342/// from the given declaration.
343///
344/// \returns true if deduction succeeded, false otherwise.
345static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000346DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000347 NonTypeTemplateParmDecl *NTTP,
348 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000349 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000350 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000351 assert(NTTP->getDepth() == 0 &&
352 "Cannot deduce non-type template argument with depth > 0");
353
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000354 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
355 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
356 Deduced[NTTP->getIndex()],
357 NewDeduced);
358 if (Result.isNull()) {
359 Info.Param = NTTP;
360 Info.FirstArg = Deduced[NTTP->getIndex()];
361 Info.SecondArg = NewDeduced;
362 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000363 }
364
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000365 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000366 return Sema::TDK_Success;
367}
368
Douglas Gregorf67875d2009-06-12 18:26:56 +0000369static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000370DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000371 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000372 TemplateName Param,
373 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000374 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000375 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000376 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000377 if (!ParamDecl) {
378 // The parameter type is dependent and is not a template template parameter,
379 // so there is nothing that we can deduce.
380 return Sema::TDK_Success;
381 }
382
383 if (TemplateTemplateParmDecl *TempParam
384 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000385 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
386 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
387 Deduced[TempParam->getIndex()],
388 NewDeduced);
389 if (Result.isNull()) {
390 Info.Param = TempParam;
391 Info.FirstArg = Deduced[TempParam->getIndex()];
392 Info.SecondArg = NewDeduced;
393 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000394 }
395
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000396 Deduced[TempParam->getIndex()] = Result;
397 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000398 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000399
400 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000401 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000402 return Sema::TDK_Success;
403
404 // Mismatch of non-dependent template parameter to argument.
405 Info.FirstArg = TemplateArgument(Param);
406 Info.SecondArg = TemplateArgument(Arg);
407 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000408}
409
Mike Stump1eb44332009-09-09 15:08:12 +0000410/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000411/// type (which is a template-id) with the template argument type.
412///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000413/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000414///
415/// \param TemplateParams the template parameters that we are deducing
416///
417/// \param Param the parameter type
418///
419/// \param Arg the argument type
420///
421/// \param Info information about the template argument deduction itself
422///
423/// \param Deduced the deduced template arguments
424///
425/// \returns the result of template argument deduction so far. Note that a
426/// "success" result means that template argument deduction has not yet failed,
427/// but it may still fail, later, for other reasons.
428static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000429DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000430 TemplateParameterList *TemplateParams,
431 const TemplateSpecializationType *Param,
432 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000433 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000434 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000435 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000437 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000438 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000439 = dyn_cast<TemplateSpecializationType>(Arg)) {
440 // Perform template argument deduction for the template name.
441 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000442 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000443 Param->getTemplateName(),
444 SpecArg->getTemplateName(),
445 Info, Deduced))
446 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000449 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000450 // argument. Ignore any missing/extra arguments, since they could be
451 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000452 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000453 Param->getArgs(), Param->getNumArgs(),
454 SpecArg->getArgs(), SpecArg->getNumArgs(),
455 Info, Deduced,
456 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000459 // If the argument type is a class template specialization, we
460 // perform template argument deduction using its template
461 // arguments.
462 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
463 if (!RecordArg)
464 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000465
466 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000467 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
468 if (!SpecArg)
469 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000471 // Perform template argument deduction for the template name.
472 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000473 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000474 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000475 Param->getTemplateName(),
476 TemplateName(SpecArg->getSpecializedTemplate()),
477 Info, Deduced))
478 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Douglas Gregor20a55e22010-12-22 18:17:10 +0000480 // Perform template argument deduction for the template arguments.
481 return DeduceTemplateArguments(S, TemplateParams,
482 Param->getArgs(), Param->getNumArgs(),
483 SpecArg->getTemplateArgs().data(),
484 SpecArg->getTemplateArgs().size(),
485 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000486}
487
John McCallcd05e812010-08-28 22:14:41 +0000488/// \brief Determines whether the given type is an opaque type that
489/// might be more qualified when instantiated.
490static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
491 switch (T->getTypeClass()) {
492 case Type::TypeOfExpr:
493 case Type::TypeOf:
494 case Type::DependentName:
495 case Type::Decltype:
496 case Type::UnresolvedUsing:
John McCall62c28c82011-01-18 07:41:22 +0000497 case Type::TemplateTypeParm:
John McCallcd05e812010-08-28 22:14:41 +0000498 return true;
499
500 case Type::ConstantArray:
501 case Type::IncompleteArray:
502 case Type::VariableArray:
503 case Type::DependentSizedArray:
504 return IsPossiblyOpaquelyQualifiedType(
505 cast<ArrayType>(T)->getElementType());
506
507 default:
508 return false;
509 }
510}
511
Douglas Gregord3731192011-01-10 07:32:04 +0000512/// \brief Retrieve the depth and index of a template parameter.
Douglas Gregor603cfb42011-01-05 23:12:31 +0000513static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000514getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor603cfb42011-01-05 23:12:31 +0000515 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
516 return std::make_pair(TTP->getDepth(), TTP->getIndex());
517
518 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
519 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
520
521 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
522 return std::make_pair(TTP->getDepth(), TTP->getIndex());
523}
524
Douglas Gregord3731192011-01-10 07:32:04 +0000525/// \brief Retrieve the depth and index of an unexpanded parameter pack.
526static std::pair<unsigned, unsigned>
527getDepthAndIndex(UnexpandedParameterPack UPP) {
528 if (const TemplateTypeParmType *TTP
529 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
530 return std::make_pair(TTP->getDepth(), TTP->getIndex());
531
532 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
533}
534
Douglas Gregor603cfb42011-01-05 23:12:31 +0000535/// \brief Helper function to build a TemplateParameter when we don't
536/// know its type statically.
537static TemplateParameter makeTemplateParameter(Decl *D) {
538 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
539 return TemplateParameter(TTP);
540 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
541 return TemplateParameter(NTTP);
542
543 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
544}
545
Douglas Gregor54293852011-01-10 17:35:05 +0000546/// \brief Prepare to perform template argument deduction for all of the
547/// arguments in a set of argument packs.
548static void PrepareArgumentPackDeduction(Sema &S,
549 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
550 const llvm::SmallVectorImpl<unsigned> &PackIndices,
551 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
552 llvm::SmallVectorImpl<
553 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
554 // Save the deduced template arguments for each parameter pack expanded
555 // by this pack expansion, then clear out the deduction.
556 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
557 // Save the previously-deduced argument pack, then clear it out so that we
558 // can deduce a new argument pack.
559 SavedPacks[I] = Deduced[PackIndices[I]];
560 Deduced[PackIndices[I]] = TemplateArgument();
561
562 // If the template arugment pack was explicitly specified, add that to
563 // the set of deduced arguments.
564 const TemplateArgument *ExplicitArgs;
565 unsigned NumExplicitArgs;
566 if (NamedDecl *PartiallySubstitutedPack
567 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
568 &ExplicitArgs,
569 &NumExplicitArgs)) {
570 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
571 NewlyDeducedPacks[I].append(ExplicitArgs,
572 ExplicitArgs + NumExplicitArgs);
573 }
574 }
575}
576
Douglas Gregor0216f812011-01-10 17:53:52 +0000577/// \brief Finish template argument deduction for a set of argument packs,
578/// producing the argument packs and checking for consistency with prior
579/// deductions.
580static Sema::TemplateDeductionResult
581FinishArgumentPackDeduction(Sema &S,
582 TemplateParameterList *TemplateParams,
583 bool HasAnyArguments,
584 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
585 const llvm::SmallVectorImpl<unsigned> &PackIndices,
586 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
587 llvm::SmallVectorImpl<
588 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
589 TemplateDeductionInfo &Info) {
590 // Build argument packs for each of the parameter packs expanded by this
591 // pack expansion.
592 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
593 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
594 // We were not able to deduce anything for this parameter pack,
595 // so just restore the saved argument pack.
596 Deduced[PackIndices[I]] = SavedPacks[I];
597 continue;
598 }
599
600 DeducedTemplateArgument NewPack;
601
602 if (NewlyDeducedPacks[I].empty()) {
603 // If we deduced an empty argument pack, create it now.
604 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
605 } else {
606 TemplateArgument *ArgumentPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000607 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
Douglas Gregor0216f812011-01-10 17:53:52 +0000608 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
609 ArgumentPack);
610 NewPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000611 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
612 NewlyDeducedPacks[I].size()),
613 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
Douglas Gregor0216f812011-01-10 17:53:52 +0000614 }
615
616 DeducedTemplateArgument Result
617 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
618 if (Result.isNull()) {
619 Info.Param
620 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
621 Info.FirstArg = SavedPacks[I];
622 Info.SecondArg = NewPack;
623 return Sema::TDK_Inconsistent;
624 }
625
626 Deduced[PackIndices[I]] = Result;
627 }
628
629 return Sema::TDK_Success;
630}
631
Douglas Gregor603cfb42011-01-05 23:12:31 +0000632/// \brief Deduce the template arguments by comparing the list of parameter
633/// types to the list of argument types, as in the parameter-type-lists of
634/// function types (C++ [temp.deduct.type]p10).
635///
636/// \param S The semantic analysis object within which we are deducing
637///
638/// \param TemplateParams The template parameters that we are deducing
639///
640/// \param Params The list of parameter types
641///
642/// \param NumParams The number of types in \c Params
643///
644/// \param Args The list of argument types
645///
646/// \param NumArgs The number of types in \c Args
647///
648/// \param Info information about the template argument deduction itself
649///
650/// \param Deduced the deduced template arguments
651///
652/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
653/// how template argument deduction is performed.
654///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000655/// \param PartialOrdering If true, we are performing template argument
656/// deduction for during partial ordering for a call
657/// (C++0x [temp.deduct.partial]).
658///
Douglas Gregorb939a192011-01-21 17:29:42 +0000659/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000660/// in the context of partial ordering, the set of qualifier comparisons.
661///
Douglas Gregor603cfb42011-01-05 23:12:31 +0000662/// \returns the result of template argument deduction so far. Note that a
663/// "success" result means that template argument deduction has not yet failed,
664/// but it may still fail, later, for other reasons.
665static Sema::TemplateDeductionResult
666DeduceTemplateArguments(Sema &S,
667 TemplateParameterList *TemplateParams,
668 const QualType *Params, unsigned NumParams,
669 const QualType *Args, unsigned NumArgs,
670 TemplateDeductionInfo &Info,
671 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000672 unsigned TDF,
673 bool PartialOrdering = false,
Douglas Gregorb939a192011-01-21 17:29:42 +0000674 llvm::SmallVectorImpl<RefParamPartialOrderingComparison> *
675 RefParamComparisons = 0) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000676 // Fast-path check to see if we have too many/too few arguments.
677 if (NumParams != NumArgs &&
678 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
679 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000680 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000681
682 // C++0x [temp.deduct.type]p10:
683 // Similarly, if P has a form that contains (T), then each parameter type
684 // Pi of the respective parameter-type- list of P is compared with the
685 // corresponding parameter type Ai of the corresponding parameter-type-list
686 // of A. [...]
687 unsigned ArgIdx = 0, ParamIdx = 0;
688 for (; ParamIdx != NumParams; ++ParamIdx) {
689 // Check argument types.
690 const PackExpansionType *Expansion
691 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
692 if (!Expansion) {
693 // Simple case: compare the parameter and argument types at this point.
694
695 // Make sure we have an argument.
696 if (ArgIdx >= NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000697 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000698
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000699 if (isa<PackExpansionType>(Args[ArgIdx])) {
700 // C++0x [temp.deduct.type]p22:
701 // If the original function parameter associated with A is a function
702 // parameter pack and the function parameter associated with P is not
703 // a function parameter pack, then template argument deduction fails.
704 return Sema::TDK_NonDeducedMismatch;
705 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000706
Douglas Gregor603cfb42011-01-05 23:12:31 +0000707 if (Sema::TemplateDeductionResult Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000708 = DeduceTemplateArguments(S, TemplateParams,
709 Params[ParamIdx],
710 Args[ArgIdx],
711 Info, Deduced, TDF,
712 PartialOrdering,
Douglas Gregorb939a192011-01-21 17:29:42 +0000713 RefParamComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000714 return Result;
715
716 ++ArgIdx;
717 continue;
718 }
719
Douglas Gregor7d5c0c12011-01-11 01:52:23 +0000720 // C++0x [temp.deduct.type]p5:
721 // The non-deduced contexts are:
722 // - A function parameter pack that does not occur at the end of the
723 // parameter-declaration-clause.
724 if (ParamIdx + 1 < NumParams)
725 return Sema::TDK_Success;
726
Douglas Gregor603cfb42011-01-05 23:12:31 +0000727 // C++0x [temp.deduct.type]p10:
728 // If the parameter-declaration corresponding to Pi is a function
729 // parameter pack, then the type of its declarator- id is compared with
730 // each remaining parameter type in the parameter-type-list of A. Each
731 // comparison deduces template arguments for subsequent positions in the
732 // template parameter packs expanded by the function parameter pack.
733
734 // Compute the set of template parameter indices that correspond to
735 // parameter packs expanded by the pack expansion.
736 llvm::SmallVector<unsigned, 2> PackIndices;
737 QualType Pattern = Expansion->getPattern();
738 {
739 llvm::BitVector SawIndices(TemplateParams->size());
740 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
741 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
742 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
743 unsigned Depth, Index;
744 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
745 if (Depth == 0 && !SawIndices[Index]) {
746 SawIndices[Index] = true;
747 PackIndices.push_back(Index);
748 }
749 }
750 }
751 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
752
Douglas Gregord3731192011-01-10 07:32:04 +0000753 // Keep track of the deduced template arguments for each parameter pack
754 // expanded by this pack expansion (the outer index) and for each
755 // template argument (the inner SmallVectors).
756 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
757 NewlyDeducedPacks(PackIndices.size());
Douglas Gregor603cfb42011-01-05 23:12:31 +0000758 llvm::SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000759 SavedPacks(PackIndices.size());
760 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
761 NewlyDeducedPacks);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000762
Douglas Gregor603cfb42011-01-05 23:12:31 +0000763 bool HasAnyArguments = false;
764 for (; ArgIdx < NumArgs; ++ArgIdx) {
765 HasAnyArguments = true;
766
767 // Deduce template arguments from the pattern.
768 if (Sema::TemplateDeductionResult Result
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000769 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
770 Info, Deduced, TDF, PartialOrdering,
771 RefParamComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000772 return Result;
773
774 // Capture the deduced template arguments for each parameter pack expanded
775 // by this pack expansion, add them to the list of arguments we've deduced
776 // for that pack, then clear out the deduced argument.
777 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
778 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
779 if (!DeducedArg.isNull()) {
780 NewlyDeducedPacks[I].push_back(DeducedArg);
781 DeducedArg = DeducedTemplateArgument();
782 }
783 }
784 }
785
786 // Build argument packs for each of the parameter packs expanded by this
787 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +0000788 if (Sema::TemplateDeductionResult Result
789 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
790 Deduced, PackIndices, SavedPacks,
791 NewlyDeducedPacks, Info))
792 return Result;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000793 }
794
795 // Make sure we don't have any extra arguments.
796 if (ArgIdx < NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000797 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000798
799 return Sema::TDK_Success;
800}
801
Douglas Gregor500d3312009-06-26 18:27:22 +0000802/// \brief Deduce the template arguments by comparing the parameter type and
803/// the argument type (C++ [temp.deduct.type]).
804///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000805/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000806///
807/// \param TemplateParams the template parameters that we are deducing
808///
809/// \param ParamIn the parameter type
810///
811/// \param ArgIn the argument type
812///
813/// \param Info information about the template argument deduction itself
814///
815/// \param Deduced the deduced template arguments
816///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000817/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000818/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000819///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000820/// \param PartialOrdering Whether we're performing template argument deduction
821/// in the context of partial ordering (C++0x [temp.deduct.partial]).
822///
Douglas Gregorb939a192011-01-21 17:29:42 +0000823/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000824/// in the context of partial ordering, the set of qualifier comparisons.
825///
Douglas Gregor500d3312009-06-26 18:27:22 +0000826/// \returns the result of template argument deduction so far. Note that a
827/// "success" result means that template argument deduction has not yet failed,
828/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000829static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000830DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000831 TemplateParameterList *TemplateParams,
832 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000833 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000834 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000835 unsigned TDF,
836 bool PartialOrdering,
Douglas Gregorb939a192011-01-21 17:29:42 +0000837 llvm::SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000838 // We only want to look at the canonical types, since typedefs and
839 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000840 QualType Param = S.Context.getCanonicalType(ParamIn);
841 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000842
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000843 // If the argument type is a pack expansion, look at its pattern.
844 // This isn't explicitly called out
845 if (const PackExpansionType *ArgExpansion
846 = dyn_cast<PackExpansionType>(Arg))
847 Arg = ArgExpansion->getPattern();
848
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000849 if (PartialOrdering) {
850 // C++0x [temp.deduct.partial]p5:
851 // Before the partial ordering is done, certain transformations are
852 // performed on the types used for partial ordering:
853 // - If P is a reference type, P is replaced by the type referred to.
854 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
855 if (ParamRef)
856 Param = ParamRef->getPointeeType();
857
858 // - If A is a reference type, A is replaced by the type referred to.
859 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
860 if (ArgRef)
861 Arg = ArgRef->getPointeeType();
862
Douglas Gregorb939a192011-01-21 17:29:42 +0000863 if (RefParamComparisons && ParamRef && ArgRef) {
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000864 // C++0x [temp.deduct.partial]p6:
865 // If both P and A were reference types (before being replaced with the
866 // type referred to above), determine which of the two types (if any) is
867 // more cv-qualified than the other; otherwise the types are considered
868 // to be equally cv-qualified for partial ordering purposes. The result
869 // of this determination will be used below.
870 //
871 // We save this information for later, using it only when deduction
872 // succeeds in both directions.
Douglas Gregorb939a192011-01-21 17:29:42 +0000873 RefParamPartialOrderingComparison Comparison;
874 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
875 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
876 Comparison.Qualifiers = NeitherMoreQualified;
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000877 if (Param.isMoreQualifiedThan(Arg))
Douglas Gregorb939a192011-01-21 17:29:42 +0000878 Comparison.Qualifiers = ParamMoreQualified;
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000879 else if (Arg.isMoreQualifiedThan(Param))
Douglas Gregorb939a192011-01-21 17:29:42 +0000880 Comparison.Qualifiers = ArgMoreQualified;
881 RefParamComparisons->push_back(Comparison);
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000882 }
883
884 // C++0x [temp.deduct.partial]p7:
885 // Remove any top-level cv-qualifiers:
886 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
887 // version of P.
888 Param = Param.getUnqualifiedType();
889 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
890 // version of A.
891 Arg = Arg.getUnqualifiedType();
892 } else {
893 // C++0x [temp.deduct.call]p4 bullet 1:
894 // - If the original P is a reference type, the deduced A (i.e., the type
895 // referred to by the reference) can be more cv-qualified than the
896 // transformed A.
897 if (TDF & TDF_ParamWithReferenceType) {
898 Qualifiers Quals;
899 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
900 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall62c28c82011-01-18 07:41:22 +0000901 Arg.getCVRQualifiers());
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000902 Param = S.Context.getQualifiedType(UnqualParam, Quals);
903 }
Douglas Gregor73b3cf62011-01-25 17:19:08 +0000904
905 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
906 // C++0x [temp.deduct.type]p10:
907 // If P and A are function types that originated from deduction when
908 // taking the address of a function template (14.8.2.2) or when deducing
909 // template arguments from a function declaration (14.8.2.6) and Pi and
910 // Ai are parameters of the top-level parameter-type-list of P and A,
911 // respectively, Pi is adjusted if it is an rvalue reference to a
912 // cv-unqualified template parameter and Ai is an lvalue reference, in
913 // which case the type of Pi is changed to be the template parameter
914 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
915 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
916 // deduced as X&. — end note ]
917 TDF &= ~TDF_TopLevelParameterTypeList;
918
919 if (const RValueReferenceType *ParamRef
920 = Param->getAs<RValueReferenceType>()) {
921 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
922 !ParamRef->getPointeeType().getQualifiers())
923 if (Arg->isLValueReferenceType())
924 Param = ParamRef->getPointeeType();
925 }
926 }
Douglas Gregor500d3312009-06-26 18:27:22 +0000927 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000928
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000929 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000930 if (!Param->isDependentType()) {
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000931 if (!(TDF & TDF_SkipNonDependent) && Param != Arg)
Douglas Gregor12820292009-09-14 20:00:47 +0000932 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor12820292009-09-14 20:00:47 +0000933
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000934 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000935 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000936
Douglas Gregor199d9912009-06-05 00:53:49 +0000937 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000938 // A template type argument T, a template template argument TT or a
939 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000940 // the following forms:
941 //
942 // T
943 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000944 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000945 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000946 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000947 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000949 // If the argument type is an array type, move the qualifiers up to the
950 // top level, so they can be matched with the qualifiers on the parameter.
951 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000952 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000953 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000954 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000955 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000956 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000957 RecanonicalizeArg = true;
958 }
959 }
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000961 // The argument type can not be less qualified than the parameter
962 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000963 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000964 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000965 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000966 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000967 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000968 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000969
970 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000971 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000972 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000973
974 // local manipulation is okay because it's canonical
975 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000976 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000977 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000979 DeducedTemplateArgument NewDeduced(DeducedType);
980 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
981 Deduced[Index],
982 NewDeduced);
983 if (Result.isNull()) {
984 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
985 Info.FirstArg = Deduced[Index];
986 Info.SecondArg = NewDeduced;
987 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000988 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000989
990 Deduced[Index] = Result;
991 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000992 }
993
Douglas Gregorf67875d2009-06-12 18:26:56 +0000994 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000995 Info.FirstArg = TemplateArgument(ParamIn);
996 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000997
Douglas Gregor0bc15d92011-01-14 05:11:40 +0000998 // If the parameter is an already-substituted template parameter
999 // pack, do nothing: we don't know which of its arguments to look
1000 // at, so we have to wait until all of the parameter packs in this
1001 // expansion have arguments.
1002 if (isa<SubstTemplateTypeParmPackType>(Param))
1003 return Sema::TDK_Success;
1004
Douglas Gregor508f1c82009-06-26 23:10:12 +00001005 // Check the cv-qualifiers on the parameter and argument types.
1006 if (!(TDF & TDF_IgnoreQualifiers)) {
1007 if (TDF & TDF_ParamWithReferenceType) {
1008 if (Param.isMoreQualifiedThan(Arg))
1009 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +00001010 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +00001011 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +00001012 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +00001013 }
1014 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001015
Douglas Gregord560d502009-06-04 00:21:18 +00001016 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001017 // No deduction possible for these types
1018 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +00001019 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Douglas Gregor199d9912009-06-05 00:53:49 +00001021 // T *
Douglas Gregord560d502009-06-04 00:21:18 +00001022 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +00001023 QualType PointeeType;
1024 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1025 PointeeType = PointerArg->getPointeeType();
1026 } else if (const ObjCObjectPointerType *PointerArg
1027 = Arg->getAs<ObjCObjectPointerType>()) {
1028 PointeeType = PointerArg->getPointeeType();
1029 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +00001030 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +00001031 }
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Douglas Gregor41128772009-06-26 23:27:24 +00001033 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001034 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001035 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +00001036 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +00001037 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +00001038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Douglas Gregor199d9912009-06-05 00:53:49 +00001040 // T &
Douglas Gregord560d502009-06-04 00:21:18 +00001041 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +00001042 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +00001043 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001044 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001046 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001047 cast<LValueReferenceType>(Param)->getPointeeType(),
1048 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001049 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001050 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001051
Douglas Gregor199d9912009-06-05 00:53:49 +00001052 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +00001053 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +00001054 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +00001055 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001056 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001058 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001059 cast<RValueReferenceType>(Param)->getPointeeType(),
1060 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001061 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001062 }
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Douglas Gregor199d9912009-06-05 00:53:49 +00001064 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001065 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001066 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001067 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001068 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001069 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001070
John McCalle4f26e52010-08-19 00:20:19 +00001071 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001072 return DeduceTemplateArguments(S, TemplateParams,
1073 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001074 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001075 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001076 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001077
1078 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001079 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001080 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001081 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001082 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001083 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001084
1085 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001086 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001087 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001088 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001089
John McCalle4f26e52010-08-19 00:20:19 +00001090 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001091 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001092 ConstantArrayParm->getElementType(),
1093 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001094 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001095 }
1096
Douglas Gregor199d9912009-06-05 00:53:49 +00001097 // type [i]
1098 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001099 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +00001100 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001101 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001102
John McCalle4f26e52010-08-19 00:20:19 +00001103 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1104
Douglas Gregor199d9912009-06-05 00:53:49 +00001105 // Check the element type of the arrays
1106 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001107 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001108 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001109 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001110 DependentArrayParm->getElementType(),
1111 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001112 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001113 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Douglas Gregor199d9912009-06-05 00:53:49 +00001115 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +00001116 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001117 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1118 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001119 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +00001120
1121 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +00001122 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001123 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +00001124 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +00001125 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +00001126 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1127 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001128 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
1129 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001130 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001131 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +00001132 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001133 if (const DependentSizedArrayType *DependentArrayArg
1134 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +00001135 if (DependentArrayArg->getSizeExpr())
1136 return DeduceNonTypeTemplateArgument(S, NTTP,
1137 DependentArrayArg->getSizeExpr(),
1138 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Douglas Gregor199d9912009-06-05 00:53:49 +00001140 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +00001141 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001142 }
Mike Stump1eb44332009-09-09 15:08:12 +00001143
1144 // type(*)(T)
1145 // T(*)()
1146 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +00001147 case Type::FunctionProto: {
Douglas Gregor73b3cf62011-01-25 17:19:08 +00001148 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump1eb44332009-09-09 15:08:12 +00001149 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +00001150 dyn_cast<FunctionProtoType>(Arg);
1151 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001152 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001153
1154 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +00001155 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001156
Mike Stump1eb44332009-09-09 15:08:12 +00001157 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001158 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001159 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001161 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001162 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001163
Anders Carlssona27fad52009-06-08 15:19:08 +00001164 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001165 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001166 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001167 FunctionProtoParam->getResultType(),
1168 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001169 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001170 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Douglas Gregor603cfb42011-01-05 23:12:31 +00001172 return DeduceTemplateArguments(S, TemplateParams,
1173 FunctionProtoParam->arg_type_begin(),
1174 FunctionProtoParam->getNumArgs(),
1175 FunctionProtoArg->arg_type_begin(),
1176 FunctionProtoArg->getNumArgs(),
Douglas Gregor73b3cf62011-01-25 17:19:08 +00001177 Info, Deduced, SubTDF);
Anders Carlssona27fad52009-06-08 15:19:08 +00001178 }
Mike Stump1eb44332009-09-09 15:08:12 +00001179
John McCall3cb0ebd2010-03-10 03:28:59 +00001180 case Type::InjectedClassName: {
1181 // Treat a template's injected-class-name as if the template
1182 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001183 Param = cast<InjectedClassNameType>(Param)
1184 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001185 assert(isa<TemplateSpecializationType>(Param) &&
1186 "injected class name is not a template specialization type");
1187 // fall through
1188 }
1189
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001190 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001191 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001192 // TT<T>
1193 // TT<i>
1194 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001195 case Type::TemplateSpecialization: {
1196 const TemplateSpecializationType *SpecParam
1197 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001199 // Try to deduce template arguments from the template-id.
1200 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001201 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001202 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001204 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001205 // C++ [temp.deduct.call]p3b3:
1206 // If P is a class, and P has the form template-id, then A can be a
1207 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001208 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001209 // class pointed to by the deduced A.
1210 //
1211 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001212 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001213 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001214 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1215 // We cannot inspect base classes as part of deduction when the type
1216 // is incomplete, so either instantiate any templates necessary to
1217 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001218 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001219 return Result;
1220
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001221 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001222 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001223 // ToVisit is our stack of records that we still need to visit.
1224 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1225 llvm::SmallVector<const RecordType *, 8> ToVisit;
1226 ToVisit.push_back(RecordT);
1227 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001228 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1229 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001230 while (!ToVisit.empty()) {
1231 // Retrieve the next class in the inheritance hierarchy.
1232 const RecordType *NextT = ToVisit.back();
1233 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001235 // If we have already seen this type, skip it.
1236 if (!Visited.insert(NextT))
1237 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001239 // If this is a base class, try to perform template argument
1240 // deduction from it.
1241 if (NextT != RecordT) {
1242 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001243 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001244 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001246 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001247 // note that we had some success. Otherwise, ignore any deductions
1248 // from this base class.
1249 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001250 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001251 DeducedOrig = Deduced;
1252 }
1253 else
1254 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001255 }
Mike Stump1eb44332009-09-09 15:08:12 +00001256
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001257 // Visit base classes
1258 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1259 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1260 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001261 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001262 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001263 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001264 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001265 }
1266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001268 if (Successful)
1269 return Sema::TDK_Success;
1270 }
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001272 }
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001274 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001275 }
1276
Douglas Gregor637a4092009-06-10 23:47:09 +00001277 // T type::*
1278 // T T::*
1279 // T (type::*)()
1280 // type (T::*)()
1281 // type (type::*)(T)
1282 // type (T::*)(T)
1283 // T (type::*)(T)
1284 // T (T::*)()
1285 // T (T::*)(T)
1286 case Type::MemberPointer: {
1287 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1288 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1289 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001290 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001291
Douglas Gregorf67875d2009-06-12 18:26:56 +00001292 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001293 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001294 MemPtrParam->getPointeeType(),
1295 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001296 Info, Deduced,
1297 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001298 return Result;
1299
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001300 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001301 QualType(MemPtrParam->getClass(), 0),
1302 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001303 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001304 }
1305
Anders Carlsson9a917e42009-06-12 22:56:54 +00001306 // (clang extension)
1307 //
Mike Stump1eb44332009-09-09 15:08:12 +00001308 // type(^)(T)
1309 // T(^)()
1310 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001311 case Type::BlockPointer: {
1312 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1313 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Anders Carlsson859ba502009-06-12 16:23:10 +00001315 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001316 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001318 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001319 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001320 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001321 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001322 }
1323
Douglas Gregor637a4092009-06-10 23:47:09 +00001324 case Type::TypeOfExpr:
1325 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001326 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001327 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001328 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001329
Douglas Gregord560d502009-06-04 00:21:18 +00001330 default:
1331 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001332 }
1333
1334 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001335 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001336}
1337
Douglas Gregorf67875d2009-06-12 18:26:56 +00001338static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001339DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001340 TemplateParameterList *TemplateParams,
1341 const TemplateArgument &Param,
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001342 TemplateArgument Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001343 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001344 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001345 // If the template argument is a pack expansion, perform template argument
1346 // deduction against the pattern of that expansion. This only occurs during
1347 // partial ordering.
1348 if (Arg.isPackExpansion())
1349 Arg = Arg.getPackExpansionPattern();
1350
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001351 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001352 case TemplateArgument::Null:
1353 assert(false && "Null template argument in parameter list");
1354 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001355
1356 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001357 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001358 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001359 Arg.getAsType(), Info, Deduced, 0);
1360 Info.FirstArg = Param;
1361 Info.SecondArg = Arg;
1362 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001363
Douglas Gregor788cd062009-11-11 01:00:40 +00001364 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001365 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001366 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001367 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001368 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001369 Info.FirstArg = Param;
1370 Info.SecondArg = Arg;
1371 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001372
1373 case TemplateArgument::TemplateExpansion:
1374 llvm_unreachable("caller should handle pack expansions");
1375 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001376
Douglas Gregor199d9912009-06-05 00:53:49 +00001377 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001378 if (Arg.getKind() == TemplateArgument::Declaration &&
1379 Param.getAsDecl()->getCanonicalDecl() ==
1380 Arg.getAsDecl()->getCanonicalDecl())
1381 return Sema::TDK_Success;
1382
Douglas Gregorf67875d2009-06-12 18:26:56 +00001383 Info.FirstArg = Param;
1384 Info.SecondArg = Arg;
1385 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Douglas Gregor199d9912009-06-05 00:53:49 +00001387 case TemplateArgument::Integral:
1388 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001389 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001390 return Sema::TDK_Success;
1391
1392 Info.FirstArg = Param;
1393 Info.SecondArg = Arg;
1394 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001395 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001396
1397 if (Arg.getKind() == TemplateArgument::Expression) {
1398 Info.FirstArg = Param;
1399 Info.SecondArg = Arg;
1400 return Sema::TDK_NonDeducedMismatch;
1401 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001402
Douglas Gregorf67875d2009-06-12 18:26:56 +00001403 Info.FirstArg = Param;
1404 Info.SecondArg = Arg;
1405 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Douglas Gregor199d9912009-06-05 00:53:49 +00001407 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001408 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001409 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1410 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001411 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001412 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001413 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001414 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001415 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001416 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001417 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001418 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001419 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001420 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001421 Info, Deduced);
1422
Douglas Gregorf67875d2009-06-12 18:26:56 +00001423 Info.FirstArg = Param;
1424 Info.SecondArg = Arg;
1425 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001426 }
Mike Stump1eb44332009-09-09 15:08:12 +00001427
Douglas Gregor199d9912009-06-05 00:53:49 +00001428 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001429 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001430 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001431 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001432 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001433 }
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Douglas Gregorf67875d2009-06-12 18:26:56 +00001435 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001436}
1437
Douglas Gregor20a55e22010-12-22 18:17:10 +00001438/// \brief Determine whether there is a template argument to be used for
1439/// deduction.
1440///
1441/// This routine "expands" argument packs in-place, overriding its input
1442/// parameters so that \c Args[ArgIdx] will be the available template argument.
1443///
1444/// \returns true if there is another template argument (which will be at
1445/// \c Args[ArgIdx]), false otherwise.
1446static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1447 unsigned &ArgIdx,
1448 unsigned &NumArgs) {
1449 if (ArgIdx == NumArgs)
1450 return false;
1451
1452 const TemplateArgument &Arg = Args[ArgIdx];
1453 if (Arg.getKind() != TemplateArgument::Pack)
1454 return true;
1455
1456 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1457 Args = Arg.pack_begin();
1458 NumArgs = Arg.pack_size();
1459 ArgIdx = 0;
1460 return ArgIdx < NumArgs;
1461}
1462
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001463/// \brief Determine whether the given set of template arguments has a pack
1464/// expansion that is not the last template argument.
1465static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1466 unsigned NumArgs) {
1467 unsigned ArgIdx = 0;
1468 while (ArgIdx < NumArgs) {
1469 const TemplateArgument &Arg = Args[ArgIdx];
1470
1471 // Unwrap argument packs.
1472 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1473 Args = Arg.pack_begin();
1474 NumArgs = Arg.pack_size();
1475 ArgIdx = 0;
1476 continue;
1477 }
1478
1479 ++ArgIdx;
1480 if (ArgIdx == NumArgs)
1481 return false;
1482
1483 if (Arg.isPackExpansion())
1484 return true;
1485 }
1486
1487 return false;
1488}
1489
Douglas Gregor20a55e22010-12-22 18:17:10 +00001490static Sema::TemplateDeductionResult
1491DeduceTemplateArguments(Sema &S,
1492 TemplateParameterList *TemplateParams,
1493 const TemplateArgument *Params, unsigned NumParams,
1494 const TemplateArgument *Args, unsigned NumArgs,
1495 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001496 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1497 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001498 // C++0x [temp.deduct.type]p9:
1499 // If the template argument list of P contains a pack expansion that is not
1500 // the last template argument, the entire template argument list is a
1501 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001502 if (hasPackExpansionBeforeEnd(Params, NumParams))
1503 return Sema::TDK_Success;
1504
Douglas Gregore02e2622010-12-22 21:19:48 +00001505 // C++0x [temp.deduct.type]p9:
1506 // If P has a form that contains <T> or <i>, then each argument Pi of the
1507 // respective template argument list P is compared with the corresponding
1508 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001509 unsigned ArgIdx = 0, ParamIdx = 0;
1510 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1511 ++ParamIdx) {
1512 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001513 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001514
1515 // Check whether we have enough arguments.
1516 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001517 return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
Douglas Gregor0972c862010-12-22 18:55:49 +00001518 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001519
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001520 if (Args[ArgIdx].isPackExpansion()) {
1521 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1522 // but applied to pack expansions that are template arguments.
1523 return Sema::TDK_NonDeducedMismatch;
1524 }
1525
Douglas Gregore02e2622010-12-22 21:19:48 +00001526 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001527 if (Sema::TemplateDeductionResult Result
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001528 = DeduceTemplateArguments(S, TemplateParams,
1529 Params[ParamIdx], Args[ArgIdx],
1530 Info, Deduced))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001531 return Result;
1532
1533 // Move to the next argument.
1534 ++ArgIdx;
1535 continue;
1536 }
1537
Douglas Gregore02e2622010-12-22 21:19:48 +00001538 // The parameter is a pack expansion.
1539
1540 // C++0x [temp.deduct.type]p9:
1541 // If Pi is a pack expansion, then the pattern of Pi is compared with
1542 // each remaining argument in the template argument list of A. Each
1543 // comparison deduces template arguments for subsequent positions in the
1544 // template parameter packs expanded by Pi.
1545 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1546
1547 // Compute the set of template parameter indices that correspond to
1548 // parameter packs expanded by the pack expansion.
1549 llvm::SmallVector<unsigned, 2> PackIndices;
1550 {
1551 llvm::BitVector SawIndices(TemplateParams->size());
1552 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1553 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1554 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1555 unsigned Depth, Index;
1556 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1557 if (Depth == 0 && !SawIndices[Index]) {
1558 SawIndices[Index] = true;
1559 PackIndices.push_back(Index);
1560 }
1561 }
1562 }
1563 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1564
1565 // FIXME: If there are no remaining arguments, we can bail out early
1566 // and set any deduced parameter packs to an empty argument pack.
1567 // The latter part of this is a (minor) correctness issue.
1568
1569 // Save the deduced template arguments for each parameter pack expanded
1570 // by this pack expansion, then clear out the deduction.
1571 llvm::SmallVector<DeducedTemplateArgument, 2>
1572 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00001573 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1574 NewlyDeducedPacks(PackIndices.size());
1575 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1576 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001577
1578 // Keep track of the deduced template arguments for each parameter pack
1579 // expanded by this pack expansion (the outer index) and for each
1580 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001581 bool HasAnyArguments = false;
1582 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1583 HasAnyArguments = true;
1584
1585 // Deduce template arguments from the pattern.
1586 if (Sema::TemplateDeductionResult Result
1587 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1588 Info, Deduced))
1589 return Result;
1590
1591 // Capture the deduced template arguments for each parameter pack expanded
1592 // by this pack expansion, add them to the list of arguments we've deduced
1593 // for that pack, then clear out the deduced argument.
1594 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1595 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1596 if (!DeducedArg.isNull()) {
1597 NewlyDeducedPacks[I].push_back(DeducedArg);
1598 DeducedArg = DeducedTemplateArgument();
1599 }
1600 }
1601
1602 ++ArgIdx;
1603 }
1604
1605 // Build argument packs for each of the parameter packs expanded by this
1606 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00001607 if (Sema::TemplateDeductionResult Result
1608 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
1609 Deduced, PackIndices, SavedPacks,
1610 NewlyDeducedPacks, Info))
1611 return Result;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001612 }
1613
1614 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001615 if (NumberOfArgumentsMustMatch &&
1616 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001617 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001618
1619 return Sema::TDK_Success;
1620}
1621
Mike Stump1eb44332009-09-09 15:08:12 +00001622static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001623DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001624 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001625 const TemplateArgumentList &ParamList,
1626 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001627 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001628 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001629 return DeduceTemplateArguments(S, TemplateParams,
1630 ParamList.data(), ParamList.size(),
1631 ArgList.data(), ArgList.size(),
1632 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001633}
1634
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001635/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001636static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001637 const TemplateArgument &X,
1638 const TemplateArgument &Y) {
1639 if (X.getKind() != Y.getKind())
1640 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001642 switch (X.getKind()) {
1643 case TemplateArgument::Null:
1644 assert(false && "Comparing NULL template argument");
1645 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001647 case TemplateArgument::Type:
1648 return Context.getCanonicalType(X.getAsType()) ==
1649 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001651 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001652 return X.getAsDecl()->getCanonicalDecl() ==
1653 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Douglas Gregor788cd062009-11-11 01:00:40 +00001655 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001656 case TemplateArgument::TemplateExpansion:
1657 return Context.getCanonicalTemplateName(
1658 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1659 Context.getCanonicalTemplateName(
1660 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001661
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001662 case TemplateArgument::Integral:
1663 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Douglas Gregor788cd062009-11-11 01:00:40 +00001665 case TemplateArgument::Expression: {
1666 llvm::FoldingSetNodeID XID, YID;
1667 X.getAsExpr()->Profile(XID, Context, true);
1668 Y.getAsExpr()->Profile(YID, Context, true);
1669 return XID == YID;
1670 }
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001672 case TemplateArgument::Pack:
1673 if (X.pack_size() != Y.pack_size())
1674 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001675
1676 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1677 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001678 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001679 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001680 if (!isSameTemplateArg(Context, *XP, *YP))
1681 return false;
1682
1683 return true;
1684 }
1685
1686 return false;
1687}
1688
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001689/// \brief Allocate a TemplateArgumentLoc where all locations have
1690/// been initialized to the given location.
1691///
1692/// \param S The semantic analysis object.
1693///
1694/// \param The template argument we are producing template argument
1695/// location information for.
1696///
1697/// \param NTTPType For a declaration template argument, the type of
1698/// the non-type template parameter that corresponds to this template
1699/// argument.
1700///
1701/// \param Loc The source location to use for the resulting template
1702/// argument.
1703static TemplateArgumentLoc
1704getTrivialTemplateArgumentLoc(Sema &S,
1705 const TemplateArgument &Arg,
1706 QualType NTTPType,
1707 SourceLocation Loc) {
1708 switch (Arg.getKind()) {
1709 case TemplateArgument::Null:
1710 llvm_unreachable("Can't get a NULL template argument here");
1711 break;
1712
1713 case TemplateArgument::Type:
1714 return TemplateArgumentLoc(Arg,
1715 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1716
1717 case TemplateArgument::Declaration: {
1718 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001719 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001720 .takeAs<Expr>();
1721 return TemplateArgumentLoc(TemplateArgument(E), E);
1722 }
1723
1724 case TemplateArgument::Integral: {
1725 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001726 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001727 return TemplateArgumentLoc(TemplateArgument(E), E);
1728 }
1729
1730 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001731 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1732
1733 case TemplateArgument::TemplateExpansion:
1734 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1735
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001736 case TemplateArgument::Expression:
1737 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1738
1739 case TemplateArgument::Pack:
1740 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1741 }
1742
1743 return TemplateArgumentLoc();
1744}
1745
1746
1747/// \brief Convert the given deduced template argument and add it to the set of
1748/// fully-converted template arguments.
1749static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1750 DeducedTemplateArgument Arg,
1751 NamedDecl *Template,
1752 QualType NTTPType,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001753 unsigned ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001754 TemplateDeductionInfo &Info,
1755 bool InFunctionTemplate,
1756 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1757 if (Arg.getKind() == TemplateArgument::Pack) {
1758 // This is a template argument pack, so check each of its arguments against
1759 // the template parameter.
1760 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1761 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001762 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001763 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001764 // When converting the deduced template argument, append it to the
1765 // general output list. We need to do this so that the template argument
1766 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001767 DeducedTemplateArgument InnerArg(*PA);
1768 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1769 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001770 NTTPType, PackedArgsBuilder.size(),
1771 Info, InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001772 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001773
1774 // Move the converted template argument into our argument pack.
1775 PackedArgsBuilder.push_back(Output.back());
1776 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001777 }
1778
1779 // Create the resulting argument pack.
Douglas Gregor203e6a32011-01-11 23:09:57 +00001780 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
1781 PackedArgsBuilder.data(),
1782 PackedArgsBuilder.size()));
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001783 return false;
1784 }
1785
1786 // Convert the deduced template argument into a template
1787 // argument that we can check, almost as if the user had written
1788 // the template argument explicitly.
1789 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1790 Info.getLocation());
1791
1792 // Check the template argument, converting it as necessary.
1793 return S.CheckTemplateArgument(Param, ArgLoc,
1794 Template,
1795 Template->getLocation(),
1796 Template->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001797 ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001798 Output,
1799 InFunctionTemplate
1800 ? (Arg.wasDeducedFromArrayBound()
1801 ? Sema::CTAK_DeducedFromArrayBound
1802 : Sema::CTAK_Deduced)
1803 : Sema::CTAK_Specified);
1804}
1805
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001806/// Complete template argument deduction for a class template partial
1807/// specialization.
1808static Sema::TemplateDeductionResult
1809FinishTemplateArgumentDeduction(Sema &S,
1810 ClassTemplatePartialSpecializationDecl *Partial,
1811 const TemplateArgumentList &TemplateArgs,
1812 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001813 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001814 // Trap errors.
1815 Sema::SFINAETrap Trap(S);
1816
1817 Sema::ContextRAII SavedContext(S, Partial);
1818
1819 // C++ [temp.deduct.type]p2:
1820 // [...] or if any template argument remains neither deduced nor
1821 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001822 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001823 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1824 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001825 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001826 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001827 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001828 return Sema::TDK_Incomplete;
1829 }
1830
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001831 // We have deduced this argument, so it still needs to be
1832 // checked and converted.
1833
1834 // First, for a non-type template parameter type that is
1835 // initialized by a declaration, we need the type of the
1836 // corresponding non-type template parameter.
1837 QualType NTTPType;
1838 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001839 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001840 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001841 if (NTTPType->isDependentType()) {
1842 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1843 Builder.data(), Builder.size());
1844 NTTPType = S.SubstType(NTTPType,
1845 MultiLevelTemplateArgumentList(TemplateArgs),
1846 NTTP->getLocation(),
1847 NTTP->getDeclName());
1848 if (NTTPType.isNull()) {
1849 Info.Param = makeTemplateParameter(Param);
1850 // FIXME: These template arguments are temporary. Free them!
1851 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1852 Builder.data(),
1853 Builder.size()));
1854 return Sema::TDK_SubstitutionFailure;
1855 }
1856 }
1857 }
1858
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001859 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001860 Partial, NTTPType, 0, Info, false,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001861 Builder)) {
1862 Info.Param = makeTemplateParameter(Param);
1863 // FIXME: These template arguments are temporary. Free them!
1864 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1865 Builder.size()));
1866 return Sema::TDK_SubstitutionFailure;
1867 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001868 }
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001869
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001870 // Form the template argument list from the deduced template arguments.
1871 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001872 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1873 Builder.size());
1874
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001875 Info.reset(DeducedArgumentList);
1876
1877 // Substitute the deduced template arguments into the template
1878 // arguments of the class template partial specialization, and
1879 // verify that the instantiated template arguments are both valid
1880 // and are equivalent to the template arguments originally provided
1881 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001882 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001883 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1884 const TemplateArgumentLoc *PartialTemplateArgs
1885 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001886
1887 // Note that we don't provide the langle and rangle locations.
1888 TemplateArgumentListInfo InstArgs;
1889
Douglas Gregore02e2622010-12-22 21:19:48 +00001890 if (S.Subst(PartialTemplateArgs,
1891 Partial->getNumTemplateArgsAsWritten(),
1892 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1893 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1894 if (ParamIdx >= Partial->getTemplateParameters()->size())
1895 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1896
1897 Decl *Param
1898 = const_cast<NamedDecl *>(
1899 Partial->getTemplateParameters()->getParam(ParamIdx));
1900 Info.Param = makeTemplateParameter(Param);
1901 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1902 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001903 }
1904
Douglas Gregor910f8002010-11-07 23:05:16 +00001905 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001906 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001907 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001908 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001909
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001910 TemplateParameterList *TemplateParams
1911 = ClassTemplate->getTemplateParameters();
1912 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001913 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001914 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001915 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001916 Info.FirstArg = TemplateArgs[I];
1917 Info.SecondArg = InstArg;
1918 return Sema::TDK_NonDeducedMismatch;
1919 }
1920 }
1921
1922 if (Trap.hasErrorOccurred())
1923 return Sema::TDK_SubstitutionFailure;
1924
1925 return Sema::TDK_Success;
1926}
1927
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001928/// \brief Perform template argument deduction to determine whether
1929/// the given template arguments match the given class template
1930/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001931Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001932Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001933 const TemplateArgumentList &TemplateArgs,
1934 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001935 // C++ [temp.class.spec.match]p2:
1936 // A partial specialization matches a given actual template
1937 // argument list if the template arguments of the partial
1938 // specialization can be deduced from the actual template argument
1939 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001940 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001941 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001942 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001943 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001944 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001945 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001946 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001947 TemplateArgs, Info, Deduced))
1948 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001949
Douglas Gregor637a4092009-06-10 23:47:09 +00001950 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001951 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001952 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001953 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001954
Douglas Gregorbb260412009-06-14 08:02:22 +00001955 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001956 return Sema::TDK_SubstitutionFailure;
1957
1958 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1959 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001960}
Douglas Gregor031a5882009-06-13 00:26:55 +00001961
Douglas Gregor41128772009-06-26 23:27:24 +00001962/// \brief Determine whether the given type T is a simple-template-id type.
1963static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001964 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001965 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001966 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Douglas Gregor41128772009-06-26 23:27:24 +00001968 return false;
1969}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001970
1971/// \brief Substitute the explicitly-provided template arguments into the
1972/// given function template according to C++ [temp.arg.explicit].
1973///
1974/// \param FunctionTemplate the function template into which the explicit
1975/// template arguments will be substituted.
1976///
Mike Stump1eb44332009-09-09 15:08:12 +00001977/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001978/// arguments.
1979///
Mike Stump1eb44332009-09-09 15:08:12 +00001980/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001981/// with the converted and checked explicit template arguments.
1982///
Mike Stump1eb44332009-09-09 15:08:12 +00001983/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001984/// parameters.
1985///
1986/// \param FunctionType if non-NULL, the result type of the function template
1987/// will also be instantiated and the pointed-to value will be updated with
1988/// the instantiated function type.
1989///
1990/// \param Info if substitution fails for any reason, this object will be
1991/// populated with more information about the failure.
1992///
1993/// \returns TDK_Success if substitution was successful, or some failure
1994/// condition.
1995Sema::TemplateDeductionResult
1996Sema::SubstituteExplicitTemplateArguments(
1997 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001998 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001999 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002000 llvm::SmallVectorImpl<QualType> &ParamTypes,
2001 QualType *FunctionType,
2002 TemplateDeductionInfo &Info) {
2003 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2004 TemplateParameterList *TemplateParams
2005 = FunctionTemplate->getTemplateParameters();
2006
John McCalld5532b62009-11-23 01:53:49 +00002007 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002008 // No arguments to substitute; just copy over the parameter types and
2009 // fill in the function type.
2010 for (FunctionDecl::param_iterator P = Function->param_begin(),
2011 PEnd = Function->param_end();
2012 P != PEnd;
2013 ++P)
2014 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Douglas Gregor83314aa2009-07-08 20:55:45 +00002016 if (FunctionType)
2017 *FunctionType = Function->getType();
2018 return TDK_Success;
2019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Douglas Gregor83314aa2009-07-08 20:55:45 +00002021 // Substitution of the explicit template arguments into a function template
2022 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002023 SFINAETrap Trap(*this);
2024
Douglas Gregor83314aa2009-07-08 20:55:45 +00002025 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002026 // Template arguments that are present shall be specified in the
2027 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00002028 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00002029 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00002030 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00002031
2032 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002033 // explicitly-specified template arguments against this function template,
2034 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00002035 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002036 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002037 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2038 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002039 if (Inst)
2040 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Douglas Gregor83314aa2009-07-08 20:55:45 +00002042 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002043 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002044 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002045 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00002046 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002047 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00002048 if (Index >= TemplateParams->size())
2049 Index = TemplateParams->size() - 1;
2050 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002051 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00002052 }
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Douglas Gregor83314aa2009-07-08 20:55:45 +00002054 // Form the template argument list from the explicitly-specified
2055 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002056 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002057 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002058 Info.reset(ExplicitArgumentList);
Douglas Gregord3731192011-01-10 07:32:04 +00002059
John McCalldf41f182010-10-12 19:40:14 +00002060 // Template argument deduction and the final substitution should be
2061 // done in the context of the templated declaration. Explicit
2062 // argument substitution, on the other hand, needs to happen in the
2063 // calling context.
2064 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2065
Douglas Gregord3731192011-01-10 07:32:04 +00002066 // If we deduced template arguments for a template parameter pack,
2067 // note that the template argument pack is partially substituted and record
2068 // the explicit template arguments. They'll be used as part of deduction
2069 // for this template parameter pack.
Douglas Gregord3731192011-01-10 07:32:04 +00002070 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2071 const TemplateArgument &Arg = Builder[I];
2072 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregord3731192011-01-10 07:32:04 +00002073 CurrentInstantiationScope->SetPartiallySubstitutedPack(
2074 TemplateParams->getParam(I),
2075 Arg.pack_begin(),
2076 Arg.pack_size());
2077 break;
2078 }
2079 }
2080
Douglas Gregor83314aa2009-07-08 20:55:45 +00002081 // Instantiate the types of each of the function parameters given the
2082 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00002083 if (SubstParmTypes(Function->getLocation(),
2084 Function->param_begin(), Function->getNumParams(),
2085 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2086 ParamTypes))
2087 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002088
2089 // If the caller wants a full function type back, instantiate the return
2090 // type and form that function type.
2091 if (FunctionType) {
2092 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00002093 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002094 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002095 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00002096
2097 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00002098 = SubstType(Proto->getResultType(),
2099 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2100 Function->getTypeSpecStartLoc(),
2101 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002102 if (ResultType.isNull() || Trap.hasErrorOccurred())
2103 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002104
2105 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002106 ParamTypes.data(), ParamTypes.size(),
2107 Proto->isVariadic(),
2108 Proto->getTypeQuals(),
2109 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00002110 Function->getDeclName(),
2111 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002112 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2113 return TDK_SubstitutionFailure;
2114 }
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Douglas Gregor83314aa2009-07-08 20:55:45 +00002116 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002117 // Trailing template arguments that can be deduced (14.8.2) may be
2118 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002119 // template arguments can be deduced, they may all be omitted; in this
2120 // case, the empty template argument list <> itself may also be omitted.
2121 //
Douglas Gregord3731192011-01-10 07:32:04 +00002122 // Take all of the explicitly-specified arguments and put them into
2123 // the set of deduced template arguments. Explicitly-specified
2124 // parameter packs, however, will be set to NULL since the deduction
2125 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002126 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00002127 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2128 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2129 if (Arg.getKind() == TemplateArgument::Pack)
2130 Deduced.push_back(DeducedTemplateArgument());
2131 else
2132 Deduced.push_back(Arg);
2133 }
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Douglas Gregor83314aa2009-07-08 20:55:45 +00002135 return TDK_Success;
2136}
2137
Mike Stump1eb44332009-09-09 15:08:12 +00002138/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002139/// checking the deduced template arguments for completeness and forming
2140/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002141Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00002142Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00002143 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2144 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002145 FunctionDecl *&Specialization,
2146 TemplateDeductionInfo &Info) {
2147 TemplateParameterList *TemplateParams
2148 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Douglas Gregor83314aa2009-07-08 20:55:45 +00002150 // Template argument deduction for function templates in a SFINAE context.
2151 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002152 SFINAETrap Trap(*this);
2153
Douglas Gregor83314aa2009-07-08 20:55:45 +00002154 // Enter a new template instantiation context while we instantiate the
2155 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002156 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002157 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002158 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2159 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002160 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002161 return TDK_InstantiationDepth;
2162
John McCall96db3102010-04-29 01:18:58 +00002163 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002164
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002165 // C++ [temp.deduct.type]p2:
2166 // [...] or if any template argument remains neither deduced nor
2167 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00002168 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002169 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2170 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002171
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002172 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002173 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002174 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002175 // argument, because it was explicitly-specified. Just record the
2176 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002177 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002178 continue;
2179 }
2180
2181 // We have deduced this argument, so it still needs to be
2182 // checked and converted.
2183
2184 // First, for a non-type template parameter type that is
2185 // initialized by a declaration, we need the type of the
2186 // corresponding non-type template parameter.
2187 QualType NTTPType;
2188 if (NonTypeTemplateParmDecl *NTTP
2189 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002190 NTTPType = NTTP->getType();
2191 if (NTTPType->isDependentType()) {
2192 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2193 Builder.data(), Builder.size());
2194 NTTPType = SubstType(NTTPType,
2195 MultiLevelTemplateArgumentList(TemplateArgs),
2196 NTTP->getLocation(),
2197 NTTP->getDeclName());
2198 if (NTTPType.isNull()) {
2199 Info.Param = makeTemplateParameter(Param);
2200 // FIXME: These template arguments are temporary. Free them!
2201 Info.reset(TemplateArgumentList::CreateCopy(Context,
2202 Builder.data(),
2203 Builder.size()));
2204 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002205 }
2206 }
2207 }
2208
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002209 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002210 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002211 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002212 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002213 // FIXME: These template arguments are temporary. Free them!
2214 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002215 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002216 return TDK_SubstitutionFailure;
2217 }
2218
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002219 continue;
2220 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002221
2222 // C++0x [temp.arg.explicit]p3:
2223 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2224 // be deduced to an empty sequence of template arguments.
2225 // FIXME: Where did the word "trailing" come from?
2226 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002227 // We may have had explicitly-specified template arguments for this
2228 // template parameter pack. If so, our empty deduction extends the
2229 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2230 const TemplateArgument *ExplicitArgs;
2231 unsigned NumExplicitArgs;
2232 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2233 &NumExplicitArgs)
2234 == Param)
2235 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2236 else
2237 Builder.push_back(TemplateArgument(0, 0));
2238
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002239 continue;
2240 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002241
2242 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002243 TemplateArgumentLoc DefArg
2244 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2245 FunctionTemplate->getLocation(),
2246 FunctionTemplate->getSourceRange().getEnd(),
2247 Param,
2248 Builder);
2249
2250 // If there was no default argument, deduction is incomplete.
2251 if (DefArg.getArgument().isNull()) {
2252 Info.Param = makeTemplateParameter(
2253 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2254 return TDK_Incomplete;
2255 }
2256
2257 // Check whether we can actually use the default argument.
2258 if (CheckTemplateArgument(Param, DefArg,
2259 FunctionTemplate,
2260 FunctionTemplate->getLocation(),
2261 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002262 0, Builder,
Douglas Gregor02024a92010-03-28 02:42:43 +00002263 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002264 Info.Param = makeTemplateParameter(
2265 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002266 // FIXME: These template arguments are temporary. Free them!
2267 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2268 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002269 return TDK_SubstitutionFailure;
2270 }
2271
2272 // If we get here, we successfully used the default template argument.
2273 }
2274
2275 // Form the template argument list from the deduced template arguments.
2276 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002277 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002278 Info.reset(DeducedArgumentList);
2279
Mike Stump1eb44332009-09-09 15:08:12 +00002280 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002281 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002282 DeclContext *Owner = FunctionTemplate->getDeclContext();
2283 if (FunctionTemplate->getFriendObjectKind())
2284 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002285 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002286 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002287 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002288 if (!Specialization)
2289 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Douglas Gregorf8825742009-09-15 18:26:13 +00002291 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2292 FunctionTemplate->getCanonicalDecl());
2293
Mike Stump1eb44332009-09-09 15:08:12 +00002294 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002295 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002296 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2297 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002298 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Douglas Gregor83314aa2009-07-08 20:55:45 +00002300 // There may have been an error that did not prevent us from constructing a
2301 // declaration. Mark the declaration invalid and return with a substitution
2302 // failure.
2303 if (Trap.hasErrorOccurred()) {
2304 Specialization->setInvalidDecl(true);
2305 return TDK_SubstitutionFailure;
2306 }
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Douglas Gregor9b623632010-10-12 23:32:35 +00002308 // If we suppressed any diagnostics while performing template argument
2309 // deduction, and if we haven't already instantiated this declaration,
2310 // keep track of these diagnostics. They'll be emitted if this specialization
2311 // is actually used.
2312 if (Info.diag_begin() != Info.diag_end()) {
2313 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2314 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2315 if (Pos == SuppressedDiagnostics.end())
2316 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2317 .append(Info.diag_begin(), Info.diag_end());
2318 }
2319
Mike Stump1eb44332009-09-09 15:08:12 +00002320 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002321}
2322
John McCall9c72c602010-08-27 09:08:28 +00002323/// Gets the type of a function for template-argument-deducton
2324/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002325static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002326 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002327 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002329 if (Method->isInstance()) {
2330 // An instance method that's referenced in a form that doesn't
2331 // look like a member pointer is just invalid.
2332 if (!R.HasFormOfMemberPointer) return QualType();
2333
John McCalleff92132010-02-02 02:21:27 +00002334 return Context.getMemberPointerType(Fn->getType(),
2335 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002336 }
2337
2338 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002339 return Context.getPointerType(Fn->getType());
2340}
2341
2342/// Apply the deduction rules for overload sets.
2343///
2344/// \return the null type if this argument should be treated as an
2345/// undeduced context
2346static QualType
2347ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002348 Expr *Arg, QualType ParamType,
2349 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002350
2351 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002352
John McCall9c72c602010-08-27 09:08:28 +00002353 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002354
Douglas Gregor75f21af2010-08-30 21:04:23 +00002355 // C++0x [temp.deduct.call]p4
2356 unsigned TDF = 0;
2357 if (ParamWasReference)
2358 TDF |= TDF_ParamWithReferenceType;
2359 if (R.IsAddressOfOperand)
2360 TDF |= TDF_IgnoreQualifiers;
2361
John McCalleff92132010-02-02 02:21:27 +00002362 // If there were explicit template arguments, we can only find
2363 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2364 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002365 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002366 // But we can still look for an explicit specialization.
2367 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002368 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002369 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002370 return QualType();
2371 }
2372
2373 // C++0x [temp.deduct.call]p6:
2374 // When P is a function type, pointer to function type, or pointer
2375 // to member function type:
2376
2377 if (!ParamType->isFunctionType() &&
2378 !ParamType->isFunctionPointerType() &&
2379 !ParamType->isMemberFunctionPointerType())
2380 return QualType();
2381
2382 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002383 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2384 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002385 NamedDecl *D = (*I)->getUnderlyingDecl();
2386
2387 // - If the argument is an overload set containing one or more
2388 // function templates, the parameter is treated as a
2389 // non-deduced context.
2390 if (isa<FunctionTemplateDecl>(D))
2391 return QualType();
2392
2393 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002394 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2395 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002396
Douglas Gregor75f21af2010-08-30 21:04:23 +00002397 // Function-to-pointer conversion.
2398 if (!ParamWasReference && ParamType->isPointerType() &&
2399 ArgType->isFunctionType())
2400 ArgType = S.Context.getPointerType(ArgType);
2401
John McCalleff92132010-02-02 02:21:27 +00002402 // - If the argument is an overload set (not containing function
2403 // templates), trial argument deduction is attempted using each
2404 // of the members of the set. If deduction succeeds for only one
2405 // of the overload set members, that member is used as the
2406 // argument value for the deduction. If deduction succeeds for
2407 // more than one member of the overload set the parameter is
2408 // treated as a non-deduced context.
2409
2410 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2411 // Type deduction is done independently for each P/A pair, and
2412 // the deduced template argument values are then combined.
2413 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002414 llvm::SmallVector<DeducedTemplateArgument, 8>
2415 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002416 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002417 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002418 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002419 ParamType, ArgType,
2420 Info, Deduced, TDF);
2421 if (Result) continue;
2422 if (!Match.isNull()) return QualType();
2423 Match = ArgType;
2424 }
2425
2426 return Match;
2427}
2428
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002429/// \brief Perform the adjustments to the parameter and argument types
2430/// described in C++ [temp.deduct.call].
2431///
2432/// \returns true if the caller should not attempt to perform any template
2433/// argument deduction based on this P/A pair.
2434static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2435 TemplateParameterList *TemplateParams,
2436 QualType &ParamType,
2437 QualType &ArgType,
2438 Expr *Arg,
2439 unsigned &TDF) {
2440 // C++0x [temp.deduct.call]p3:
2441 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2442 // are ignored for type deduction.
2443 if (ParamType.getCVRQualifiers())
2444 ParamType = ParamType.getLocalUnqualifiedType();
2445 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2446 if (ParamRefType) {
Douglas Gregor2ad746a2011-01-21 05:18:22 +00002447 // [C++0x] If P is an rvalue reference to a cv-unqualified
2448 // template parameter and the argument is an lvalue, the type
2449 // "lvalue reference to A" is used in place of A for type
2450 // deduction.
2451 if (const RValueReferenceType *RValueRef
2452 = dyn_cast<RValueReferenceType>(ParamType)) {
2453 if (!RValueRef->getPointeeType().getQualifiers() &&
2454 isa<TemplateTypeParmType>(RValueRef->getPointeeType()) &&
2455 Arg->Classify(S.Context).isLValue())
2456 ArgType = S.Context.getLValueReferenceType(ArgType);
2457 }
2458
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002459 // [...] If P is a reference type, the type referred to by P is used
2460 // for type deduction.
2461 ParamType = ParamRefType->getPointeeType();
2462 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002463
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002464 // Overload sets usually make this parameter an undeduced
2465 // context, but there are sometimes special circumstances.
2466 if (ArgType == S.Context.OverloadTy) {
2467 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2468 Arg, ParamType,
2469 ParamRefType != 0);
2470 if (ArgType.isNull())
2471 return true;
2472 }
2473
2474 if (ParamRefType) {
2475 // C++0x [temp.deduct.call]p3:
2476 // [...] If P is of the form T&&, where T is a template parameter, and
2477 // the argument is an lvalue, the type A& is used in place of A for
2478 // type deduction.
2479 if (ParamRefType->isRValueReferenceType() &&
2480 ParamRefType->getAs<TemplateTypeParmType>() &&
2481 Arg->isLValue())
2482 ArgType = S.Context.getLValueReferenceType(ArgType);
2483 } else {
2484 // C++ [temp.deduct.call]p2:
2485 // If P is not a reference type:
2486 // - If A is an array type, the pointer type produced by the
2487 // array-to-pointer standard conversion (4.2) is used in place of
2488 // A for type deduction; otherwise,
2489 if (ArgType->isArrayType())
2490 ArgType = S.Context.getArrayDecayedType(ArgType);
2491 // - If A is a function type, the pointer type produced by the
2492 // function-to-pointer standard conversion (4.3) is used in place
2493 // of A for type deduction; otherwise,
2494 else if (ArgType->isFunctionType())
2495 ArgType = S.Context.getPointerType(ArgType);
2496 else {
2497 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2498 // type are ignored for type deduction.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002499 if (ArgType.getCVRQualifiers())
2500 ArgType = ArgType.getUnqualifiedType();
2501 }
2502 }
2503
2504 // C++0x [temp.deduct.call]p4:
2505 // In general, the deduction process attempts to find template argument
2506 // values that will make the deduced A identical to A (after the type A
2507 // is transformed as described above). [...]
2508 TDF = TDF_SkipNonDependent;
2509
2510 // - If the original P is a reference type, the deduced A (i.e., the
2511 // type referred to by the reference) can be more cv-qualified than
2512 // the transformed A.
2513 if (ParamRefType)
2514 TDF |= TDF_ParamWithReferenceType;
2515 // - The transformed A can be another pointer or pointer to member
2516 // type that can be converted to the deduced A via a qualification
2517 // conversion (4.4).
2518 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2519 ArgType->isObjCObjectPointerType())
2520 TDF |= TDF_IgnoreQualifiers;
2521 // - If P is a class and P has the form simple-template-id, then the
2522 // transformed A can be a derived class of the deduced A. Likewise,
2523 // if P is a pointer to a class of the form simple-template-id, the
2524 // transformed A can be a pointer to a derived class pointed to by
2525 // the deduced A.
2526 if (isSimpleTemplateIdType(ParamType) ||
2527 (isa<PointerType>(ParamType) &&
2528 isSimpleTemplateIdType(
2529 ParamType->getAs<PointerType>()->getPointeeType())))
2530 TDF |= TDF_DerivedClass;
2531
2532 return false;
2533}
2534
Douglas Gregore53060f2009-06-25 22:08:12 +00002535/// \brief Perform template argument deduction from a function call
2536/// (C++ [temp.deduct.call]).
2537///
2538/// \param FunctionTemplate the function template for which we are performing
2539/// template argument deduction.
2540///
Douglas Gregor48026d22010-01-11 18:40:55 +00002541/// \param ExplicitTemplateArguments the explicit template arguments provided
2542/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002543///
Douglas Gregore53060f2009-06-25 22:08:12 +00002544/// \param Args the function call arguments
2545///
2546/// \param NumArgs the number of arguments in Args
2547///
Douglas Gregor48026d22010-01-11 18:40:55 +00002548/// \param Name the name of the function being called. This is only significant
2549/// when the function template is a conversion function template, in which
2550/// case this routine will also perform template argument deduction based on
2551/// the function to which
2552///
Douglas Gregore53060f2009-06-25 22:08:12 +00002553/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002554/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002555/// template argument deduction.
2556///
2557/// \param Info the argument will be updated to provide additional information
2558/// about template argument deduction.
2559///
2560/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002561Sema::TemplateDeductionResult
2562Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002563 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002564 Expr **Args, unsigned NumArgs,
2565 FunctionDecl *&Specialization,
2566 TemplateDeductionInfo &Info) {
2567 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002568
Douglas Gregore53060f2009-06-25 22:08:12 +00002569 // C++ [temp.deduct.call]p1:
2570 // Template argument deduction is done by comparing each function template
2571 // parameter type (call it P) with the type of the corresponding argument
2572 // of the call (call it A) as described below.
2573 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002574 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002575 return TDK_TooFewArguments;
2576 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002577 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002578 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002579 if (Proto->isTemplateVariadic())
2580 /* Do nothing */;
2581 else if (Proto->isVariadic())
2582 CheckArgs = Function->getNumParams();
2583 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002584 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002585 }
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002587 // The types of the parameters from which we will perform template argument
2588 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002589 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002590 TemplateParameterList *TemplateParams
2591 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002592 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002593 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002594 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002595 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002596 TemplateDeductionResult Result =
2597 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002598 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002599 Deduced,
2600 ParamTypes,
2601 0,
2602 Info);
2603 if (Result)
2604 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002605
2606 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002607 } else {
2608 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002609 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002610 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2611 }
Mike Stump1eb44332009-09-09 15:08:12 +00002612
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002613 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002614 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002615 unsigned ArgIdx = 0;
2616 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2617 ParamIdx != NumParams; ++ParamIdx) {
2618 QualType ParamType = ParamTypes[ParamIdx];
2619
2620 const PackExpansionType *ParamExpansion
2621 = dyn_cast<PackExpansionType>(ParamType);
2622 if (!ParamExpansion) {
2623 // Simple case: matching a function parameter to a function argument.
2624 if (ArgIdx >= CheckArgs)
2625 break;
2626
2627 Expr *Arg = Args[ArgIdx++];
2628 QualType ArgType = Arg->getType();
2629 unsigned TDF = 0;
2630 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2631 ParamType, ArgType, Arg,
2632 TDF))
2633 continue;
2634
2635 if (TemplateDeductionResult Result
2636 = ::DeduceTemplateArguments(*this, TemplateParams,
2637 ParamType, ArgType, Info, Deduced,
2638 TDF))
2639 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002641 // FIXME: we need to check that the deduced A is the same as A,
2642 // modulo the various allowed differences.
2643 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002644 }
2645
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002646 // C++0x [temp.deduct.call]p1:
2647 // For a function parameter pack that occurs at the end of the
2648 // parameter-declaration-list, the type A of each remaining argument of
2649 // the call is compared with the type P of the declarator-id of the
2650 // function parameter pack. Each comparison deduces template arguments
2651 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002652 // the function parameter pack. For a function parameter pack that does
2653 // not occur at the end of the parameter-declaration-list, the type of
2654 // the parameter pack is a non-deduced context.
2655 if (ParamIdx + 1 < NumParams)
2656 break;
2657
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002658 QualType ParamPattern = ParamExpansion->getPattern();
2659 llvm::SmallVector<unsigned, 2> PackIndices;
2660 {
2661 llvm::BitVector SawIndices(TemplateParams->size());
2662 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2663 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2664 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2665 unsigned Depth, Index;
2666 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2667 if (Depth == 0 && !SawIndices[Index]) {
2668 SawIndices[Index] = true;
2669 PackIndices.push_back(Index);
2670 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002671 }
2672 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002673 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2674
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002675 // Keep track of the deduced template arguments for each parameter pack
2676 // expanded by this pack expansion (the outer index) and for each
2677 // template argument (the inner SmallVectors).
2678 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00002679 NewlyDeducedPacks(PackIndices.size());
Douglas Gregord3731192011-01-10 07:32:04 +00002680 llvm::SmallVector<DeducedTemplateArgument, 2>
2681 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00002682 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
2683 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002684 bool HasAnyArguments = false;
2685 for (; ArgIdx < NumArgs; ++ArgIdx) {
2686 HasAnyArguments = true;
2687
2688 ParamType = ParamPattern;
2689 Expr *Arg = Args[ArgIdx];
2690 QualType ArgType = Arg->getType();
2691 unsigned TDF = 0;
2692 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2693 ParamType, ArgType, Arg,
2694 TDF)) {
2695 // We can't actually perform any deduction for this argument, so stop
2696 // deduction at this point.
2697 ++ArgIdx;
2698 break;
2699 }
2700
2701 if (TemplateDeductionResult Result
2702 = ::DeduceTemplateArguments(*this, TemplateParams,
2703 ParamType, ArgType, Info, Deduced,
2704 TDF))
2705 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002707 // Capture the deduced template arguments for each parameter pack expanded
2708 // by this pack expansion, add them to the list of arguments we've deduced
2709 // for that pack, then clear out the deduced argument.
2710 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2711 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2712 if (!DeducedArg.isNull()) {
2713 NewlyDeducedPacks[I].push_back(DeducedArg);
2714 DeducedArg = DeducedTemplateArgument();
2715 }
2716 }
2717 }
2718
2719 // Build argument packs for each of the parameter packs expanded by this
2720 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00002721 if (Sema::TemplateDeductionResult Result
2722 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
2723 Deduced, PackIndices, SavedPacks,
2724 NewlyDeducedPacks, Info))
2725 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002726
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002727 // After we've matching against a parameter pack, we're done.
2728 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002729 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002730
Mike Stump1eb44332009-09-09 15:08:12 +00002731 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002732 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002733 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002734}
2735
Douglas Gregor83314aa2009-07-08 20:55:45 +00002736/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002737/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2738/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002739///
2740/// \param FunctionTemplate the function template for which we are performing
2741/// template argument deduction.
2742///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002743/// \param ExplicitTemplateArguments the explicitly-specified template
2744/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002745///
2746/// \param ArgFunctionType the function type that will be used as the
2747/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002748/// function template's function type. This type may be NULL, if there is no
2749/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002750///
2751/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002752/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002753/// template argument deduction.
2754///
2755/// \param Info the argument will be updated to provide additional information
2756/// about template argument deduction.
2757///
2758/// \returns the result of template argument deduction.
2759Sema::TemplateDeductionResult
2760Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002761 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002762 QualType ArgFunctionType,
2763 FunctionDecl *&Specialization,
2764 TemplateDeductionInfo &Info) {
2765 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2766 TemplateParameterList *TemplateParams
2767 = FunctionTemplate->getTemplateParameters();
2768 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002769
Douglas Gregor83314aa2009-07-08 20:55:45 +00002770 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002771 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002772 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2773 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002774 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002775 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002776 if (TemplateDeductionResult Result
2777 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002778 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002779 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002780 &FunctionType, Info))
2781 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002782
2783 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002784 }
2785
2786 // Template argument deduction for function templates in a SFINAE context.
2787 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002788 SFINAETrap Trap(*this);
2789
John McCalleff92132010-02-02 02:21:27 +00002790 Deduced.resize(TemplateParams->size());
2791
Douglas Gregor4b52e252009-12-21 23:17:24 +00002792 if (!ArgFunctionType.isNull()) {
2793 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002794 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002795 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002796 FunctionType, ArgFunctionType, Info,
Douglas Gregor73b3cf62011-01-25 17:19:08 +00002797 Deduced, TDF_TopLevelParameterTypeList))
Douglas Gregor4b52e252009-12-21 23:17:24 +00002798 return Result;
2799 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002800
2801 if (TemplateDeductionResult Result
2802 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2803 NumExplicitlySpecified,
2804 Specialization, Info))
2805 return Result;
2806
2807 // If the requested function type does not match the actual type of the
2808 // specialization, template argument deduction fails.
2809 if (!ArgFunctionType.isNull() &&
2810 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2811 return TDK_NonDeducedMismatch;
2812
2813 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002814}
2815
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002816/// \brief Deduce template arguments for a templated conversion
2817/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2818/// conversion function template specialization.
2819Sema::TemplateDeductionResult
2820Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2821 QualType ToType,
2822 CXXConversionDecl *&Specialization,
2823 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002824 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002825 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2826 QualType FromType = Conv->getConversionType();
2827
2828 // Canonicalize the types for deduction.
2829 QualType P = Context.getCanonicalType(FromType);
2830 QualType A = Context.getCanonicalType(ToType);
2831
2832 // C++0x [temp.deduct.conv]p3:
2833 // If P is a reference type, the type referred to by P is used for
2834 // type deduction.
2835 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2836 P = PRef->getPointeeType();
2837
2838 // C++0x [temp.deduct.conv]p3:
2839 // If A is a reference type, the type referred to by A is used
2840 // for type deduction.
2841 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2842 A = ARef->getPointeeType();
2843 // C++ [temp.deduct.conv]p2:
2844 //
Mike Stump1eb44332009-09-09 15:08:12 +00002845 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002846 else {
2847 assert(!A->isReferenceType() && "Reference types were handled above");
2848
2849 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002850 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002851 // of P for type deduction; otherwise,
2852 if (P->isArrayType())
2853 P = Context.getArrayDecayedType(P);
2854 // - If P is a function type, the pointer type produced by the
2855 // function-to-pointer standard conversion (4.3) is used in
2856 // place of P for type deduction; otherwise,
2857 else if (P->isFunctionType())
2858 P = Context.getPointerType(P);
2859 // - If P is a cv-qualified type, the top level cv-qualifiers of
2860 // P’s type are ignored for type deduction.
2861 else
2862 P = P.getUnqualifiedType();
2863
2864 // C++0x [temp.deduct.conv]p3:
2865 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2866 // type are ignored for type deduction.
2867 A = A.getUnqualifiedType();
2868 }
2869
2870 // Template argument deduction for function templates in a SFINAE context.
2871 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002872 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002873
2874 // C++ [temp.deduct.conv]p1:
2875 // Template argument deduction is done by comparing the return
2876 // type of the template conversion function (call it P) with the
2877 // type that is required as the result of the conversion (call it
2878 // A) as described in 14.8.2.4.
2879 TemplateParameterList *TemplateParams
2880 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002881 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002882 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002883
2884 // C++0x [temp.deduct.conv]p4:
2885 // In general, the deduction process attempts to find template
2886 // argument values that will make the deduced A identical to
2887 // A. However, there are two cases that allow a difference:
2888 unsigned TDF = 0;
2889 // - If the original A is a reference type, A can be more
2890 // cv-qualified than the deduced A (i.e., the type referred to
2891 // by the reference)
2892 if (ToType->isReferenceType())
2893 TDF |= TDF_ParamWithReferenceType;
2894 // - The deduced A can be another pointer or pointer to member
2895 // type that can be converted to A via a qualification
2896 // conversion.
2897 //
2898 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2899 // both P and A are pointers or member pointers. In this case, we
2900 // just ignore cv-qualifiers completely).
2901 if ((P->isPointerType() && A->isPointerType()) ||
2902 (P->isMemberPointerType() && P->isMemberPointerType()))
2903 TDF |= TDF_IgnoreQualifiers;
2904 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002905 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002906 P, A, Info, Deduced, TDF))
2907 return Result;
2908
2909 // FIXME: we need to check that the deduced A is the same as A,
2910 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002911
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002912 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002913 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002914 FunctionDecl *Spec = 0;
2915 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002916 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2917 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002918 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2919 return Result;
2920}
2921
Douglas Gregor4b52e252009-12-21 23:17:24 +00002922/// \brief Deduce template arguments for a function template when there is
2923/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2924///
2925/// \param FunctionTemplate the function template for which we are performing
2926/// template argument deduction.
2927///
2928/// \param ExplicitTemplateArguments the explicitly-specified template
2929/// arguments.
2930///
2931/// \param Specialization if template argument deduction was successful,
2932/// this will be set to the function template specialization produced by
2933/// template argument deduction.
2934///
2935/// \param Info the argument will be updated to provide additional information
2936/// about template argument deduction.
2937///
2938/// \returns the result of template argument deduction.
2939Sema::TemplateDeductionResult
2940Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2941 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2942 FunctionDecl *&Specialization,
2943 TemplateDeductionInfo &Info) {
2944 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2945 QualType(), Specialization, Info);
2946}
2947
Douglas Gregor8a514912009-09-14 18:39:43 +00002948static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002949MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2950 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002951 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002952 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002953
2954/// \brief If this is a non-static member function,
2955static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2956 CXXMethodDecl *Method,
2957 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2958 if (Method->isStatic())
2959 return;
2960
2961 // C++ [over.match.funcs]p4:
2962 //
2963 // For non-static member functions, the type of the implicit
2964 // object parameter is
2965 // — "lvalue reference to cv X" for functions declared without a
2966 // ref-qualifier or with the & ref-qualifier
2967 // - "rvalue reference to cv X" for functions declared with the
2968 // && ref-qualifier
2969 //
2970 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2971 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2972 ArgTy = Context.getQualifiedType(ArgTy,
2973 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2974 ArgTy = Context.getLValueReferenceType(ArgTy);
2975 ArgTypes.push_back(ArgTy);
2976}
2977
Douglas Gregor8a514912009-09-14 18:39:43 +00002978/// \brief Determine whether the function template \p FT1 is at least as
2979/// specialized as \p FT2.
2980static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002981 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002982 FunctionTemplateDecl *FT1,
2983 FunctionTemplateDecl *FT2,
2984 TemplatePartialOrderingContext TPOC,
Douglas Gregorb939a192011-01-21 17:29:42 +00002985 unsigned NumCallArguments,
2986 llvm::SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002987 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2988 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2989 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2990 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2991
2992 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2993 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002994 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002995 Deduced.resize(TemplateParams->size());
2996
2997 // C++0x [temp.deduct.partial]p3:
2998 // The types used to determine the ordering depend on the context in which
2999 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00003000 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003001 CXXMethodDecl *Method1 = 0;
3002 CXXMethodDecl *Method2 = 0;
3003 bool IsNonStatic2 = false;
3004 bool IsNonStatic1 = false;
3005 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003006 switch (TPOC) {
3007 case TPOC_Call: {
3008 // - In the context of a function call, the function parameter types are
3009 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003010 Method1 = dyn_cast<CXXMethodDecl>(FD1);
3011 Method2 = dyn_cast<CXXMethodDecl>(FD2);
3012 IsNonStatic1 = Method1 && !Method1->isStatic();
3013 IsNonStatic2 = Method2 && !Method2->isStatic();
3014
3015 // C++0x [temp.func.order]p3:
3016 // [...] If only one of the function templates is a non-static
3017 // member, that function template is considered to have a new
3018 // first parameter inserted in its function parameter list. The
3019 // new parameter is of type "reference to cv A," where cv are
3020 // the cv-qualifiers of the function template (if any) and A is
3021 // the class of which the function template is a member.
3022 //
3023 // C++98/03 doesn't have this provision, so instead we drop the
3024 // first argument of the free function or static member, which
3025 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00003026 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003027 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
3028 IsNonStatic2 && !IsNonStatic1;
3029 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003030 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
Douglas Gregor77bc5722010-11-12 23:44:13 +00003031 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003032 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00003033
3034 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003035 Skip2 = !S.getLangOptions().CPlusPlus0x &&
3036 IsNonStatic1 && !IsNonStatic2;
3037 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00003038 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
3039 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003040 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003041
3042 // C++ [temp.func.order]p5:
3043 // The presence of unused ellipsis and default arguments has no effect on
3044 // the partial ordering of function templates.
3045 if (Args1.size() > NumCallArguments)
3046 Args1.resize(NumCallArguments);
3047 if (Args2.size() > NumCallArguments)
3048 Args2.resize(NumCallArguments);
3049 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
3050 Args1.data(), Args1.size(), Info, Deduced,
3051 TDF_None, /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003052 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003053 return false;
3054
3055 break;
3056 }
3057
3058 case TPOC_Conversion:
3059 // - In the context of a call to a conversion operator, the return types
3060 // of the conversion function templates are used.
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003061 if (DeduceTemplateArguments(S, TemplateParams, Proto2->getResultType(),
3062 Proto1->getResultType(), Info, Deduced,
3063 TDF_None, /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003064 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003065 return false;
3066 break;
3067
3068 case TPOC_Other:
3069 // - In other contexts (14.6.6.2) the function template’s function type
3070 // is used.
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003071 // FIXME: Don't we actually want to perform the adjustments on the parameter
3072 // types?
3073 if (DeduceTemplateArguments(S, TemplateParams, FD2->getType(),
3074 FD1->getType(), Info, Deduced, TDF_None,
Douglas Gregorb939a192011-01-21 17:29:42 +00003075 /*PartialOrdering=*/true, RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003076 return false;
3077 break;
3078 }
3079
3080 // C++0x [temp.deduct.partial]p11:
3081 // In most cases, all template parameters must have values in order for
3082 // deduction to succeed, but for partial ordering purposes a template
3083 // parameter may remain without a value provided it is not used in the
3084 // types being used for partial ordering. [ Note: a template parameter used
3085 // in a non-deduced context is considered used. -end note]
3086 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3087 for (; ArgIdx != NumArgs; ++ArgIdx)
3088 if (Deduced[ArgIdx].isNull())
3089 break;
3090
3091 if (ArgIdx == NumArgs) {
3092 // All template arguments were deduced. FT1 is at least as specialized
3093 // as FT2.
3094 return true;
3095 }
3096
Douglas Gregore73bb602009-09-14 21:25:05 +00003097 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003098 llvm::SmallVector<bool, 4> UsedParameters;
3099 UsedParameters.resize(TemplateParams->size());
3100 switch (TPOC) {
3101 case TPOC_Call: {
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003102 unsigned NumParams = std::min(NumCallArguments,
3103 std::min(Proto1->getNumArgs(),
3104 Proto2->getNumArgs()));
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003105 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3106 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3107 TemplateParams->getDepth(), UsedParameters);
3108 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003109 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3110 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003111 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003112 break;
3113 }
3114
3115 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003116 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3117 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003118 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003119 break;
3120
3121 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003122 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3123 TemplateParams->getDepth(),
3124 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003125 break;
3126 }
3127
3128 for (; ArgIdx != NumArgs; ++ArgIdx)
3129 // If this argument had no value deduced but was used in one of the types
3130 // used for partial ordering, then deduction fails.
3131 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3132 return false;
3133
3134 return true;
3135}
3136
Douglas Gregor9da95e62011-01-16 16:03:23 +00003137/// \brief Determine whether this a function template whose parameter-type-list
3138/// ends with a function parameter pack.
3139static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
3140 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3141 unsigned NumParams = Function->getNumParams();
3142 if (NumParams == 0)
3143 return false;
3144
3145 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
3146 if (!Last->isParameterPack())
3147 return false;
3148
3149 // Make sure that no previous parameter is a parameter pack.
3150 while (--NumParams > 0) {
3151 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
3152 return false;
3153 }
3154
3155 return true;
3156}
Douglas Gregor8a514912009-09-14 18:39:43 +00003157
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003158/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003159/// to the rules of function template partial ordering (C++ [temp.func.order]).
3160///
3161/// \param FT1 the first function template
3162///
3163/// \param FT2 the second function template
3164///
Douglas Gregor8a514912009-09-14 18:39:43 +00003165/// \param TPOC the context in which we are performing partial ordering of
3166/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003167///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003168/// \param NumCallArguments The number of arguments in a call, used only
3169/// when \c TPOC is \c TPOC_Call.
3170///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003171/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003172/// template is more specialized, returns NULL.
3173FunctionTemplateDecl *
3174Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3175 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003176 SourceLocation Loc,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003177 TemplatePartialOrderingContext TPOC,
3178 unsigned NumCallArguments) {
Douglas Gregorb939a192011-01-21 17:29:42 +00003179 llvm::SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003180 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
3181 NumCallArguments, 0);
John McCall5769d612010-02-08 23:07:23 +00003182 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003183 NumCallArguments,
Douglas Gregorb939a192011-01-21 17:29:42 +00003184 &RefParamComparisons);
Douglas Gregor8a514912009-09-14 18:39:43 +00003185
3186 if (Better1 != Better2) // We have a clear winner
3187 return Better1? FT1 : FT2;
3188
3189 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003190 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003191
Douglas Gregor8a514912009-09-14 18:39:43 +00003192 // C++0x [temp.deduct.partial]p10:
3193 // If for each type being considered a given template is at least as
3194 // specialized for all types and more specialized for some set of types and
3195 // the other template is not more specialized for any types or is not at
3196 // least as specialized for any types, then the given template is more
3197 // specialized than the other template. Otherwise, neither template is more
3198 // specialized than the other.
3199 Better1 = false;
3200 Better2 = false;
Douglas Gregorb939a192011-01-21 17:29:42 +00003201 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003202 // C++0x [temp.deduct.partial]p9:
3203 // If, for a given type, deduction succeeds in both directions (i.e., the
Douglas Gregorb939a192011-01-21 17:29:42 +00003204 // types are identical after the transformations above) and both P and A
3205 // were reference types (before being replaced with the type referred to
3206 // above):
3207
3208 // -- if the type from the argument template was an lvalue reference
3209 // and the type from the parameter template was not, the argument
3210 // type is considered to be more specialized than the other;
3211 // otherwise,
3212 if (!RefParamComparisons[I].ArgIsRvalueRef &&
3213 RefParamComparisons[I].ParamIsRvalueRef) {
3214 Better2 = true;
3215 if (Better1)
3216 return 0;
3217 continue;
3218 } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
3219 RefParamComparisons[I].ArgIsRvalueRef) {
3220 Better1 = true;
3221 if (Better2)
3222 return 0;
3223 continue;
Douglas Gregor8a514912009-09-14 18:39:43 +00003224 }
Douglas Gregorb939a192011-01-21 17:29:42 +00003225
3226 // -- if the type from the argument template is more cv-qualified than
3227 // the type from the parameter template (as described above), the
3228 // argument type is considered to be more specialized than the
3229 // other; otherwise,
3230 switch (RefParamComparisons[I].Qualifiers) {
3231 case NeitherMoreQualified:
3232 break;
3233
3234 case ParamMoreQualified:
3235 Better1 = true;
3236 if (Better2)
3237 return 0;
3238 continue;
3239
3240 case ArgMoreQualified:
3241 Better2 = true;
3242 if (Better1)
3243 return 0;
3244 continue;
3245 }
3246
3247 // -- neither type is more specialized than the other.
Douglas Gregor8a514912009-09-14 18:39:43 +00003248 }
3249
3250 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003251 if (Better1)
3252 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003253 else if (Better2)
3254 return FT2;
Douglas Gregor9da95e62011-01-16 16:03:23 +00003255
3256 // FIXME: This mimics what GCC implements, but doesn't match up with the
3257 // proposed resolution for core issue 692. This area needs to be sorted out,
3258 // but for now we attempt to maintain compatibility.
3259 bool Variadic1 = isVariadicFunctionTemplate(FT1);
3260 bool Variadic2 = isVariadicFunctionTemplate(FT2);
3261 if (Variadic1 != Variadic2)
3262 return Variadic1? FT2 : FT1;
3263
3264 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003265}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003266
Douglas Gregord5a423b2009-09-25 18:43:00 +00003267/// \brief Determine if the two templates are equivalent.
3268static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3269 if (T1 == T2)
3270 return true;
3271
3272 if (!T1 || !T2)
3273 return false;
3274
3275 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3276}
3277
3278/// \brief Retrieve the most specialized of the given function template
3279/// specializations.
3280///
John McCallc373d482010-01-27 01:50:18 +00003281/// \param SpecBegin the start iterator of the function template
3282/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003283///
John McCallc373d482010-01-27 01:50:18 +00003284/// \param SpecEnd the end iterator of the function template
3285/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003286///
3287/// \param TPOC the partial ordering context to use to compare the function
3288/// template specializations.
3289///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003290/// \param NumCallArguments The number of arguments in a call, used only
3291/// when \c TPOC is \c TPOC_Call.
3292///
Douglas Gregord5a423b2009-09-25 18:43:00 +00003293/// \param Loc the location where the ambiguity or no-specializations
3294/// diagnostic should occur.
3295///
3296/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3297/// no matching candidates.
3298///
3299/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3300/// occurs.
3301///
3302/// \param CandidateDiag partial diagnostic used for each function template
3303/// specialization that is a candidate in the ambiguous ordering. One parameter
3304/// in this diagnostic should be unbound, which will correspond to the string
3305/// describing the template arguments for the function template specialization.
3306///
3307/// \param Index if non-NULL and the result of this function is non-nULL,
3308/// receives the index corresponding to the resulting function template
3309/// specialization.
3310///
3311/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003312/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003313///
3314/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3315/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003316UnresolvedSetIterator
3317Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003318 UnresolvedSetIterator SpecEnd,
John McCallc373d482010-01-27 01:50:18 +00003319 TemplatePartialOrderingContext TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003320 unsigned NumCallArguments,
John McCallc373d482010-01-27 01:50:18 +00003321 SourceLocation Loc,
3322 const PartialDiagnostic &NoneDiag,
3323 const PartialDiagnostic &AmbigDiag,
3324 const PartialDiagnostic &CandidateDiag) {
3325 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003326 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003327 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003328 }
3329
John McCallc373d482010-01-27 01:50:18 +00003330 if (SpecBegin + 1 == SpecEnd)
3331 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003332
3333 // Find the function template that is better than all of the templates it
3334 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003335 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003336 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003337 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003338 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003339 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3340 FunctionTemplateDecl *Challenger
3341 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003342 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003343 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003344 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003345 Challenger)) {
3346 Best = I;
3347 BestTemplate = Challenger;
3348 }
3349 }
3350
3351 // Make sure that the "best" function template is more specialized than all
3352 // of the others.
3353 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003354 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3355 FunctionTemplateDecl *Challenger
3356 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003357 if (I != Best &&
3358 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003359 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003360 BestTemplate)) {
3361 Ambiguous = true;
3362 break;
3363 }
3364 }
3365
3366 if (!Ambiguous) {
3367 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003368 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003369 }
3370
3371 // Diagnose the ambiguity.
3372 Diag(Loc, AmbigDiag);
3373
3374 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003375 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3376 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003377 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003378 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3379 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003380
John McCallc373d482010-01-27 01:50:18 +00003381 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003382}
3383
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003384/// \brief Returns the more specialized class template partial specialization
3385/// according to the rules of partial ordering of class template partial
3386/// specializations (C++ [temp.class.order]).
3387///
3388/// \param PS1 the first class template partial specialization
3389///
3390/// \param PS2 the second class template partial specialization
3391///
3392/// \returns the more specialized class template partial specialization. If
3393/// neither partial specialization is more specialized, returns NULL.
3394ClassTemplatePartialSpecializationDecl *
3395Sema::getMoreSpecializedPartialSpecialization(
3396 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003397 ClassTemplatePartialSpecializationDecl *PS2,
3398 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003399 // C++ [temp.class.order]p1:
3400 // For two class template partial specializations, the first is at least as
3401 // specialized as the second if, given the following rewrite to two
3402 // function templates, the first function template is at least as
3403 // specialized as the second according to the ordering rules for function
3404 // templates (14.6.6.2):
3405 // - the first function template has the same template parameters as the
3406 // first partial specialization and has a single function parameter
3407 // whose type is a class template specialization with the template
3408 // arguments of the first partial specialization, and
3409 // - the second function template has the same template parameters as the
3410 // second partial specialization and has a single function parameter
3411 // whose type is a class template specialization with the template
3412 // arguments of the second partial specialization.
3413 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003414 // Rather than synthesize function templates, we merely perform the
3415 // equivalent partial ordering by performing deduction directly on
3416 // the template arguments of the class template partial
3417 // specializations. This computation is slightly simpler than the
3418 // general problem of function template partial ordering, because
3419 // class template partial specializations are more constrained. We
3420 // know that every template parameter is deducible from the class
3421 // template partial specialization's template arguments, for
3422 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003423 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003424 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003425
3426 QualType PT1 = PS1->getInjectedSpecializationType();
3427 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003428
3429 // Determine whether PS1 is at least as specialized as PS2
3430 Deduced.resize(PS2->getTemplateParameters()->size());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003431 bool Better1 = !::DeduceTemplateArguments(*this, PS2->getTemplateParameters(),
3432 PT2, PT1, Info, Deduced, TDF_None,
3433 /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003434 /*RefParamComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003435 if (Better1) {
3436 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3437 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003438 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3439 PS1->getTemplateArgs(),
3440 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003441 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003442
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003443 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003444 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003445 Deduced.resize(PS1->getTemplateParameters()->size());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003446 bool Better2 = !::DeduceTemplateArguments(*this, PS1->getTemplateParameters(),
3447 PT1, PT2, Info, Deduced, TDF_None,
3448 /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003449 /*RefParamComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003450 if (Better2) {
3451 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3452 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003453 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3454 PS2->getTemplateArgs(),
3455 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003456 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003457
3458 if (Better1 == Better2)
3459 return 0;
3460
3461 return Better1? PS1 : PS2;
3462}
3463
Mike Stump1eb44332009-09-09 15:08:12 +00003464static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003465MarkUsedTemplateParameters(Sema &SemaRef,
3466 const TemplateArgument &TemplateArg,
3467 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003468 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003469 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003470
Douglas Gregore73bb602009-09-14 21:25:05 +00003471/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003472/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003473static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003474MarkUsedTemplateParameters(Sema &SemaRef,
3475 const Expr *E,
3476 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003477 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003478 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003479 // We can deduce from a pack expansion.
3480 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3481 E = Expansion->getPattern();
3482
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003483 // Skip through any implicit casts we added while type-checking.
3484 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3485 E = ICE->getSubExpr();
3486
Douglas Gregore73bb602009-09-14 21:25:05 +00003487 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3488 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003489 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003490 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003491 return;
3492
Mike Stump1eb44332009-09-09 15:08:12 +00003493 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003494 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3495 if (!NTTP)
3496 return;
3497
Douglas Gregored9c0f92009-10-29 00:04:11 +00003498 if (NTTP->getDepth() == Depth)
3499 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003500}
3501
Douglas Gregore73bb602009-09-14 21:25:05 +00003502/// \brief Mark the template parameters that are used by the given
3503/// nested name specifier.
3504static void
3505MarkUsedTemplateParameters(Sema &SemaRef,
3506 NestedNameSpecifier *NNS,
3507 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003508 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003509 llvm::SmallVectorImpl<bool> &Used) {
3510 if (!NNS)
3511 return;
3512
Douglas Gregored9c0f92009-10-29 00:04:11 +00003513 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3514 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003515 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003516 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003517}
3518
3519/// \brief Mark the template parameters that are used by the given
3520/// template name.
3521static void
3522MarkUsedTemplateParameters(Sema &SemaRef,
3523 TemplateName Name,
3524 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003525 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003526 llvm::SmallVectorImpl<bool> &Used) {
3527 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3528 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003529 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3530 if (TTP->getDepth() == Depth)
3531 Used[TTP->getIndex()] = true;
3532 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003533 return;
3534 }
3535
Douglas Gregor788cd062009-11-11 01:00:40 +00003536 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3537 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3538 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003539 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003540 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3541 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003542}
3543
3544/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003545/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003546static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003547MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3548 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003549 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003550 llvm::SmallVectorImpl<bool> &Used) {
3551 if (T.isNull())
3552 return;
3553
Douglas Gregor031a5882009-06-13 00:26:55 +00003554 // Non-dependent types have nothing deducible
3555 if (!T->isDependentType())
3556 return;
3557
3558 T = SemaRef.Context.getCanonicalType(T);
3559 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003560 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003561 MarkUsedTemplateParameters(SemaRef,
3562 cast<PointerType>(T)->getPointeeType(),
3563 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003564 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003565 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003566 break;
3567
3568 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003569 MarkUsedTemplateParameters(SemaRef,
3570 cast<BlockPointerType>(T)->getPointeeType(),
3571 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003572 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003573 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003574 break;
3575
3576 case Type::LValueReference:
3577 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003578 MarkUsedTemplateParameters(SemaRef,
3579 cast<ReferenceType>(T)->getPointeeType(),
3580 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003581 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003582 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003583 break;
3584
3585 case Type::MemberPointer: {
3586 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003587 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003588 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003589 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003590 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003591 break;
3592 }
3593
3594 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003595 MarkUsedTemplateParameters(SemaRef,
3596 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003597 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003598 // Fall through to check the element type
3599
3600 case Type::ConstantArray:
3601 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003602 MarkUsedTemplateParameters(SemaRef,
3603 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003604 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003605 break;
3606
3607 case Type::Vector:
3608 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003609 MarkUsedTemplateParameters(SemaRef,
3610 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003611 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003612 break;
3613
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003614 case Type::DependentSizedExtVector: {
3615 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003616 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003617 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003618 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003619 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003620 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003621 break;
3622 }
3623
Douglas Gregor031a5882009-06-13 00:26:55 +00003624 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003625 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003626 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003627 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003628 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003629 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003630 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003631 break;
3632 }
3633
Douglas Gregored9c0f92009-10-29 00:04:11 +00003634 case Type::TemplateTypeParm: {
3635 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3636 if (TTP->getDepth() == Depth)
3637 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003638 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003639 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003640
Douglas Gregor0bc15d92011-01-14 05:11:40 +00003641 case Type::SubstTemplateTypeParmPack: {
3642 const SubstTemplateTypeParmPackType *Subst
3643 = cast<SubstTemplateTypeParmPackType>(T);
3644 MarkUsedTemplateParameters(SemaRef,
3645 QualType(Subst->getReplacedParameter(), 0),
3646 OnlyDeduced, Depth, Used);
3647 MarkUsedTemplateParameters(SemaRef, Subst->getArgumentPack(),
3648 OnlyDeduced, Depth, Used);
3649 break;
3650 }
3651
John McCall31f17ec2010-04-27 00:57:59 +00003652 case Type::InjectedClassName:
3653 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3654 // fall through
3655
Douglas Gregor031a5882009-06-13 00:26:55 +00003656 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003657 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003658 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003659 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003660 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003661
3662 // C++0x [temp.deduct.type]p9:
3663 // If the template argument list of P contains a pack expansion that is not
3664 // the last template argument, the entire template argument list is a
3665 // non-deduced context.
3666 if (OnlyDeduced &&
3667 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3668 break;
3669
Douglas Gregore73bb602009-09-14 21:25:05 +00003670 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003671 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3672 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003673 break;
3674 }
3675
Douglas Gregore73bb602009-09-14 21:25:05 +00003676 case Type::Complex:
3677 if (!OnlyDeduced)
3678 MarkUsedTemplateParameters(SemaRef,
3679 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003680 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003681 break;
3682
Douglas Gregor4714c122010-03-31 17:34:00 +00003683 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003684 if (!OnlyDeduced)
3685 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003686 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003687 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003688 break;
3689
John McCall33500952010-06-11 00:33:02 +00003690 case Type::DependentTemplateSpecialization: {
3691 const DependentTemplateSpecializationType *Spec
3692 = cast<DependentTemplateSpecializationType>(T);
3693 if (!OnlyDeduced)
3694 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3695 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003696
3697 // C++0x [temp.deduct.type]p9:
3698 // If the template argument list of P contains a pack expansion that is not
3699 // the last template argument, the entire template argument list is a
3700 // non-deduced context.
3701 if (OnlyDeduced &&
3702 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3703 break;
3704
John McCall33500952010-06-11 00:33:02 +00003705 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3706 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3707 Used);
3708 break;
3709 }
3710
John McCallad5e7382010-03-01 23:49:17 +00003711 case Type::TypeOf:
3712 if (!OnlyDeduced)
3713 MarkUsedTemplateParameters(SemaRef,
3714 cast<TypeOfType>(T)->getUnderlyingType(),
3715 OnlyDeduced, Depth, Used);
3716 break;
3717
3718 case Type::TypeOfExpr:
3719 if (!OnlyDeduced)
3720 MarkUsedTemplateParameters(SemaRef,
3721 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3722 OnlyDeduced, Depth, Used);
3723 break;
3724
3725 case Type::Decltype:
3726 if (!OnlyDeduced)
3727 MarkUsedTemplateParameters(SemaRef,
3728 cast<DecltypeType>(T)->getUnderlyingExpr(),
3729 OnlyDeduced, Depth, Used);
3730 break;
3731
Douglas Gregor7536dd52010-12-20 02:24:11 +00003732 case Type::PackExpansion:
3733 MarkUsedTemplateParameters(SemaRef,
3734 cast<PackExpansionType>(T)->getPattern(),
3735 OnlyDeduced, Depth, Used);
3736 break;
3737
Douglas Gregore73bb602009-09-14 21:25:05 +00003738 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003739 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003740 case Type::VariableArray:
3741 case Type::FunctionNoProto:
3742 case Type::Record:
3743 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003744 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003745 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003746 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003747 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003748#define TYPE(Class, Base)
3749#define ABSTRACT_TYPE(Class, Base)
3750#define DEPENDENT_TYPE(Class, Base)
3751#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3752#include "clang/AST/TypeNodes.def"
3753 break;
3754 }
3755}
3756
Douglas Gregore73bb602009-09-14 21:25:05 +00003757/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003758/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003759static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003760MarkUsedTemplateParameters(Sema &SemaRef,
3761 const TemplateArgument &TemplateArg,
3762 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003763 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003764 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003765 switch (TemplateArg.getKind()) {
3766 case TemplateArgument::Null:
3767 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003768 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003769 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Douglas Gregor031a5882009-06-13 00:26:55 +00003771 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003772 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003773 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003774 break;
3775
Douglas Gregor788cd062009-11-11 01:00:40 +00003776 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003777 case TemplateArgument::TemplateExpansion:
3778 MarkUsedTemplateParameters(SemaRef,
3779 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003780 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003781 break;
3782
3783 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003784 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003785 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003786 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003787
Anders Carlssond01b1da2009-06-15 17:04:53 +00003788 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003789 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3790 PEnd = TemplateArg.pack_end();
3791 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003792 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003793 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003794 }
3795}
3796
3797/// \brief Mark the template parameters can be deduced by the given
3798/// template argument list.
3799///
3800/// \param TemplateArgs the template argument list from which template
3801/// parameters will be deduced.
3802///
3803/// \param Deduced a bit vector whose elements will be set to \c true
3804/// to indicate when the corresponding template parameter will be
3805/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003806void
Douglas Gregore73bb602009-09-14 21:25:05 +00003807Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003808 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003809 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003810 // C++0x [temp.deduct.type]p9:
3811 // If the template argument list of P contains a pack expansion that is not
3812 // the last template argument, the entire template argument list is a
3813 // non-deduced context.
3814 if (OnlyDeduced &&
3815 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3816 return;
3817
Douglas Gregor031a5882009-06-13 00:26:55 +00003818 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003819 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3820 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003821}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003822
3823/// \brief Marks all of the template parameters that will be deduced by a
3824/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003825void
3826Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3827 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003828 TemplateParameterList *TemplateParams
3829 = FunctionTemplate->getTemplateParameters();
3830 Deduced.clear();
3831 Deduced.resize(TemplateParams->size());
3832
3833 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3834 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3835 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003836 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003837}