blob: 5c899ebdea365070fd3f0e82b5053efdbc8846ab [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.
52 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor0b9247f2009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor9d0e4412010-03-26 05:50:28 +000058/// \brief Compare two APSInts, extending and switching the sign as
59/// necessary to compare their values regardless of underlying type.
60static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
61 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000065
66 // If there is a signedness mismatch, correct it.
67 if (X.isSigned() != Y.isSigned()) {
68 // If the signed value is negative, then the values cannot be the same.
69 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
70 return false;
71
72 Y.setIsSigned(true);
73 X.setIsSigned(true);
74 }
75
76 return X == Y;
77}
78
Douglas Gregorf67875d2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregor77d6bb92011-01-11 22:21:24 +000083 TemplateArgument Arg,
John McCall2a7fb272010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000086
Douglas Gregorb939a192011-01-21 17:29:42 +000087/// \brief Whether template argument deduction for two reference parameters
88/// resulted in the argument type, parameter type, or neither type being more
89/// qualified than the other.
Douglas Gregor5c7bf422011-01-11 17:34:58 +000090enum DeductionQualifierComparison {
91 NeitherMoreQualified = 0,
92 ParamMoreQualified,
93 ArgMoreQualified
94};
95
Douglas Gregorb939a192011-01-21 17:29:42 +000096/// \brief Stores the result of comparing two reference parameters while
97/// performing template argument deduction for partial ordering of function
98/// templates.
99struct RefParamPartialOrderingComparison {
100 /// \brief Whether the parameter type is an rvalue reference type.
101 bool ParamIsRvalueRef;
102 /// \brief Whether the argument type is an rvalue reference type.
103 bool ArgIsRvalueRef;
104
105 /// \brief Whether the parameter or argument (or neither) is more qualified.
106 DeductionQualifierComparison Qualifiers;
107};
108
109
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000110
Douglas Gregor20a55e22010-12-22 18:17:10 +0000111static Sema::TemplateDeductionResult
112DeduceTemplateArguments(Sema &S,
113 TemplateParameterList *TemplateParams,
Douglas Gregor603cfb42011-01-05 23:12:31 +0000114 QualType Param,
115 QualType Arg,
116 TemplateDeductionInfo &Info,
117 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000118 unsigned TDF,
119 bool PartialOrdering = false,
Douglas Gregorb939a192011-01-21 17:29:42 +0000120 llvm::SmallVectorImpl<RefParamPartialOrderingComparison> *
121 RefParamComparisons = 0);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000122
123static Sema::TemplateDeductionResult
124DeduceTemplateArguments(Sema &S,
125 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +0000126 const TemplateArgument *Params, unsigned NumParams,
127 const TemplateArgument *Args, unsigned NumArgs,
128 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000129 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
130 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000131
Douglas Gregor199d9912009-06-05 00:53:49 +0000132/// \brief If the given expression is of a form that permits the deduction
133/// of a non-type template parameter, return the declaration of that
134/// non-type template parameter.
135static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
136 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
137 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Douglas Gregor199d9912009-06-05 00:53:49 +0000139 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
140 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000141
Douglas Gregor199d9912009-06-05 00:53:49 +0000142 return 0;
143}
144
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000145/// \brief Determine whether two declaration pointers refer to the same
146/// declaration.
147static bool isSameDeclaration(Decl *X, Decl *Y) {
148 if (!X || !Y)
149 return !X && !Y;
150
151 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
152 X = NX->getUnderlyingDecl();
153 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
154 Y = NY->getUnderlyingDecl();
155
156 return X->getCanonicalDecl() == Y->getCanonicalDecl();
157}
158
159/// \brief Verify that the given, deduced template arguments are compatible.
160///
161/// \returns The deduced template argument, or a NULL template argument if
162/// the deduced template arguments were incompatible.
163static DeducedTemplateArgument
164checkDeducedTemplateArguments(ASTContext &Context,
165 const DeducedTemplateArgument &X,
166 const DeducedTemplateArgument &Y) {
167 // We have no deduction for one or both of the arguments; they're compatible.
168 if (X.isNull())
169 return Y;
170 if (Y.isNull())
171 return X;
172
173 switch (X.getKind()) {
174 case TemplateArgument::Null:
175 llvm_unreachable("Non-deduced template arguments handled above");
176
177 case TemplateArgument::Type:
178 // If two template type arguments have the same type, they're compatible.
179 if (Y.getKind() == TemplateArgument::Type &&
180 Context.hasSameType(X.getAsType(), Y.getAsType()))
181 return X;
182
183 return DeducedTemplateArgument();
184
185 case TemplateArgument::Integral:
186 // If we deduced a constant in one case and either a dependent expression or
187 // declaration in another case, keep the integral constant.
188 // If both are integral constants with the same value, keep that value.
189 if (Y.getKind() == TemplateArgument::Expression ||
190 Y.getKind() == TemplateArgument::Declaration ||
191 (Y.getKind() == TemplateArgument::Integral &&
192 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
193 return DeducedTemplateArgument(X,
194 X.wasDeducedFromArrayBound() &&
195 Y.wasDeducedFromArrayBound());
196
197 // All other combinations are incompatible.
198 return DeducedTemplateArgument();
199
200 case TemplateArgument::Template:
201 if (Y.getKind() == TemplateArgument::Template &&
202 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
203 return X;
204
205 // All other combinations are incompatible.
206 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000207
208 case TemplateArgument::TemplateExpansion:
209 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
210 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
211 Y.getAsTemplateOrTemplatePattern()))
212 return X;
213
214 // All other combinations are incompatible.
215 return DeducedTemplateArgument();
216
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000217 case TemplateArgument::Expression:
218 // If we deduced a dependent expression in one case and either an integral
219 // constant or a declaration in another case, keep the integral constant
220 // or declaration.
221 if (Y.getKind() == TemplateArgument::Integral ||
222 Y.getKind() == TemplateArgument::Declaration)
223 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
224 Y.wasDeducedFromArrayBound());
225
226 if (Y.getKind() == TemplateArgument::Expression) {
227 // Compare the expressions for equality
228 llvm::FoldingSetNodeID ID1, ID2;
229 X.getAsExpr()->Profile(ID1, Context, true);
230 Y.getAsExpr()->Profile(ID2, Context, true);
231 if (ID1 == ID2)
232 return X;
233 }
234
235 // All other combinations are incompatible.
236 return DeducedTemplateArgument();
237
238 case TemplateArgument::Declaration:
239 // If we deduced a declaration and a dependent expression, keep the
240 // declaration.
241 if (Y.getKind() == TemplateArgument::Expression)
242 return X;
243
244 // If we deduced a declaration and an integral constant, keep the
245 // integral constant.
246 if (Y.getKind() == TemplateArgument::Integral)
247 return Y;
248
249 // If we deduced two declarations, make sure they they refer to the
250 // same declaration.
251 if (Y.getKind() == TemplateArgument::Declaration &&
252 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
253 return X;
254
255 // All other combinations are incompatible.
256 return DeducedTemplateArgument();
257
258 case TemplateArgument::Pack:
259 if (Y.getKind() != TemplateArgument::Pack ||
260 X.pack_size() != Y.pack_size())
261 return DeducedTemplateArgument();
262
263 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
264 XAEnd = X.pack_end(),
265 YA = Y.pack_begin();
266 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000267 if (checkDeducedTemplateArguments(Context,
268 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
269 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
270 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000271 return DeducedTemplateArgument();
272 }
273
274 return X;
275 }
276
277 return DeducedTemplateArgument();
278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000281/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000282static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000283DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000284 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000285 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000286 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000287 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000288 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000289 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000290 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000291
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000292 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
293 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
294 Deduced[NTTP->getIndex()],
295 NewDeduced);
296 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000297 Info.Param = NTTP;
298 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000299 Info.SecondArg = NewDeduced;
300 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000301 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000302
303 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000304 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000305}
306
Mike Stump1eb44332009-09-09 15:08:12 +0000307/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000308/// from the given type- or value-dependent expression.
309///
310/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000311static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000312DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000313 NonTypeTemplateParmDecl *NTTP,
314 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000315 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000316 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000317 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000318 "Cannot deduce non-type template argument with depth > 0");
319 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
320 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000322 DeducedTemplateArgument NewDeduced(Value);
323 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
324 Deduced[NTTP->getIndex()],
325 NewDeduced);
326
327 if (Result.isNull()) {
328 Info.Param = NTTP;
329 Info.FirstArg = Deduced[NTTP->getIndex()];
330 Info.SecondArg = NewDeduced;
331 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000332 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000333
334 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000335 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000336}
337
Douglas Gregor15755cb2009-11-13 23:45:44 +0000338/// \brief Deduce the value of the given non-type template parameter
339/// from the given declaration.
340///
341/// \returns true if deduction succeeded, false otherwise.
342static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000343DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000344 NonTypeTemplateParmDecl *NTTP,
345 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000346 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000347 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000348 assert(NTTP->getDepth() == 0 &&
349 "Cannot deduce non-type template argument with depth > 0");
350
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000351 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
352 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
353 Deduced[NTTP->getIndex()],
354 NewDeduced);
355 if (Result.isNull()) {
356 Info.Param = NTTP;
357 Info.FirstArg = Deduced[NTTP->getIndex()];
358 Info.SecondArg = NewDeduced;
359 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000360 }
361
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000362 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000363 return Sema::TDK_Success;
364}
365
Douglas Gregorf67875d2009-06-12 18:26:56 +0000366static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000367DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000368 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000369 TemplateName Param,
370 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000371 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000372 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000373 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000374 if (!ParamDecl) {
375 // The parameter type is dependent and is not a template template parameter,
376 // so there is nothing that we can deduce.
377 return Sema::TDK_Success;
378 }
379
380 if (TemplateTemplateParmDecl *TempParam
381 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000382 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
383 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
384 Deduced[TempParam->getIndex()],
385 NewDeduced);
386 if (Result.isNull()) {
387 Info.Param = TempParam;
388 Info.FirstArg = Deduced[TempParam->getIndex()];
389 Info.SecondArg = NewDeduced;
390 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000391 }
392
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000393 Deduced[TempParam->getIndex()] = Result;
394 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000395 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000396
397 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000398 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000399 return Sema::TDK_Success;
400
401 // Mismatch of non-dependent template parameter to argument.
402 Info.FirstArg = TemplateArgument(Param);
403 Info.SecondArg = TemplateArgument(Arg);
404 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000405}
406
Mike Stump1eb44332009-09-09 15:08:12 +0000407/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000408/// type (which is a template-id) with the template argument type.
409///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000410/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000411///
412/// \param TemplateParams the template parameters that we are deducing
413///
414/// \param Param the parameter type
415///
416/// \param Arg the argument type
417///
418/// \param Info information about the template argument deduction itself
419///
420/// \param Deduced the deduced template arguments
421///
422/// \returns the result of template argument deduction so far. Note that a
423/// "success" result means that template argument deduction has not yet failed,
424/// but it may still fail, later, for other reasons.
425static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000426DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000427 TemplateParameterList *TemplateParams,
428 const TemplateSpecializationType *Param,
429 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000430 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000431 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000432 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000434 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000435 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000436 = dyn_cast<TemplateSpecializationType>(Arg)) {
437 // Perform template argument deduction for the template name.
438 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000439 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000440 Param->getTemplateName(),
441 SpecArg->getTemplateName(),
442 Info, Deduced))
443 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000446 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000447 // argument. Ignore any missing/extra arguments, since they could be
448 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000449 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000450 Param->getArgs(), Param->getNumArgs(),
451 SpecArg->getArgs(), SpecArg->getNumArgs(),
452 Info, Deduced,
453 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000456 // If the argument type is a class template specialization, we
457 // perform template argument deduction using its template
458 // arguments.
459 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
460 if (!RecordArg)
461 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000462
463 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000464 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
465 if (!SpecArg)
466 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000468 // Perform template argument deduction for the template name.
469 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000470 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000471 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000472 Param->getTemplateName(),
473 TemplateName(SpecArg->getSpecializedTemplate()),
474 Info, Deduced))
475 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Douglas Gregor20a55e22010-12-22 18:17:10 +0000477 // Perform template argument deduction for the template arguments.
478 return DeduceTemplateArguments(S, TemplateParams,
479 Param->getArgs(), Param->getNumArgs(),
480 SpecArg->getTemplateArgs().data(),
481 SpecArg->getTemplateArgs().size(),
482 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000483}
484
John McCallcd05e812010-08-28 22:14:41 +0000485/// \brief Determines whether the given type is an opaque type that
486/// might be more qualified when instantiated.
487static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
488 switch (T->getTypeClass()) {
489 case Type::TypeOfExpr:
490 case Type::TypeOf:
491 case Type::DependentName:
492 case Type::Decltype:
493 case Type::UnresolvedUsing:
John McCall62c28c82011-01-18 07:41:22 +0000494 case Type::TemplateTypeParm:
John McCallcd05e812010-08-28 22:14:41 +0000495 return true;
496
497 case Type::ConstantArray:
498 case Type::IncompleteArray:
499 case Type::VariableArray:
500 case Type::DependentSizedArray:
501 return IsPossiblyOpaquelyQualifiedType(
502 cast<ArrayType>(T)->getElementType());
503
504 default:
505 return false;
506 }
507}
508
Douglas Gregord3731192011-01-10 07:32:04 +0000509/// \brief Retrieve the depth and index of a template parameter.
Douglas Gregor603cfb42011-01-05 23:12:31 +0000510static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000511getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor603cfb42011-01-05 23:12:31 +0000512 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
513 return std::make_pair(TTP->getDepth(), TTP->getIndex());
514
515 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
516 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
517
518 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
519 return std::make_pair(TTP->getDepth(), TTP->getIndex());
520}
521
Douglas Gregord3731192011-01-10 07:32:04 +0000522/// \brief Retrieve the depth and index of an unexpanded parameter pack.
523static std::pair<unsigned, unsigned>
524getDepthAndIndex(UnexpandedParameterPack UPP) {
525 if (const TemplateTypeParmType *TTP
526 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
527 return std::make_pair(TTP->getDepth(), TTP->getIndex());
528
529 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
530}
531
Douglas Gregor603cfb42011-01-05 23:12:31 +0000532/// \brief Helper function to build a TemplateParameter when we don't
533/// know its type statically.
534static TemplateParameter makeTemplateParameter(Decl *D) {
535 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
536 return TemplateParameter(TTP);
537 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
538 return TemplateParameter(NTTP);
539
540 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
541}
542
Douglas Gregor54293852011-01-10 17:35:05 +0000543/// \brief Prepare to perform template argument deduction for all of the
544/// arguments in a set of argument packs.
545static void PrepareArgumentPackDeduction(Sema &S,
546 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
547 const llvm::SmallVectorImpl<unsigned> &PackIndices,
548 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
549 llvm::SmallVectorImpl<
550 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
551 // Save the deduced template arguments for each parameter pack expanded
552 // by this pack expansion, then clear out the deduction.
553 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
554 // Save the previously-deduced argument pack, then clear it out so that we
555 // can deduce a new argument pack.
556 SavedPacks[I] = Deduced[PackIndices[I]];
557 Deduced[PackIndices[I]] = TemplateArgument();
558
559 // If the template arugment pack was explicitly specified, add that to
560 // the set of deduced arguments.
561 const TemplateArgument *ExplicitArgs;
562 unsigned NumExplicitArgs;
563 if (NamedDecl *PartiallySubstitutedPack
564 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
565 &ExplicitArgs,
566 &NumExplicitArgs)) {
567 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
568 NewlyDeducedPacks[I].append(ExplicitArgs,
569 ExplicitArgs + NumExplicitArgs);
570 }
571 }
572}
573
Douglas Gregor0216f812011-01-10 17:53:52 +0000574/// \brief Finish template argument deduction for a set of argument packs,
575/// producing the argument packs and checking for consistency with prior
576/// deductions.
577static Sema::TemplateDeductionResult
578FinishArgumentPackDeduction(Sema &S,
579 TemplateParameterList *TemplateParams,
580 bool HasAnyArguments,
581 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
582 const llvm::SmallVectorImpl<unsigned> &PackIndices,
583 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
584 llvm::SmallVectorImpl<
585 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
586 TemplateDeductionInfo &Info) {
587 // Build argument packs for each of the parameter packs expanded by this
588 // pack expansion.
589 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
590 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
591 // We were not able to deduce anything for this parameter pack,
592 // so just restore the saved argument pack.
593 Deduced[PackIndices[I]] = SavedPacks[I];
594 continue;
595 }
596
597 DeducedTemplateArgument NewPack;
598
599 if (NewlyDeducedPacks[I].empty()) {
600 // If we deduced an empty argument pack, create it now.
601 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
602 } else {
603 TemplateArgument *ArgumentPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000604 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
Douglas Gregor0216f812011-01-10 17:53:52 +0000605 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
606 ArgumentPack);
607 NewPack
Douglas Gregor203e6a32011-01-11 23:09:57 +0000608 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
609 NewlyDeducedPacks[I].size()),
610 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
Douglas Gregor0216f812011-01-10 17:53:52 +0000611 }
612
613 DeducedTemplateArgument Result
614 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
615 if (Result.isNull()) {
616 Info.Param
617 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
618 Info.FirstArg = SavedPacks[I];
619 Info.SecondArg = NewPack;
620 return Sema::TDK_Inconsistent;
621 }
622
623 Deduced[PackIndices[I]] = Result;
624 }
625
626 return Sema::TDK_Success;
627}
628
Douglas Gregor603cfb42011-01-05 23:12:31 +0000629/// \brief Deduce the template arguments by comparing the list of parameter
630/// types to the list of argument types, as in the parameter-type-lists of
631/// function types (C++ [temp.deduct.type]p10).
632///
633/// \param S The semantic analysis object within which we are deducing
634///
635/// \param TemplateParams The template parameters that we are deducing
636///
637/// \param Params The list of parameter types
638///
639/// \param NumParams The number of types in \c Params
640///
641/// \param Args The list of argument types
642///
643/// \param NumArgs The number of types in \c Args
644///
645/// \param Info information about the template argument deduction itself
646///
647/// \param Deduced the deduced template arguments
648///
649/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
650/// how template argument deduction is performed.
651///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000652/// \param PartialOrdering If true, we are performing template argument
653/// deduction for during partial ordering for a call
654/// (C++0x [temp.deduct.partial]).
655///
Douglas Gregorb939a192011-01-21 17:29:42 +0000656/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000657/// in the context of partial ordering, the set of qualifier comparisons.
658///
Douglas Gregor603cfb42011-01-05 23:12:31 +0000659/// \returns the result of template argument deduction so far. Note that a
660/// "success" result means that template argument deduction has not yet failed,
661/// but it may still fail, later, for other reasons.
662static Sema::TemplateDeductionResult
663DeduceTemplateArguments(Sema &S,
664 TemplateParameterList *TemplateParams,
665 const QualType *Params, unsigned NumParams,
666 const QualType *Args, unsigned NumArgs,
667 TemplateDeductionInfo &Info,
668 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000669 unsigned TDF,
670 bool PartialOrdering = false,
Douglas Gregorb939a192011-01-21 17:29:42 +0000671 llvm::SmallVectorImpl<RefParamPartialOrderingComparison> *
672 RefParamComparisons = 0) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000673 // Fast-path check to see if we have too many/too few arguments.
674 if (NumParams != NumArgs &&
675 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
676 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000677 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000678
679 // C++0x [temp.deduct.type]p10:
680 // Similarly, if P has a form that contains (T), then each parameter type
681 // Pi of the respective parameter-type- list of P is compared with the
682 // corresponding parameter type Ai of the corresponding parameter-type-list
683 // of A. [...]
684 unsigned ArgIdx = 0, ParamIdx = 0;
685 for (; ParamIdx != NumParams; ++ParamIdx) {
686 // Check argument types.
687 const PackExpansionType *Expansion
688 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
689 if (!Expansion) {
690 // Simple case: compare the parameter and argument types at this point.
691
692 // Make sure we have an argument.
693 if (ArgIdx >= NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000694 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000695
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000696 if (isa<PackExpansionType>(Args[ArgIdx])) {
697 // C++0x [temp.deduct.type]p22:
698 // If the original function parameter associated with A is a function
699 // parameter pack and the function parameter associated with P is not
700 // a function parameter pack, then template argument deduction fails.
701 return Sema::TDK_NonDeducedMismatch;
702 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000703
Douglas Gregor603cfb42011-01-05 23:12:31 +0000704 if (Sema::TemplateDeductionResult Result
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000705 = DeduceTemplateArguments(S, TemplateParams,
706 Params[ParamIdx],
707 Args[ArgIdx],
708 Info, Deduced, TDF,
709 PartialOrdering,
Douglas Gregorb939a192011-01-21 17:29:42 +0000710 RefParamComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000711 return Result;
712
713 ++ArgIdx;
714 continue;
715 }
716
Douglas Gregor7d5c0c12011-01-11 01:52:23 +0000717 // C++0x [temp.deduct.type]p5:
718 // The non-deduced contexts are:
719 // - A function parameter pack that does not occur at the end of the
720 // parameter-declaration-clause.
721 if (ParamIdx + 1 < NumParams)
722 return Sema::TDK_Success;
723
Douglas Gregor603cfb42011-01-05 23:12:31 +0000724 // C++0x [temp.deduct.type]p10:
725 // If the parameter-declaration corresponding to Pi is a function
726 // parameter pack, then the type of its declarator- id is compared with
727 // each remaining parameter type in the parameter-type-list of A. Each
728 // comparison deduces template arguments for subsequent positions in the
729 // template parameter packs expanded by the function parameter pack.
730
731 // Compute the set of template parameter indices that correspond to
732 // parameter packs expanded by the pack expansion.
733 llvm::SmallVector<unsigned, 2> PackIndices;
734 QualType Pattern = Expansion->getPattern();
735 {
736 llvm::BitVector SawIndices(TemplateParams->size());
737 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
738 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
739 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
740 unsigned Depth, Index;
741 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
742 if (Depth == 0 && !SawIndices[Index]) {
743 SawIndices[Index] = true;
744 PackIndices.push_back(Index);
745 }
746 }
747 }
748 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
749
Douglas Gregord3731192011-01-10 07:32:04 +0000750 // Keep track of the deduced template arguments for each parameter pack
751 // expanded by this pack expansion (the outer index) and for each
752 // template argument (the inner SmallVectors).
753 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
754 NewlyDeducedPacks(PackIndices.size());
Douglas Gregor603cfb42011-01-05 23:12:31 +0000755 llvm::SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000756 SavedPacks(PackIndices.size());
757 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
758 NewlyDeducedPacks);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000759
Douglas Gregor603cfb42011-01-05 23:12:31 +0000760 bool HasAnyArguments = false;
761 for (; ArgIdx < NumArgs; ++ArgIdx) {
762 HasAnyArguments = true;
763
764 // Deduce template arguments from the pattern.
765 if (Sema::TemplateDeductionResult Result
766 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000767 Info, Deduced, PartialOrdering,
Douglas Gregorb939a192011-01-21 17:29:42 +0000768 RefParamComparisons))
Douglas Gregor603cfb42011-01-05 23:12:31 +0000769 return Result;
770
771 // Capture the deduced template arguments for each parameter pack expanded
772 // by this pack expansion, add them to the list of arguments we've deduced
773 // for that pack, then clear out the deduced argument.
774 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
775 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
776 if (!DeducedArg.isNull()) {
777 NewlyDeducedPacks[I].push_back(DeducedArg);
778 DeducedArg = DeducedTemplateArgument();
779 }
780 }
781 }
782
783 // Build argument packs for each of the parameter packs expanded by this
784 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +0000785 if (Sema::TemplateDeductionResult Result
786 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
787 Deduced, PackIndices, SavedPacks,
788 NewlyDeducedPacks, Info))
789 return Result;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000790 }
791
792 // Make sure we don't have any extra arguments.
793 if (ArgIdx < NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000794 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000795
796 return Sema::TDK_Success;
797}
798
Douglas Gregor500d3312009-06-26 18:27:22 +0000799/// \brief Deduce the template arguments by comparing the parameter type and
800/// the argument type (C++ [temp.deduct.type]).
801///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000802/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000803///
804/// \param TemplateParams the template parameters that we are deducing
805///
806/// \param ParamIn the parameter type
807///
808/// \param ArgIn the argument type
809///
810/// \param Info information about the template argument deduction itself
811///
812/// \param Deduced the deduced template arguments
813///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000814/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000815/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000816///
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000817/// \param PartialOrdering Whether we're performing template argument deduction
818/// in the context of partial ordering (C++0x [temp.deduct.partial]).
819///
Douglas Gregorb939a192011-01-21 17:29:42 +0000820/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000821/// in the context of partial ordering, the set of qualifier comparisons.
822///
Douglas Gregor500d3312009-06-26 18:27:22 +0000823/// \returns the result of template argument deduction so far. Note that a
824/// "success" result means that template argument deduction has not yet failed,
825/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000826static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000827DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000828 TemplateParameterList *TemplateParams,
829 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000830 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000831 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000832 unsigned TDF,
833 bool PartialOrdering,
Douglas Gregorb939a192011-01-21 17:29:42 +0000834 llvm::SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000835 // We only want to look at the canonical types, since typedefs and
836 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000837 QualType Param = S.Context.getCanonicalType(ParamIn);
838 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000839
Douglas Gregor77d6bb92011-01-11 22:21:24 +0000840 // If the argument type is a pack expansion, look at its pattern.
841 // This isn't explicitly called out
842 if (const PackExpansionType *ArgExpansion
843 = dyn_cast<PackExpansionType>(Arg))
844 Arg = ArgExpansion->getPattern();
845
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000846 if (PartialOrdering) {
847 // C++0x [temp.deduct.partial]p5:
848 // Before the partial ordering is done, certain transformations are
849 // performed on the types used for partial ordering:
850 // - If P is a reference type, P is replaced by the type referred to.
851 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
852 if (ParamRef)
853 Param = ParamRef->getPointeeType();
854
855 // - If A is a reference type, A is replaced by the type referred to.
856 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
857 if (ArgRef)
858 Arg = ArgRef->getPointeeType();
859
Douglas Gregorb939a192011-01-21 17:29:42 +0000860 if (RefParamComparisons && ParamRef && ArgRef) {
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000861 // C++0x [temp.deduct.partial]p6:
862 // If both P and A were reference types (before being replaced with the
863 // type referred to above), determine which of the two types (if any) is
864 // more cv-qualified than the other; otherwise the types are considered
865 // to be equally cv-qualified for partial ordering purposes. The result
866 // of this determination will be used below.
867 //
868 // We save this information for later, using it only when deduction
869 // succeeds in both directions.
Douglas Gregorb939a192011-01-21 17:29:42 +0000870 RefParamPartialOrderingComparison Comparison;
871 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
872 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
873 Comparison.Qualifiers = NeitherMoreQualified;
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000874 if (Param.isMoreQualifiedThan(Arg))
Douglas Gregorb939a192011-01-21 17:29:42 +0000875 Comparison.Qualifiers = ParamMoreQualified;
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000876 else if (Arg.isMoreQualifiedThan(Param))
Douglas Gregorb939a192011-01-21 17:29:42 +0000877 Comparison.Qualifiers = ArgMoreQualified;
878 RefParamComparisons->push_back(Comparison);
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000879 }
880
881 // C++0x [temp.deduct.partial]p7:
882 // Remove any top-level cv-qualifiers:
883 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
884 // version of P.
885 Param = Param.getUnqualifiedType();
886 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
887 // version of A.
888 Arg = Arg.getUnqualifiedType();
889 } else {
890 // C++0x [temp.deduct.call]p4 bullet 1:
891 // - If the original P is a reference type, the deduced A (i.e., the type
892 // referred to by the reference) can be more cv-qualified than the
893 // transformed A.
894 if (TDF & TDF_ParamWithReferenceType) {
895 Qualifiers Quals;
896 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
897 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall62c28c82011-01-18 07:41:22 +0000898 Arg.getCVRQualifiers());
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000899 Param = S.Context.getQualifiedType(UnqualParam, Quals);
900 }
Douglas Gregor500d3312009-06-26 18:27:22 +0000901 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +0000902
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000903 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000904 if (!Param->isDependentType()) {
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000905 if (!(TDF & TDF_SkipNonDependent) && Param != Arg)
Douglas Gregor12820292009-09-14 20:00:47 +0000906 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor12820292009-09-14 20:00:47 +0000907
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000908 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000909 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000910
Douglas Gregor199d9912009-06-05 00:53:49 +0000911 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000912 // A template type argument T, a template template argument TT or a
913 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000914 // the following forms:
915 //
916 // T
917 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000918 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000919 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000920 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000921 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000923 // If the argument type is an array type, move the qualifiers up to the
924 // top level, so they can be matched with the qualifiers on the parameter.
925 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000926 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000927 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000928 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000929 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000930 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000931 RecanonicalizeArg = true;
932 }
933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000935 // The argument type can not be less qualified than the parameter
936 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000937 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000938 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000939 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000940 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000941 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000942 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000943
944 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000945 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000946 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000947
948 // local manipulation is okay because it's canonical
949 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000950 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000951 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000953 DeducedTemplateArgument NewDeduced(DeducedType);
954 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
955 Deduced[Index],
956 NewDeduced);
957 if (Result.isNull()) {
958 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
959 Info.FirstArg = Deduced[Index];
960 Info.SecondArg = NewDeduced;
961 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000962 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000963
964 Deduced[Index] = Result;
965 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000966 }
967
Douglas Gregorf67875d2009-06-12 18:26:56 +0000968 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000969 Info.FirstArg = TemplateArgument(ParamIn);
970 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000971
Douglas Gregor0bc15d92011-01-14 05:11:40 +0000972 // If the parameter is an already-substituted template parameter
973 // pack, do nothing: we don't know which of its arguments to look
974 // at, so we have to wait until all of the parameter packs in this
975 // expansion have arguments.
976 if (isa<SubstTemplateTypeParmPackType>(Param))
977 return Sema::TDK_Success;
978
Douglas Gregor508f1c82009-06-26 23:10:12 +0000979 // Check the cv-qualifiers on the parameter and argument types.
980 if (!(TDF & TDF_IgnoreQualifiers)) {
981 if (TDF & TDF_ParamWithReferenceType) {
982 if (Param.isMoreQualifiedThan(Arg))
983 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000984 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000985 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000986 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000987 }
988 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000989
Douglas Gregord560d502009-06-04 00:21:18 +0000990 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000991 // No deduction possible for these types
992 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000993 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Douglas Gregor199d9912009-06-05 00:53:49 +0000995 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000996 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000997 QualType PointeeType;
998 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
999 PointeeType = PointerArg->getPointeeType();
1000 } else if (const ObjCObjectPointerType *PointerArg
1001 = Arg->getAs<ObjCObjectPointerType>()) {
1002 PointeeType = PointerArg->getPointeeType();
1003 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +00001004 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +00001005 }
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Douglas Gregor41128772009-06-26 23:27:24 +00001007 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001008 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001009 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +00001010 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +00001011 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +00001012 }
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Douglas Gregor199d9912009-06-05 00:53:49 +00001014 // T &
Douglas Gregord560d502009-06-04 00:21:18 +00001015 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +00001016 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +00001017 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001018 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001020 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001021 cast<LValueReferenceType>(Param)->getPointeeType(),
1022 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001023 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001024 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001025
Douglas Gregor199d9912009-06-05 00:53:49 +00001026 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +00001027 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +00001028 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +00001029 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001030 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001032 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +00001033 cast<RValueReferenceType>(Param)->getPointeeType(),
1034 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001035 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +00001036 }
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Douglas Gregor199d9912009-06-05 00:53:49 +00001038 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001039 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001040 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001041 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001042 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001043 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001044
John McCalle4f26e52010-08-19 00:20:19 +00001045 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001046 return DeduceTemplateArguments(S, TemplateParams,
1047 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001048 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001049 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001050 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001051
1052 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001053 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +00001054 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001055 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001056 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001057 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001058
1059 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001060 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001061 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001062 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001063
John McCalle4f26e52010-08-19 00:20:19 +00001064 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001065 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001066 ConstantArrayParm->getElementType(),
1067 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001068 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +00001069 }
1070
Douglas Gregor199d9912009-06-05 00:53:49 +00001071 // type [i]
1072 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001073 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +00001074 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001075 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001076
John McCalle4f26e52010-08-19 00:20:19 +00001077 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1078
Douglas Gregor199d9912009-06-05 00:53:49 +00001079 // Check the element type of the arrays
1080 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001081 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001082 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001083 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001084 DependentArrayParm->getElementType(),
1085 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +00001086 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001087 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Douglas Gregor199d9912009-06-05 00:53:49 +00001089 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +00001090 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001091 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1092 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001093 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +00001094
1095 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +00001096 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00001097 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +00001098 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +00001099 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +00001100 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1101 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001102 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
1103 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001104 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001105 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +00001106 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001107 if (const DependentSizedArrayType *DependentArrayArg
1108 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +00001109 if (DependentArrayArg->getSizeExpr())
1110 return DeduceNonTypeTemplateArgument(S, NTTP,
1111 DependentArrayArg->getSizeExpr(),
1112 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Douglas Gregor199d9912009-06-05 00:53:49 +00001114 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +00001115 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001116 }
Mike Stump1eb44332009-09-09 15:08:12 +00001117
1118 // type(*)(T)
1119 // T(*)()
1120 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +00001121 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +00001122 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +00001123 dyn_cast<FunctionProtoType>(Arg);
1124 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001125 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
1127 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +00001128 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001129
Mike Stump1eb44332009-09-09 15:08:12 +00001130 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001131 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001132 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001134 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001135 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001136
Anders Carlssona27fad52009-06-08 15:19:08 +00001137 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001138 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001139 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001140 FunctionProtoParam->getResultType(),
1141 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001142 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001143 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Douglas Gregor603cfb42011-01-05 23:12:31 +00001145 return DeduceTemplateArguments(S, TemplateParams,
1146 FunctionProtoParam->arg_type_begin(),
1147 FunctionProtoParam->getNumArgs(),
1148 FunctionProtoArg->arg_type_begin(),
1149 FunctionProtoArg->getNumArgs(),
1150 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +00001151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
John McCall3cb0ebd2010-03-10 03:28:59 +00001153 case Type::InjectedClassName: {
1154 // Treat a template's injected-class-name as if the template
1155 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001156 Param = cast<InjectedClassNameType>(Param)
1157 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001158 assert(isa<TemplateSpecializationType>(Param) &&
1159 "injected class name is not a template specialization type");
1160 // fall through
1161 }
1162
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001163 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001164 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001165 // TT<T>
1166 // TT<i>
1167 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001168 case Type::TemplateSpecialization: {
1169 const TemplateSpecializationType *SpecParam
1170 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001172 // Try to deduce template arguments from the template-id.
1173 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001174 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001175 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001177 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001178 // C++ [temp.deduct.call]p3b3:
1179 // If P is a class, and P has the form template-id, then A can be a
1180 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001181 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001182 // class pointed to by the deduced A.
1183 //
1184 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001185 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001186 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001187 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1188 // We cannot inspect base classes as part of deduction when the type
1189 // is incomplete, so either instantiate any templates necessary to
1190 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001191 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001192 return Result;
1193
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001194 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001195 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001196 // ToVisit is our stack of records that we still need to visit.
1197 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1198 llvm::SmallVector<const RecordType *, 8> ToVisit;
1199 ToVisit.push_back(RecordT);
1200 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001201 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1202 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001203 while (!ToVisit.empty()) {
1204 // Retrieve the next class in the inheritance hierarchy.
1205 const RecordType *NextT = ToVisit.back();
1206 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001208 // If we have already seen this type, skip it.
1209 if (!Visited.insert(NextT))
1210 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001211
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001212 // If this is a base class, try to perform template argument
1213 // deduction from it.
1214 if (NextT != RecordT) {
1215 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001216 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001217 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001218
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001219 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001220 // note that we had some success. Otherwise, ignore any deductions
1221 // from this base class.
1222 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001223 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001224 DeducedOrig = Deduced;
1225 }
1226 else
1227 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001228 }
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001230 // Visit base classes
1231 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1232 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1233 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001234 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001235 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001236 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001237 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001238 }
1239 }
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001241 if (Successful)
1242 return Sema::TDK_Success;
1243 }
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001245 }
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001247 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001248 }
1249
Douglas Gregor637a4092009-06-10 23:47:09 +00001250 // T type::*
1251 // T T::*
1252 // T (type::*)()
1253 // type (T::*)()
1254 // type (type::*)(T)
1255 // type (T::*)(T)
1256 // T (type::*)(T)
1257 // T (T::*)()
1258 // T (T::*)(T)
1259 case Type::MemberPointer: {
1260 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1261 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1262 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001263 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001264
Douglas Gregorf67875d2009-06-12 18:26:56 +00001265 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001266 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001267 MemPtrParam->getPointeeType(),
1268 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001269 Info, Deduced,
1270 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001271 return Result;
1272
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001273 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001274 QualType(MemPtrParam->getClass(), 0),
1275 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001276 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001277 }
1278
Anders Carlsson9a917e42009-06-12 22:56:54 +00001279 // (clang extension)
1280 //
Mike Stump1eb44332009-09-09 15:08:12 +00001281 // type(^)(T)
1282 // T(^)()
1283 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001284 case Type::BlockPointer: {
1285 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1286 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Anders Carlsson859ba502009-06-12 16:23:10 +00001288 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001289 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001291 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001292 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001293 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001294 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001295 }
1296
Douglas Gregor637a4092009-06-10 23:47:09 +00001297 case Type::TypeOfExpr:
1298 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001299 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001300 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001301 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001302
Douglas Gregord560d502009-06-04 00:21:18 +00001303 default:
1304 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001305 }
1306
1307 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001308 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001309}
1310
Douglas Gregorf67875d2009-06-12 18:26:56 +00001311static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001312DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001313 TemplateParameterList *TemplateParams,
1314 const TemplateArgument &Param,
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001315 TemplateArgument Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001316 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001317 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001318 // If the template argument is a pack expansion, perform template argument
1319 // deduction against the pattern of that expansion. This only occurs during
1320 // partial ordering.
1321 if (Arg.isPackExpansion())
1322 Arg = Arg.getPackExpansionPattern();
1323
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001324 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001325 case TemplateArgument::Null:
1326 assert(false && "Null template argument in parameter list");
1327 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001328
1329 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001330 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001331 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001332 Arg.getAsType(), Info, Deduced, 0);
1333 Info.FirstArg = Param;
1334 Info.SecondArg = Arg;
1335 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001336
Douglas Gregor788cd062009-11-11 01:00:40 +00001337 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001338 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001339 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001340 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001341 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001342 Info.FirstArg = Param;
1343 Info.SecondArg = Arg;
1344 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001345
1346 case TemplateArgument::TemplateExpansion:
1347 llvm_unreachable("caller should handle pack expansions");
1348 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001349
Douglas Gregor199d9912009-06-05 00:53:49 +00001350 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001351 if (Arg.getKind() == TemplateArgument::Declaration &&
1352 Param.getAsDecl()->getCanonicalDecl() ==
1353 Arg.getAsDecl()->getCanonicalDecl())
1354 return Sema::TDK_Success;
1355
Douglas Gregorf67875d2009-06-12 18:26:56 +00001356 Info.FirstArg = Param;
1357 Info.SecondArg = Arg;
1358 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Douglas Gregor199d9912009-06-05 00:53:49 +00001360 case TemplateArgument::Integral:
1361 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001362 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001363 return Sema::TDK_Success;
1364
1365 Info.FirstArg = Param;
1366 Info.SecondArg = Arg;
1367 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001368 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001369
1370 if (Arg.getKind() == TemplateArgument::Expression) {
1371 Info.FirstArg = Param;
1372 Info.SecondArg = Arg;
1373 return Sema::TDK_NonDeducedMismatch;
1374 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001375
Douglas Gregorf67875d2009-06-12 18:26:56 +00001376 Info.FirstArg = Param;
1377 Info.SecondArg = Arg;
1378 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Douglas Gregor199d9912009-06-05 00:53:49 +00001380 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001381 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001382 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1383 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001384 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001385 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001386 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001387 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001388 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001389 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001390 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001391 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001392 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001393 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001394 Info, Deduced);
1395
Douglas Gregorf67875d2009-06-12 18:26:56 +00001396 Info.FirstArg = Param;
1397 Info.SecondArg = Arg;
1398 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001399 }
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Douglas Gregor199d9912009-06-05 00:53:49 +00001401 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001402 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001403 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001404 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001405 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001406 }
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Douglas Gregorf67875d2009-06-12 18:26:56 +00001408 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001409}
1410
Douglas Gregor20a55e22010-12-22 18:17:10 +00001411/// \brief Determine whether there is a template argument to be used for
1412/// deduction.
1413///
1414/// This routine "expands" argument packs in-place, overriding its input
1415/// parameters so that \c Args[ArgIdx] will be the available template argument.
1416///
1417/// \returns true if there is another template argument (which will be at
1418/// \c Args[ArgIdx]), false otherwise.
1419static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1420 unsigned &ArgIdx,
1421 unsigned &NumArgs) {
1422 if (ArgIdx == NumArgs)
1423 return false;
1424
1425 const TemplateArgument &Arg = Args[ArgIdx];
1426 if (Arg.getKind() != TemplateArgument::Pack)
1427 return true;
1428
1429 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1430 Args = Arg.pack_begin();
1431 NumArgs = Arg.pack_size();
1432 ArgIdx = 0;
1433 return ArgIdx < NumArgs;
1434}
1435
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001436/// \brief Determine whether the given set of template arguments has a pack
1437/// expansion that is not the last template argument.
1438static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1439 unsigned NumArgs) {
1440 unsigned ArgIdx = 0;
1441 while (ArgIdx < NumArgs) {
1442 const TemplateArgument &Arg = Args[ArgIdx];
1443
1444 // Unwrap argument packs.
1445 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1446 Args = Arg.pack_begin();
1447 NumArgs = Arg.pack_size();
1448 ArgIdx = 0;
1449 continue;
1450 }
1451
1452 ++ArgIdx;
1453 if (ArgIdx == NumArgs)
1454 return false;
1455
1456 if (Arg.isPackExpansion())
1457 return true;
1458 }
1459
1460 return false;
1461}
1462
Douglas Gregor20a55e22010-12-22 18:17:10 +00001463static Sema::TemplateDeductionResult
1464DeduceTemplateArguments(Sema &S,
1465 TemplateParameterList *TemplateParams,
1466 const TemplateArgument *Params, unsigned NumParams,
1467 const TemplateArgument *Args, unsigned NumArgs,
1468 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001469 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1470 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001471 // C++0x [temp.deduct.type]p9:
1472 // If the template argument list of P contains a pack expansion that is not
1473 // the last template argument, the entire template argument list is a
1474 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001475 if (hasPackExpansionBeforeEnd(Params, NumParams))
1476 return Sema::TDK_Success;
1477
Douglas Gregore02e2622010-12-22 21:19:48 +00001478 // C++0x [temp.deduct.type]p9:
1479 // If P has a form that contains <T> or <i>, then each argument Pi of the
1480 // respective template argument list P is compared with the corresponding
1481 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001482 unsigned ArgIdx = 0, ParamIdx = 0;
1483 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1484 ++ParamIdx) {
1485 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001486 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001487
1488 // Check whether we have enough arguments.
1489 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001490 return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
Douglas Gregor0972c862010-12-22 18:55:49 +00001491 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001492
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001493 if (Args[ArgIdx].isPackExpansion()) {
1494 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1495 // but applied to pack expansions that are template arguments.
1496 return Sema::TDK_NonDeducedMismatch;
1497 }
1498
Douglas Gregore02e2622010-12-22 21:19:48 +00001499 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001500 if (Sema::TemplateDeductionResult Result
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001501 = DeduceTemplateArguments(S, TemplateParams,
1502 Params[ParamIdx], Args[ArgIdx],
1503 Info, Deduced))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001504 return Result;
1505
1506 // Move to the next argument.
1507 ++ArgIdx;
1508 continue;
1509 }
1510
Douglas Gregore02e2622010-12-22 21:19:48 +00001511 // The parameter is a pack expansion.
1512
1513 // C++0x [temp.deduct.type]p9:
1514 // If Pi is a pack expansion, then the pattern of Pi is compared with
1515 // each remaining argument in the template argument list of A. Each
1516 // comparison deduces template arguments for subsequent positions in the
1517 // template parameter packs expanded by Pi.
1518 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1519
1520 // Compute the set of template parameter indices that correspond to
1521 // parameter packs expanded by the pack expansion.
1522 llvm::SmallVector<unsigned, 2> PackIndices;
1523 {
1524 llvm::BitVector SawIndices(TemplateParams->size());
1525 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1526 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1527 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1528 unsigned Depth, Index;
1529 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1530 if (Depth == 0 && !SawIndices[Index]) {
1531 SawIndices[Index] = true;
1532 PackIndices.push_back(Index);
1533 }
1534 }
1535 }
1536 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1537
1538 // FIXME: If there are no remaining arguments, we can bail out early
1539 // and set any deduced parameter packs to an empty argument pack.
1540 // The latter part of this is a (minor) correctness issue.
1541
1542 // Save the deduced template arguments for each parameter pack expanded
1543 // by this pack expansion, then clear out the deduction.
1544 llvm::SmallVector<DeducedTemplateArgument, 2>
1545 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00001546 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1547 NewlyDeducedPacks(PackIndices.size());
1548 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1549 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001550
1551 // Keep track of the deduced template arguments for each parameter pack
1552 // expanded by this pack expansion (the outer index) and for each
1553 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001554 bool HasAnyArguments = false;
1555 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1556 HasAnyArguments = true;
1557
1558 // Deduce template arguments from the pattern.
1559 if (Sema::TemplateDeductionResult Result
1560 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1561 Info, Deduced))
1562 return Result;
1563
1564 // Capture the deduced template arguments for each parameter pack expanded
1565 // by this pack expansion, add them to the list of arguments we've deduced
1566 // for that pack, then clear out the deduced argument.
1567 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1568 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1569 if (!DeducedArg.isNull()) {
1570 NewlyDeducedPacks[I].push_back(DeducedArg);
1571 DeducedArg = DeducedTemplateArgument();
1572 }
1573 }
1574
1575 ++ArgIdx;
1576 }
1577
1578 // Build argument packs for each of the parameter packs expanded by this
1579 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00001580 if (Sema::TemplateDeductionResult Result
1581 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
1582 Deduced, PackIndices, SavedPacks,
1583 NewlyDeducedPacks, Info))
1584 return Result;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001585 }
1586
1587 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001588 if (NumberOfArgumentsMustMatch &&
1589 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001590 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001591
1592 return Sema::TDK_Success;
1593}
1594
Mike Stump1eb44332009-09-09 15:08:12 +00001595static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001596DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001597 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001598 const TemplateArgumentList &ParamList,
1599 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001600 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001601 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001602 return DeduceTemplateArguments(S, TemplateParams,
1603 ParamList.data(), ParamList.size(),
1604 ArgList.data(), ArgList.size(),
1605 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001606}
1607
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001608/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001609static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001610 const TemplateArgument &X,
1611 const TemplateArgument &Y) {
1612 if (X.getKind() != Y.getKind())
1613 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001615 switch (X.getKind()) {
1616 case TemplateArgument::Null:
1617 assert(false && "Comparing NULL template argument");
1618 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001620 case TemplateArgument::Type:
1621 return Context.getCanonicalType(X.getAsType()) ==
1622 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001624 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001625 return X.getAsDecl()->getCanonicalDecl() ==
1626 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001627
Douglas Gregor788cd062009-11-11 01:00:40 +00001628 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001629 case TemplateArgument::TemplateExpansion:
1630 return Context.getCanonicalTemplateName(
1631 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1632 Context.getCanonicalTemplateName(
1633 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001634
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001635 case TemplateArgument::Integral:
1636 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Douglas Gregor788cd062009-11-11 01:00:40 +00001638 case TemplateArgument::Expression: {
1639 llvm::FoldingSetNodeID XID, YID;
1640 X.getAsExpr()->Profile(XID, Context, true);
1641 Y.getAsExpr()->Profile(YID, Context, true);
1642 return XID == YID;
1643 }
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001645 case TemplateArgument::Pack:
1646 if (X.pack_size() != Y.pack_size())
1647 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001648
1649 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1650 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001651 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001652 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001653 if (!isSameTemplateArg(Context, *XP, *YP))
1654 return false;
1655
1656 return true;
1657 }
1658
1659 return false;
1660}
1661
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001662/// \brief Allocate a TemplateArgumentLoc where all locations have
1663/// been initialized to the given location.
1664///
1665/// \param S The semantic analysis object.
1666///
1667/// \param The template argument we are producing template argument
1668/// location information for.
1669///
1670/// \param NTTPType For a declaration template argument, the type of
1671/// the non-type template parameter that corresponds to this template
1672/// argument.
1673///
1674/// \param Loc The source location to use for the resulting template
1675/// argument.
1676static TemplateArgumentLoc
1677getTrivialTemplateArgumentLoc(Sema &S,
1678 const TemplateArgument &Arg,
1679 QualType NTTPType,
1680 SourceLocation Loc) {
1681 switch (Arg.getKind()) {
1682 case TemplateArgument::Null:
1683 llvm_unreachable("Can't get a NULL template argument here");
1684 break;
1685
1686 case TemplateArgument::Type:
1687 return TemplateArgumentLoc(Arg,
1688 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1689
1690 case TemplateArgument::Declaration: {
1691 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001692 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001693 .takeAs<Expr>();
1694 return TemplateArgumentLoc(TemplateArgument(E), E);
1695 }
1696
1697 case TemplateArgument::Integral: {
1698 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001699 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001700 return TemplateArgumentLoc(TemplateArgument(E), E);
1701 }
1702
1703 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001704 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1705
1706 case TemplateArgument::TemplateExpansion:
1707 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1708
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001709 case TemplateArgument::Expression:
1710 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1711
1712 case TemplateArgument::Pack:
1713 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1714 }
1715
1716 return TemplateArgumentLoc();
1717}
1718
1719
1720/// \brief Convert the given deduced template argument and add it to the set of
1721/// fully-converted template arguments.
1722static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1723 DeducedTemplateArgument Arg,
1724 NamedDecl *Template,
1725 QualType NTTPType,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001726 unsigned ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001727 TemplateDeductionInfo &Info,
1728 bool InFunctionTemplate,
1729 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1730 if (Arg.getKind() == TemplateArgument::Pack) {
1731 // This is a template argument pack, so check each of its arguments against
1732 // the template parameter.
1733 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1734 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001735 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001736 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001737 // When converting the deduced template argument, append it to the
1738 // general output list. We need to do this so that the template argument
1739 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001740 DeducedTemplateArgument InnerArg(*PA);
1741 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1742 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001743 NTTPType, PackedArgsBuilder.size(),
1744 Info, InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001745 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001746
1747 // Move the converted template argument into our argument pack.
1748 PackedArgsBuilder.push_back(Output.back());
1749 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001750 }
1751
1752 // Create the resulting argument pack.
Douglas Gregor203e6a32011-01-11 23:09:57 +00001753 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
1754 PackedArgsBuilder.data(),
1755 PackedArgsBuilder.size()));
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001756 return false;
1757 }
1758
1759 // Convert the deduced template argument into a template
1760 // argument that we can check, almost as if the user had written
1761 // the template argument explicitly.
1762 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1763 Info.getLocation());
1764
1765 // Check the template argument, converting it as necessary.
1766 return S.CheckTemplateArgument(Param, ArgLoc,
1767 Template,
1768 Template->getLocation(),
1769 Template->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001770 ArgumentPackIndex,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001771 Output,
1772 InFunctionTemplate
1773 ? (Arg.wasDeducedFromArrayBound()
1774 ? Sema::CTAK_DeducedFromArrayBound
1775 : Sema::CTAK_Deduced)
1776 : Sema::CTAK_Specified);
1777}
1778
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001779/// Complete template argument deduction for a class template partial
1780/// specialization.
1781static Sema::TemplateDeductionResult
1782FinishTemplateArgumentDeduction(Sema &S,
1783 ClassTemplatePartialSpecializationDecl *Partial,
1784 const TemplateArgumentList &TemplateArgs,
1785 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001786 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001787 // Trap errors.
1788 Sema::SFINAETrap Trap(S);
1789
1790 Sema::ContextRAII SavedContext(S, Partial);
1791
1792 // C++ [temp.deduct.type]p2:
1793 // [...] or if any template argument remains neither deduced nor
1794 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001795 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001796 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1797 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001798 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001799 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001800 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001801 return Sema::TDK_Incomplete;
1802 }
1803
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001804 // We have deduced this argument, so it still needs to be
1805 // checked and converted.
1806
1807 // First, for a non-type template parameter type that is
1808 // initialized by a declaration, we need the type of the
1809 // corresponding non-type template parameter.
1810 QualType NTTPType;
1811 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001812 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001813 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001814 if (NTTPType->isDependentType()) {
1815 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1816 Builder.data(), Builder.size());
1817 NTTPType = S.SubstType(NTTPType,
1818 MultiLevelTemplateArgumentList(TemplateArgs),
1819 NTTP->getLocation(),
1820 NTTP->getDeclName());
1821 if (NTTPType.isNull()) {
1822 Info.Param = makeTemplateParameter(Param);
1823 // FIXME: These template arguments are temporary. Free them!
1824 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1825 Builder.data(),
1826 Builder.size()));
1827 return Sema::TDK_SubstitutionFailure;
1828 }
1829 }
1830 }
1831
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001832 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001833 Partial, NTTPType, 0, Info, false,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001834 Builder)) {
1835 Info.Param = makeTemplateParameter(Param);
1836 // FIXME: These template arguments are temporary. Free them!
1837 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1838 Builder.size()));
1839 return Sema::TDK_SubstitutionFailure;
1840 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001841 }
Douglas Gregor77d6bb92011-01-11 22:21:24 +00001842
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001843 // Form the template argument list from the deduced template arguments.
1844 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001845 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1846 Builder.size());
1847
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001848 Info.reset(DeducedArgumentList);
1849
1850 // Substitute the deduced template arguments into the template
1851 // arguments of the class template partial specialization, and
1852 // verify that the instantiated template arguments are both valid
1853 // and are equivalent to the template arguments originally provided
1854 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001855 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001856 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1857 const TemplateArgumentLoc *PartialTemplateArgs
1858 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001859
1860 // Note that we don't provide the langle and rangle locations.
1861 TemplateArgumentListInfo InstArgs;
1862
Douglas Gregore02e2622010-12-22 21:19:48 +00001863 if (S.Subst(PartialTemplateArgs,
1864 Partial->getNumTemplateArgsAsWritten(),
1865 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1866 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1867 if (ParamIdx >= Partial->getTemplateParameters()->size())
1868 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1869
1870 Decl *Param
1871 = const_cast<NamedDecl *>(
1872 Partial->getTemplateParameters()->getParam(ParamIdx));
1873 Info.Param = makeTemplateParameter(Param);
1874 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1875 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001876 }
1877
Douglas Gregor910f8002010-11-07 23:05:16 +00001878 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001879 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001880 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001881 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001882
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001883 TemplateParameterList *TemplateParams
1884 = ClassTemplate->getTemplateParameters();
1885 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001886 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001887 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001888 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001889 Info.FirstArg = TemplateArgs[I];
1890 Info.SecondArg = InstArg;
1891 return Sema::TDK_NonDeducedMismatch;
1892 }
1893 }
1894
1895 if (Trap.hasErrorOccurred())
1896 return Sema::TDK_SubstitutionFailure;
1897
1898 return Sema::TDK_Success;
1899}
1900
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001901/// \brief Perform template argument deduction to determine whether
1902/// the given template arguments match the given class template
1903/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001904Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001905Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001906 const TemplateArgumentList &TemplateArgs,
1907 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001908 // C++ [temp.class.spec.match]p2:
1909 // A partial specialization matches a given actual template
1910 // argument list if the template arguments of the partial
1911 // specialization can be deduced from the actual template argument
1912 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001913 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001914 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001915 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001916 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001917 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001918 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001919 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001920 TemplateArgs, Info, Deduced))
1921 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001922
Douglas Gregor637a4092009-06-10 23:47:09 +00001923 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001924 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001925 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001926 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001927
Douglas Gregorbb260412009-06-14 08:02:22 +00001928 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001929 return Sema::TDK_SubstitutionFailure;
1930
1931 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1932 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001933}
Douglas Gregor031a5882009-06-13 00:26:55 +00001934
Douglas Gregor41128772009-06-26 23:27:24 +00001935/// \brief Determine whether the given type T is a simple-template-id type.
1936static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001937 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001938 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001939 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Douglas Gregor41128772009-06-26 23:27:24 +00001941 return false;
1942}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001943
1944/// \brief Substitute the explicitly-provided template arguments into the
1945/// given function template according to C++ [temp.arg.explicit].
1946///
1947/// \param FunctionTemplate the function template into which the explicit
1948/// template arguments will be substituted.
1949///
Mike Stump1eb44332009-09-09 15:08:12 +00001950/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001951/// arguments.
1952///
Mike Stump1eb44332009-09-09 15:08:12 +00001953/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001954/// with the converted and checked explicit template arguments.
1955///
Mike Stump1eb44332009-09-09 15:08:12 +00001956/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001957/// parameters.
1958///
1959/// \param FunctionType if non-NULL, the result type of the function template
1960/// will also be instantiated and the pointed-to value will be updated with
1961/// the instantiated function type.
1962///
1963/// \param Info if substitution fails for any reason, this object will be
1964/// populated with more information about the failure.
1965///
1966/// \returns TDK_Success if substitution was successful, or some failure
1967/// condition.
1968Sema::TemplateDeductionResult
1969Sema::SubstituteExplicitTemplateArguments(
1970 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001971 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001972 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001973 llvm::SmallVectorImpl<QualType> &ParamTypes,
1974 QualType *FunctionType,
1975 TemplateDeductionInfo &Info) {
1976 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1977 TemplateParameterList *TemplateParams
1978 = FunctionTemplate->getTemplateParameters();
1979
John McCalld5532b62009-11-23 01:53:49 +00001980 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001981 // No arguments to substitute; just copy over the parameter types and
1982 // fill in the function type.
1983 for (FunctionDecl::param_iterator P = Function->param_begin(),
1984 PEnd = Function->param_end();
1985 P != PEnd;
1986 ++P)
1987 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Douglas Gregor83314aa2009-07-08 20:55:45 +00001989 if (FunctionType)
1990 *FunctionType = Function->getType();
1991 return TDK_Success;
1992 }
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregor83314aa2009-07-08 20:55:45 +00001994 // Substitution of the explicit template arguments into a function template
1995 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001996 SFINAETrap Trap(*this);
1997
Douglas Gregor83314aa2009-07-08 20:55:45 +00001998 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001999 // Template arguments that are present shall be specified in the
2000 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00002001 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00002002 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00002003 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00002004
2005 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002006 // explicitly-specified template arguments against this function template,
2007 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00002008 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002009 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002010 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2011 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002012 if (Inst)
2013 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Douglas Gregor83314aa2009-07-08 20:55:45 +00002015 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002016 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002017 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002018 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00002019 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00002020 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00002021 if (Index >= TemplateParams->size())
2022 Index = TemplateParams->size() - 1;
2023 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002024 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00002025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Douglas Gregor83314aa2009-07-08 20:55:45 +00002027 // Form the template argument list from the explicitly-specified
2028 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00002029 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002030 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002031 Info.reset(ExplicitArgumentList);
Douglas Gregord3731192011-01-10 07:32:04 +00002032
John McCalldf41f182010-10-12 19:40:14 +00002033 // Template argument deduction and the final substitution should be
2034 // done in the context of the templated declaration. Explicit
2035 // argument substitution, on the other hand, needs to happen in the
2036 // calling context.
2037 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2038
Douglas Gregord3731192011-01-10 07:32:04 +00002039 // If we deduced template arguments for a template parameter pack,
2040 // note that the template argument pack is partially substituted and record
2041 // the explicit template arguments. They'll be used as part of deduction
2042 // for this template parameter pack.
Douglas Gregord3731192011-01-10 07:32:04 +00002043 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2044 const TemplateArgument &Arg = Builder[I];
2045 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregord3731192011-01-10 07:32:04 +00002046 CurrentInstantiationScope->SetPartiallySubstitutedPack(
2047 TemplateParams->getParam(I),
2048 Arg.pack_begin(),
2049 Arg.pack_size());
2050 break;
2051 }
2052 }
2053
Douglas Gregor83314aa2009-07-08 20:55:45 +00002054 // Instantiate the types of each of the function parameters given the
2055 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00002056 if (SubstParmTypes(Function->getLocation(),
2057 Function->param_begin(), Function->getNumParams(),
2058 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2059 ParamTypes))
2060 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002061
2062 // If the caller wants a full function type back, instantiate the return
2063 // type and form that function type.
2064 if (FunctionType) {
2065 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00002066 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002067 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002068 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00002069
2070 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00002071 = SubstType(Proto->getResultType(),
2072 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2073 Function->getTypeSpecStartLoc(),
2074 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002075 if (ResultType.isNull() || Trap.hasErrorOccurred())
2076 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002077
2078 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002079 ParamTypes.data(), ParamTypes.size(),
2080 Proto->isVariadic(),
2081 Proto->getTypeQuals(),
2082 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00002083 Function->getDeclName(),
2084 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00002085 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2086 return TDK_SubstitutionFailure;
2087 }
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Douglas Gregor83314aa2009-07-08 20:55:45 +00002089 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002090 // Trailing template arguments that can be deduced (14.8.2) may be
2091 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00002092 // template arguments can be deduced, they may all be omitted; in this
2093 // case, the empty template argument list <> itself may also be omitted.
2094 //
Douglas Gregord3731192011-01-10 07:32:04 +00002095 // Take all of the explicitly-specified arguments and put them into
2096 // the set of deduced template arguments. Explicitly-specified
2097 // parameter packs, however, will be set to NULL since the deduction
2098 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002099 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00002100 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2101 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2102 if (Arg.getKind() == TemplateArgument::Pack)
2103 Deduced.push_back(DeducedTemplateArgument());
2104 else
2105 Deduced.push_back(Arg);
2106 }
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Douglas Gregor83314aa2009-07-08 20:55:45 +00002108 return TDK_Success;
2109}
2110
Mike Stump1eb44332009-09-09 15:08:12 +00002111/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002112/// checking the deduced template arguments for completeness and forming
2113/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002114Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00002115Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00002116 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2117 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002118 FunctionDecl *&Specialization,
2119 TemplateDeductionInfo &Info) {
2120 TemplateParameterList *TemplateParams
2121 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Douglas Gregor83314aa2009-07-08 20:55:45 +00002123 // Template argument deduction for function templates in a SFINAE context.
2124 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002125 SFINAETrap Trap(*this);
2126
Douglas Gregor83314aa2009-07-08 20:55:45 +00002127 // Enter a new template instantiation context while we instantiate the
2128 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002129 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002130 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002131 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2132 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002133 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002134 return TDK_InstantiationDepth;
2135
John McCall96db3102010-04-29 01:18:58 +00002136 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002137
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002138 // C++ [temp.deduct.type]p2:
2139 // [...] or if any template argument remains neither deduced nor
2140 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00002141 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002142 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2143 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002144
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002145 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002146 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002147 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002148 // argument, because it was explicitly-specified. Just record the
2149 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002150 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002151 continue;
2152 }
2153
2154 // We have deduced this argument, so it still needs to be
2155 // checked and converted.
2156
2157 // First, for a non-type template parameter type that is
2158 // initialized by a declaration, we need the type of the
2159 // corresponding non-type template parameter.
2160 QualType NTTPType;
2161 if (NonTypeTemplateParmDecl *NTTP
2162 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002163 NTTPType = NTTP->getType();
2164 if (NTTPType->isDependentType()) {
2165 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2166 Builder.data(), Builder.size());
2167 NTTPType = SubstType(NTTPType,
2168 MultiLevelTemplateArgumentList(TemplateArgs),
2169 NTTP->getLocation(),
2170 NTTP->getDeclName());
2171 if (NTTPType.isNull()) {
2172 Info.Param = makeTemplateParameter(Param);
2173 // FIXME: These template arguments are temporary. Free them!
2174 Info.reset(TemplateArgumentList::CreateCopy(Context,
2175 Builder.data(),
2176 Builder.size()));
2177 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002178 }
2179 }
2180 }
2181
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002182 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002183 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002184 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002185 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002186 // FIXME: These template arguments are temporary. Free them!
2187 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002188 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002189 return TDK_SubstitutionFailure;
2190 }
2191
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002192 continue;
2193 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002194
2195 // C++0x [temp.arg.explicit]p3:
2196 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2197 // be deduced to an empty sequence of template arguments.
2198 // FIXME: Where did the word "trailing" come from?
2199 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002200 // We may have had explicitly-specified template arguments for this
2201 // template parameter pack. If so, our empty deduction extends the
2202 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2203 const TemplateArgument *ExplicitArgs;
2204 unsigned NumExplicitArgs;
2205 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2206 &NumExplicitArgs)
2207 == Param)
2208 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2209 else
2210 Builder.push_back(TemplateArgument(0, 0));
2211
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002212 continue;
2213 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002214
2215 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002216 TemplateArgumentLoc DefArg
2217 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2218 FunctionTemplate->getLocation(),
2219 FunctionTemplate->getSourceRange().getEnd(),
2220 Param,
2221 Builder);
2222
2223 // If there was no default argument, deduction is incomplete.
2224 if (DefArg.getArgument().isNull()) {
2225 Info.Param = makeTemplateParameter(
2226 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2227 return TDK_Incomplete;
2228 }
2229
2230 // Check whether we can actually use the default argument.
2231 if (CheckTemplateArgument(Param, DefArg,
2232 FunctionTemplate,
2233 FunctionTemplate->getLocation(),
2234 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002235 0, Builder,
Douglas Gregor02024a92010-03-28 02:42:43 +00002236 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002237 Info.Param = makeTemplateParameter(
2238 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002239 // FIXME: These template arguments are temporary. Free them!
2240 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2241 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002242 return TDK_SubstitutionFailure;
2243 }
2244
2245 // If we get here, we successfully used the default template argument.
2246 }
2247
2248 // Form the template argument list from the deduced template arguments.
2249 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002250 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002251 Info.reset(DeducedArgumentList);
2252
Mike Stump1eb44332009-09-09 15:08:12 +00002253 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002254 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002255 DeclContext *Owner = FunctionTemplate->getDeclContext();
2256 if (FunctionTemplate->getFriendObjectKind())
2257 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002258 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002259 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002260 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002261 if (!Specialization)
2262 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Douglas Gregorf8825742009-09-15 18:26:13 +00002264 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2265 FunctionTemplate->getCanonicalDecl());
2266
Mike Stump1eb44332009-09-09 15:08:12 +00002267 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002268 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002269 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2270 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002271 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Douglas Gregor83314aa2009-07-08 20:55:45 +00002273 // There may have been an error that did not prevent us from constructing a
2274 // declaration. Mark the declaration invalid and return with a substitution
2275 // failure.
2276 if (Trap.hasErrorOccurred()) {
2277 Specialization->setInvalidDecl(true);
2278 return TDK_SubstitutionFailure;
2279 }
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Douglas Gregor9b623632010-10-12 23:32:35 +00002281 // If we suppressed any diagnostics while performing template argument
2282 // deduction, and if we haven't already instantiated this declaration,
2283 // keep track of these diagnostics. They'll be emitted if this specialization
2284 // is actually used.
2285 if (Info.diag_begin() != Info.diag_end()) {
2286 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2287 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2288 if (Pos == SuppressedDiagnostics.end())
2289 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2290 .append(Info.diag_begin(), Info.diag_end());
2291 }
2292
Mike Stump1eb44332009-09-09 15:08:12 +00002293 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002294}
2295
John McCall9c72c602010-08-27 09:08:28 +00002296/// Gets the type of a function for template-argument-deducton
2297/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002298static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002299 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002300 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002301 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002302 if (Method->isInstance()) {
2303 // An instance method that's referenced in a form that doesn't
2304 // look like a member pointer is just invalid.
2305 if (!R.HasFormOfMemberPointer) return QualType();
2306
John McCalleff92132010-02-02 02:21:27 +00002307 return Context.getMemberPointerType(Fn->getType(),
2308 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002309 }
2310
2311 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002312 return Context.getPointerType(Fn->getType());
2313}
2314
2315/// Apply the deduction rules for overload sets.
2316///
2317/// \return the null type if this argument should be treated as an
2318/// undeduced context
2319static QualType
2320ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002321 Expr *Arg, QualType ParamType,
2322 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002323
2324 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002325
John McCall9c72c602010-08-27 09:08:28 +00002326 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002327
Douglas Gregor75f21af2010-08-30 21:04:23 +00002328 // C++0x [temp.deduct.call]p4
2329 unsigned TDF = 0;
2330 if (ParamWasReference)
2331 TDF |= TDF_ParamWithReferenceType;
2332 if (R.IsAddressOfOperand)
2333 TDF |= TDF_IgnoreQualifiers;
2334
John McCalleff92132010-02-02 02:21:27 +00002335 // If there were explicit template arguments, we can only find
2336 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2337 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002338 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002339 // But we can still look for an explicit specialization.
2340 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002341 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002342 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002343 return QualType();
2344 }
2345
2346 // C++0x [temp.deduct.call]p6:
2347 // When P is a function type, pointer to function type, or pointer
2348 // to member function type:
2349
2350 if (!ParamType->isFunctionType() &&
2351 !ParamType->isFunctionPointerType() &&
2352 !ParamType->isMemberFunctionPointerType())
2353 return QualType();
2354
2355 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002356 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2357 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002358 NamedDecl *D = (*I)->getUnderlyingDecl();
2359
2360 // - If the argument is an overload set containing one or more
2361 // function templates, the parameter is treated as a
2362 // non-deduced context.
2363 if (isa<FunctionTemplateDecl>(D))
2364 return QualType();
2365
2366 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002367 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2368 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002369
Douglas Gregor75f21af2010-08-30 21:04:23 +00002370 // Function-to-pointer conversion.
2371 if (!ParamWasReference && ParamType->isPointerType() &&
2372 ArgType->isFunctionType())
2373 ArgType = S.Context.getPointerType(ArgType);
2374
John McCalleff92132010-02-02 02:21:27 +00002375 // - If the argument is an overload set (not containing function
2376 // templates), trial argument deduction is attempted using each
2377 // of the members of the set. If deduction succeeds for only one
2378 // of the overload set members, that member is used as the
2379 // argument value for the deduction. If deduction succeeds for
2380 // more than one member of the overload set the parameter is
2381 // treated as a non-deduced context.
2382
2383 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2384 // Type deduction is done independently for each P/A pair, and
2385 // the deduced template argument values are then combined.
2386 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002387 llvm::SmallVector<DeducedTemplateArgument, 8>
2388 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002389 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002390 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002391 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002392 ParamType, ArgType,
2393 Info, Deduced, TDF);
2394 if (Result) continue;
2395 if (!Match.isNull()) return QualType();
2396 Match = ArgType;
2397 }
2398
2399 return Match;
2400}
2401
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002402/// \brief Perform the adjustments to the parameter and argument types
2403/// described in C++ [temp.deduct.call].
2404///
2405/// \returns true if the caller should not attempt to perform any template
2406/// argument deduction based on this P/A pair.
2407static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2408 TemplateParameterList *TemplateParams,
2409 QualType &ParamType,
2410 QualType &ArgType,
2411 Expr *Arg,
2412 unsigned &TDF) {
2413 // C++0x [temp.deduct.call]p3:
2414 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2415 // are ignored for type deduction.
2416 if (ParamType.getCVRQualifiers())
2417 ParamType = ParamType.getLocalUnqualifiedType();
2418 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2419 if (ParamRefType) {
Douglas Gregor2ad746a2011-01-21 05:18:22 +00002420 // [C++0x] If P is an rvalue reference to a cv-unqualified
2421 // template parameter and the argument is an lvalue, the type
2422 // "lvalue reference to A" is used in place of A for type
2423 // deduction.
2424 if (const RValueReferenceType *RValueRef
2425 = dyn_cast<RValueReferenceType>(ParamType)) {
2426 if (!RValueRef->getPointeeType().getQualifiers() &&
2427 isa<TemplateTypeParmType>(RValueRef->getPointeeType()) &&
2428 Arg->Classify(S.Context).isLValue())
2429 ArgType = S.Context.getLValueReferenceType(ArgType);
2430 }
2431
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002432 // [...] If P is a reference type, the type referred to by P is used
2433 // for type deduction.
2434 ParamType = ParamRefType->getPointeeType();
2435 }
Douglas Gregor5c7bf422011-01-11 17:34:58 +00002436
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002437 // Overload sets usually make this parameter an undeduced
2438 // context, but there are sometimes special circumstances.
2439 if (ArgType == S.Context.OverloadTy) {
2440 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2441 Arg, ParamType,
2442 ParamRefType != 0);
2443 if (ArgType.isNull())
2444 return true;
2445 }
2446
2447 if (ParamRefType) {
2448 // C++0x [temp.deduct.call]p3:
2449 // [...] If P is of the form T&&, where T is a template parameter, and
2450 // the argument is an lvalue, the type A& is used in place of A for
2451 // type deduction.
2452 if (ParamRefType->isRValueReferenceType() &&
2453 ParamRefType->getAs<TemplateTypeParmType>() &&
2454 Arg->isLValue())
2455 ArgType = S.Context.getLValueReferenceType(ArgType);
2456 } else {
2457 // C++ [temp.deduct.call]p2:
2458 // If P is not a reference type:
2459 // - If A is an array type, the pointer type produced by the
2460 // array-to-pointer standard conversion (4.2) is used in place of
2461 // A for type deduction; otherwise,
2462 if (ArgType->isArrayType())
2463 ArgType = S.Context.getArrayDecayedType(ArgType);
2464 // - If A is a function type, the pointer type produced by the
2465 // function-to-pointer standard conversion (4.3) is used in place
2466 // of A for type deduction; otherwise,
2467 else if (ArgType->isFunctionType())
2468 ArgType = S.Context.getPointerType(ArgType);
2469 else {
2470 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2471 // type are ignored for type deduction.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002472 if (ArgType.getCVRQualifiers())
2473 ArgType = ArgType.getUnqualifiedType();
2474 }
2475 }
2476
2477 // C++0x [temp.deduct.call]p4:
2478 // In general, the deduction process attempts to find template argument
2479 // values that will make the deduced A identical to A (after the type A
2480 // is transformed as described above). [...]
2481 TDF = TDF_SkipNonDependent;
2482
2483 // - If the original P is a reference type, the deduced A (i.e., the
2484 // type referred to by the reference) can be more cv-qualified than
2485 // the transformed A.
2486 if (ParamRefType)
2487 TDF |= TDF_ParamWithReferenceType;
2488 // - The transformed A can be another pointer or pointer to member
2489 // type that can be converted to the deduced A via a qualification
2490 // conversion (4.4).
2491 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2492 ArgType->isObjCObjectPointerType())
2493 TDF |= TDF_IgnoreQualifiers;
2494 // - If P is a class and P has the form simple-template-id, then the
2495 // transformed A can be a derived class of the deduced A. Likewise,
2496 // if P is a pointer to a class of the form simple-template-id, the
2497 // transformed A can be a pointer to a derived class pointed to by
2498 // the deduced A.
2499 if (isSimpleTemplateIdType(ParamType) ||
2500 (isa<PointerType>(ParamType) &&
2501 isSimpleTemplateIdType(
2502 ParamType->getAs<PointerType>()->getPointeeType())))
2503 TDF |= TDF_DerivedClass;
2504
2505 return false;
2506}
2507
Douglas Gregore53060f2009-06-25 22:08:12 +00002508/// \brief Perform template argument deduction from a function call
2509/// (C++ [temp.deduct.call]).
2510///
2511/// \param FunctionTemplate the function template for which we are performing
2512/// template argument deduction.
2513///
Douglas Gregor48026d22010-01-11 18:40:55 +00002514/// \param ExplicitTemplateArguments the explicit template arguments provided
2515/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002516///
Douglas Gregore53060f2009-06-25 22:08:12 +00002517/// \param Args the function call arguments
2518///
2519/// \param NumArgs the number of arguments in Args
2520///
Douglas Gregor48026d22010-01-11 18:40:55 +00002521/// \param Name the name of the function being called. This is only significant
2522/// when the function template is a conversion function template, in which
2523/// case this routine will also perform template argument deduction based on
2524/// the function to which
2525///
Douglas Gregore53060f2009-06-25 22:08:12 +00002526/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002527/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002528/// template argument deduction.
2529///
2530/// \param Info the argument will be updated to provide additional information
2531/// about template argument deduction.
2532///
2533/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002534Sema::TemplateDeductionResult
2535Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002536 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002537 Expr **Args, unsigned NumArgs,
2538 FunctionDecl *&Specialization,
2539 TemplateDeductionInfo &Info) {
2540 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002541
Douglas Gregore53060f2009-06-25 22:08:12 +00002542 // C++ [temp.deduct.call]p1:
2543 // Template argument deduction is done by comparing each function template
2544 // parameter type (call it P) with the type of the corresponding argument
2545 // of the call (call it A) as described below.
2546 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002547 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002548 return TDK_TooFewArguments;
2549 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002550 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002551 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002552 if (Proto->isTemplateVariadic())
2553 /* Do nothing */;
2554 else if (Proto->isVariadic())
2555 CheckArgs = Function->getNumParams();
2556 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002557 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002558 }
Mike Stump1eb44332009-09-09 15:08:12 +00002559
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002560 // The types of the parameters from which we will perform template argument
2561 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002562 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002563 TemplateParameterList *TemplateParams
2564 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002565 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002566 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002567 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002568 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002569 TemplateDeductionResult Result =
2570 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002571 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002572 Deduced,
2573 ParamTypes,
2574 0,
2575 Info);
2576 if (Result)
2577 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002578
2579 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002580 } else {
2581 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002582 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002583 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2584 }
Mike Stump1eb44332009-09-09 15:08:12 +00002585
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002586 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002587 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002588 unsigned ArgIdx = 0;
2589 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2590 ParamIdx != NumParams; ++ParamIdx) {
2591 QualType ParamType = ParamTypes[ParamIdx];
2592
2593 const PackExpansionType *ParamExpansion
2594 = dyn_cast<PackExpansionType>(ParamType);
2595 if (!ParamExpansion) {
2596 // Simple case: matching a function parameter to a function argument.
2597 if (ArgIdx >= CheckArgs)
2598 break;
2599
2600 Expr *Arg = Args[ArgIdx++];
2601 QualType ArgType = Arg->getType();
2602 unsigned TDF = 0;
2603 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2604 ParamType, ArgType, Arg,
2605 TDF))
2606 continue;
2607
2608 if (TemplateDeductionResult Result
2609 = ::DeduceTemplateArguments(*this, TemplateParams,
2610 ParamType, ArgType, Info, Deduced,
2611 TDF))
2612 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002613
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002614 // FIXME: we need to check that the deduced A is the same as A,
2615 // modulo the various allowed differences.
2616 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002617 }
2618
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002619 // C++0x [temp.deduct.call]p1:
2620 // For a function parameter pack that occurs at the end of the
2621 // parameter-declaration-list, the type A of each remaining argument of
2622 // the call is compared with the type P of the declarator-id of the
2623 // function parameter pack. Each comparison deduces template arguments
2624 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002625 // the function parameter pack. For a function parameter pack that does
2626 // not occur at the end of the parameter-declaration-list, the type of
2627 // the parameter pack is a non-deduced context.
2628 if (ParamIdx + 1 < NumParams)
2629 break;
2630
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002631 QualType ParamPattern = ParamExpansion->getPattern();
2632 llvm::SmallVector<unsigned, 2> PackIndices;
2633 {
2634 llvm::BitVector SawIndices(TemplateParams->size());
2635 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2636 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2637 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2638 unsigned Depth, Index;
2639 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2640 if (Depth == 0 && !SawIndices[Index]) {
2641 SawIndices[Index] = true;
2642 PackIndices.push_back(Index);
2643 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002644 }
2645 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002646 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2647
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002648 // Keep track of the deduced template arguments for each parameter pack
2649 // expanded by this pack expansion (the outer index) and for each
2650 // template argument (the inner SmallVectors).
2651 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00002652 NewlyDeducedPacks(PackIndices.size());
Douglas Gregord3731192011-01-10 07:32:04 +00002653 llvm::SmallVector<DeducedTemplateArgument, 2>
2654 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00002655 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
2656 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002657 bool HasAnyArguments = false;
2658 for (; ArgIdx < NumArgs; ++ArgIdx) {
2659 HasAnyArguments = true;
2660
2661 ParamType = ParamPattern;
2662 Expr *Arg = Args[ArgIdx];
2663 QualType ArgType = Arg->getType();
2664 unsigned TDF = 0;
2665 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2666 ParamType, ArgType, Arg,
2667 TDF)) {
2668 // We can't actually perform any deduction for this argument, so stop
2669 // deduction at this point.
2670 ++ArgIdx;
2671 break;
2672 }
2673
2674 if (TemplateDeductionResult Result
2675 = ::DeduceTemplateArguments(*this, TemplateParams,
2676 ParamType, ArgType, Info, Deduced,
2677 TDF))
2678 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002680 // Capture the deduced template arguments for each parameter pack expanded
2681 // by this pack expansion, add them to the list of arguments we've deduced
2682 // for that pack, then clear out the deduced argument.
2683 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2684 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2685 if (!DeducedArg.isNull()) {
2686 NewlyDeducedPacks[I].push_back(DeducedArg);
2687 DeducedArg = DeducedTemplateArgument();
2688 }
2689 }
2690 }
2691
2692 // Build argument packs for each of the parameter packs expanded by this
2693 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00002694 if (Sema::TemplateDeductionResult Result
2695 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
2696 Deduced, PackIndices, SavedPacks,
2697 NewlyDeducedPacks, Info))
2698 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002700 // After we've matching against a parameter pack, we're done.
2701 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002702 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002703
Mike Stump1eb44332009-09-09 15:08:12 +00002704 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002705 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002706 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002707}
2708
Douglas Gregor83314aa2009-07-08 20:55:45 +00002709/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002710/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2711/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002712///
2713/// \param FunctionTemplate the function template for which we are performing
2714/// template argument deduction.
2715///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002716/// \param ExplicitTemplateArguments the explicitly-specified template
2717/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002718///
2719/// \param ArgFunctionType the function type that will be used as the
2720/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002721/// function template's function type. This type may be NULL, if there is no
2722/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002723///
2724/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002725/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002726/// template argument deduction.
2727///
2728/// \param Info the argument will be updated to provide additional information
2729/// about template argument deduction.
2730///
2731/// \returns the result of template argument deduction.
2732Sema::TemplateDeductionResult
2733Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002734 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002735 QualType ArgFunctionType,
2736 FunctionDecl *&Specialization,
2737 TemplateDeductionInfo &Info) {
2738 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2739 TemplateParameterList *TemplateParams
2740 = FunctionTemplate->getTemplateParameters();
2741 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002742
Douglas Gregor83314aa2009-07-08 20:55:45 +00002743 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002744 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002745 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2746 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002747 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002748 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002749 if (TemplateDeductionResult Result
2750 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002751 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002752 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002753 &FunctionType, Info))
2754 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002755
2756 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002757 }
2758
2759 // Template argument deduction for function templates in a SFINAE context.
2760 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002761 SFINAETrap Trap(*this);
2762
John McCalleff92132010-02-02 02:21:27 +00002763 Deduced.resize(TemplateParams->size());
2764
Douglas Gregor4b52e252009-12-21 23:17:24 +00002765 if (!ArgFunctionType.isNull()) {
2766 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002767 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002768 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002769 FunctionType, ArgFunctionType, Info,
2770 Deduced, 0))
2771 return Result;
2772 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002773
2774 if (TemplateDeductionResult Result
2775 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2776 NumExplicitlySpecified,
2777 Specialization, Info))
2778 return Result;
2779
2780 // If the requested function type does not match the actual type of the
2781 // specialization, template argument deduction fails.
2782 if (!ArgFunctionType.isNull() &&
2783 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2784 return TDK_NonDeducedMismatch;
2785
2786 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002787}
2788
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002789/// \brief Deduce template arguments for a templated conversion
2790/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2791/// conversion function template specialization.
2792Sema::TemplateDeductionResult
2793Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2794 QualType ToType,
2795 CXXConversionDecl *&Specialization,
2796 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002797 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002798 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2799 QualType FromType = Conv->getConversionType();
2800
2801 // Canonicalize the types for deduction.
2802 QualType P = Context.getCanonicalType(FromType);
2803 QualType A = Context.getCanonicalType(ToType);
2804
2805 // C++0x [temp.deduct.conv]p3:
2806 // If P is a reference type, the type referred to by P is used for
2807 // type deduction.
2808 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2809 P = PRef->getPointeeType();
2810
2811 // C++0x [temp.deduct.conv]p3:
2812 // If A is a reference type, the type referred to by A is used
2813 // for type deduction.
2814 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2815 A = ARef->getPointeeType();
2816 // C++ [temp.deduct.conv]p2:
2817 //
Mike Stump1eb44332009-09-09 15:08:12 +00002818 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002819 else {
2820 assert(!A->isReferenceType() && "Reference types were handled above");
2821
2822 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002823 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002824 // of P for type deduction; otherwise,
2825 if (P->isArrayType())
2826 P = Context.getArrayDecayedType(P);
2827 // - If P is a function type, the pointer type produced by the
2828 // function-to-pointer standard conversion (4.3) is used in
2829 // place of P for type deduction; otherwise,
2830 else if (P->isFunctionType())
2831 P = Context.getPointerType(P);
2832 // - If P is a cv-qualified type, the top level cv-qualifiers of
2833 // P’s type are ignored for type deduction.
2834 else
2835 P = P.getUnqualifiedType();
2836
2837 // C++0x [temp.deduct.conv]p3:
2838 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2839 // type are ignored for type deduction.
2840 A = A.getUnqualifiedType();
2841 }
2842
2843 // Template argument deduction for function templates in a SFINAE context.
2844 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002845 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002846
2847 // C++ [temp.deduct.conv]p1:
2848 // Template argument deduction is done by comparing the return
2849 // type of the template conversion function (call it P) with the
2850 // type that is required as the result of the conversion (call it
2851 // A) as described in 14.8.2.4.
2852 TemplateParameterList *TemplateParams
2853 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002854 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002855 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002856
2857 // C++0x [temp.deduct.conv]p4:
2858 // In general, the deduction process attempts to find template
2859 // argument values that will make the deduced A identical to
2860 // A. However, there are two cases that allow a difference:
2861 unsigned TDF = 0;
2862 // - If the original A is a reference type, A can be more
2863 // cv-qualified than the deduced A (i.e., the type referred to
2864 // by the reference)
2865 if (ToType->isReferenceType())
2866 TDF |= TDF_ParamWithReferenceType;
2867 // - The deduced A can be another pointer or pointer to member
2868 // type that can be converted to A via a qualification
2869 // conversion.
2870 //
2871 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2872 // both P and A are pointers or member pointers. In this case, we
2873 // just ignore cv-qualifiers completely).
2874 if ((P->isPointerType() && A->isPointerType()) ||
2875 (P->isMemberPointerType() && P->isMemberPointerType()))
2876 TDF |= TDF_IgnoreQualifiers;
2877 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002878 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002879 P, A, Info, Deduced, TDF))
2880 return Result;
2881
2882 // FIXME: we need to check that the deduced A is the same as A,
2883 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002884
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002885 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002886 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002887 FunctionDecl *Spec = 0;
2888 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002889 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2890 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002891 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2892 return Result;
2893}
2894
Douglas Gregor4b52e252009-12-21 23:17:24 +00002895/// \brief Deduce template arguments for a function template when there is
2896/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2897///
2898/// \param FunctionTemplate the function template for which we are performing
2899/// template argument deduction.
2900///
2901/// \param ExplicitTemplateArguments the explicitly-specified template
2902/// arguments.
2903///
2904/// \param Specialization if template argument deduction was successful,
2905/// this will be set to the function template specialization produced by
2906/// template argument deduction.
2907///
2908/// \param Info the argument will be updated to provide additional information
2909/// about template argument deduction.
2910///
2911/// \returns the result of template argument deduction.
2912Sema::TemplateDeductionResult
2913Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2914 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2915 FunctionDecl *&Specialization,
2916 TemplateDeductionInfo &Info) {
2917 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2918 QualType(), Specialization, Info);
2919}
2920
Douglas Gregor8a514912009-09-14 18:39:43 +00002921static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002922MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2923 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002924 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002925 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002926
2927/// \brief If this is a non-static member function,
2928static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2929 CXXMethodDecl *Method,
2930 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2931 if (Method->isStatic())
2932 return;
2933
2934 // C++ [over.match.funcs]p4:
2935 //
2936 // For non-static member functions, the type of the implicit
2937 // object parameter is
2938 // — "lvalue reference to cv X" for functions declared without a
2939 // ref-qualifier or with the & ref-qualifier
2940 // - "rvalue reference to cv X" for functions declared with the
2941 // && ref-qualifier
2942 //
2943 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2944 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2945 ArgTy = Context.getQualifiedType(ArgTy,
2946 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2947 ArgTy = Context.getLValueReferenceType(ArgTy);
2948 ArgTypes.push_back(ArgTy);
2949}
2950
Douglas Gregor8a514912009-09-14 18:39:43 +00002951/// \brief Determine whether the function template \p FT1 is at least as
2952/// specialized as \p FT2.
2953static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002954 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002955 FunctionTemplateDecl *FT1,
2956 FunctionTemplateDecl *FT2,
2957 TemplatePartialOrderingContext TPOC,
Douglas Gregorb939a192011-01-21 17:29:42 +00002958 unsigned NumCallArguments,
2959 llvm::SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002960 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2961 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2962 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2963 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2964
2965 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2966 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002967 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002968 Deduced.resize(TemplateParams->size());
2969
2970 // C++0x [temp.deduct.partial]p3:
2971 // The types used to determine the ordering depend on the context in which
2972 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002973 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002974 CXXMethodDecl *Method1 = 0;
2975 CXXMethodDecl *Method2 = 0;
2976 bool IsNonStatic2 = false;
2977 bool IsNonStatic1 = false;
2978 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002979 switch (TPOC) {
2980 case TPOC_Call: {
2981 // - In the context of a function call, the function parameter types are
2982 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002983 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2984 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2985 IsNonStatic1 = Method1 && !Method1->isStatic();
2986 IsNonStatic2 = Method2 && !Method2->isStatic();
2987
2988 // C++0x [temp.func.order]p3:
2989 // [...] If only one of the function templates is a non-static
2990 // member, that function template is considered to have a new
2991 // first parameter inserted in its function parameter list. The
2992 // new parameter is of type "reference to cv A," where cv are
2993 // the cv-qualifiers of the function template (if any) and A is
2994 // the class of which the function template is a member.
2995 //
2996 // C++98/03 doesn't have this provision, so instead we drop the
2997 // first argument of the free function or static member, which
2998 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002999 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003000 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
3001 IsNonStatic2 && !IsNonStatic1;
3002 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003003 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
Douglas Gregor77bc5722010-11-12 23:44:13 +00003004 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003005 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00003006
3007 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003008 Skip2 = !S.getLangOptions().CPlusPlus0x &&
3009 IsNonStatic1 && !IsNonStatic2;
3010 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00003011 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
3012 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003013 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003014
3015 // C++ [temp.func.order]p5:
3016 // The presence of unused ellipsis and default arguments has no effect on
3017 // the partial ordering of function templates.
3018 if (Args1.size() > NumCallArguments)
3019 Args1.resize(NumCallArguments);
3020 if (Args2.size() > NumCallArguments)
3021 Args2.resize(NumCallArguments);
3022 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
3023 Args1.data(), Args1.size(), Info, Deduced,
3024 TDF_None, /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003025 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003026 return false;
3027
3028 break;
3029 }
3030
3031 case TPOC_Conversion:
3032 // - In the context of a call to a conversion operator, the return types
3033 // of the conversion function templates are used.
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003034 if (DeduceTemplateArguments(S, TemplateParams, Proto2->getResultType(),
3035 Proto1->getResultType(), Info, Deduced,
3036 TDF_None, /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003037 RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003038 return false;
3039 break;
3040
3041 case TPOC_Other:
3042 // - In other contexts (14.6.6.2) the function template’s function type
3043 // is used.
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003044 // FIXME: Don't we actually want to perform the adjustments on the parameter
3045 // types?
3046 if (DeduceTemplateArguments(S, TemplateParams, FD2->getType(),
3047 FD1->getType(), Info, Deduced, TDF_None,
Douglas Gregorb939a192011-01-21 17:29:42 +00003048 /*PartialOrdering=*/true, RefParamComparisons))
Douglas Gregor8a514912009-09-14 18:39:43 +00003049 return false;
3050 break;
3051 }
3052
3053 // C++0x [temp.deduct.partial]p11:
3054 // In most cases, all template parameters must have values in order for
3055 // deduction to succeed, but for partial ordering purposes a template
3056 // parameter may remain without a value provided it is not used in the
3057 // types being used for partial ordering. [ Note: a template parameter used
3058 // in a non-deduced context is considered used. -end note]
3059 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3060 for (; ArgIdx != NumArgs; ++ArgIdx)
3061 if (Deduced[ArgIdx].isNull())
3062 break;
3063
3064 if (ArgIdx == NumArgs) {
3065 // All template arguments were deduced. FT1 is at least as specialized
3066 // as FT2.
3067 return true;
3068 }
3069
Douglas Gregore73bb602009-09-14 21:25:05 +00003070 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003071 llvm::SmallVector<bool, 4> UsedParameters;
3072 UsedParameters.resize(TemplateParams->size());
3073 switch (TPOC) {
3074 case TPOC_Call: {
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003075 unsigned NumParams = std::min(NumCallArguments,
3076 std::min(Proto1->getNumArgs(),
3077 Proto2->getNumArgs()));
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003078 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3079 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3080 TemplateParams->getDepth(), UsedParameters);
3081 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003082 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3083 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003084 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003085 break;
3086 }
3087
3088 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003089 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3090 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003091 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003092 break;
3093
3094 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003095 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3096 TemplateParams->getDepth(),
3097 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003098 break;
3099 }
3100
3101 for (; ArgIdx != NumArgs; ++ArgIdx)
3102 // If this argument had no value deduced but was used in one of the types
3103 // used for partial ordering, then deduction fails.
3104 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3105 return false;
3106
3107 return true;
3108}
3109
Douglas Gregor9da95e62011-01-16 16:03:23 +00003110/// \brief Determine whether this a function template whose parameter-type-list
3111/// ends with a function parameter pack.
3112static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
3113 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3114 unsigned NumParams = Function->getNumParams();
3115 if (NumParams == 0)
3116 return false;
3117
3118 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
3119 if (!Last->isParameterPack())
3120 return false;
3121
3122 // Make sure that no previous parameter is a parameter pack.
3123 while (--NumParams > 0) {
3124 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
3125 return false;
3126 }
3127
3128 return true;
3129}
Douglas Gregor8a514912009-09-14 18:39:43 +00003130
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003131/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003132/// to the rules of function template partial ordering (C++ [temp.func.order]).
3133///
3134/// \param FT1 the first function template
3135///
3136/// \param FT2 the second function template
3137///
Douglas Gregor8a514912009-09-14 18:39:43 +00003138/// \param TPOC the context in which we are performing partial ordering of
3139/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003140///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003141/// \param NumCallArguments The number of arguments in a call, used only
3142/// when \c TPOC is \c TPOC_Call.
3143///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003144/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003145/// template is more specialized, returns NULL.
3146FunctionTemplateDecl *
3147Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3148 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003149 SourceLocation Loc,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003150 TemplatePartialOrderingContext TPOC,
3151 unsigned NumCallArguments) {
Douglas Gregorb939a192011-01-21 17:29:42 +00003152 llvm::SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003153 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
3154 NumCallArguments, 0);
John McCall5769d612010-02-08 23:07:23 +00003155 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003156 NumCallArguments,
Douglas Gregorb939a192011-01-21 17:29:42 +00003157 &RefParamComparisons);
Douglas Gregor8a514912009-09-14 18:39:43 +00003158
3159 if (Better1 != Better2) // We have a clear winner
3160 return Better1? FT1 : FT2;
3161
3162 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003163 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003164
Douglas Gregor8a514912009-09-14 18:39:43 +00003165 // C++0x [temp.deduct.partial]p10:
3166 // If for each type being considered a given template is at least as
3167 // specialized for all types and more specialized for some set of types and
3168 // the other template is not more specialized for any types or is not at
3169 // least as specialized for any types, then the given template is more
3170 // specialized than the other template. Otherwise, neither template is more
3171 // specialized than the other.
3172 Better1 = false;
3173 Better2 = false;
Douglas Gregorb939a192011-01-21 17:29:42 +00003174 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003175 // C++0x [temp.deduct.partial]p9:
3176 // If, for a given type, deduction succeeds in both directions (i.e., the
Douglas Gregorb939a192011-01-21 17:29:42 +00003177 // types are identical after the transformations above) and both P and A
3178 // were reference types (before being replaced with the type referred to
3179 // above):
3180
3181 // -- if the type from the argument template was an lvalue reference
3182 // and the type from the parameter template was not, the argument
3183 // type is considered to be more specialized than the other;
3184 // otherwise,
3185 if (!RefParamComparisons[I].ArgIsRvalueRef &&
3186 RefParamComparisons[I].ParamIsRvalueRef) {
3187 Better2 = true;
3188 if (Better1)
3189 return 0;
3190 continue;
3191 } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
3192 RefParamComparisons[I].ArgIsRvalueRef) {
3193 Better1 = true;
3194 if (Better2)
3195 return 0;
3196 continue;
Douglas Gregor8a514912009-09-14 18:39:43 +00003197 }
Douglas Gregorb939a192011-01-21 17:29:42 +00003198
3199 // -- if the type from the argument template is more cv-qualified than
3200 // the type from the parameter template (as described above), the
3201 // argument type is considered to be more specialized than the
3202 // other; otherwise,
3203 switch (RefParamComparisons[I].Qualifiers) {
3204 case NeitherMoreQualified:
3205 break;
3206
3207 case ParamMoreQualified:
3208 Better1 = true;
3209 if (Better2)
3210 return 0;
3211 continue;
3212
3213 case ArgMoreQualified:
3214 Better2 = true;
3215 if (Better1)
3216 return 0;
3217 continue;
3218 }
3219
3220 // -- neither type is more specialized than the other.
Douglas Gregor8a514912009-09-14 18:39:43 +00003221 }
3222
3223 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003224 if (Better1)
3225 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003226 else if (Better2)
3227 return FT2;
Douglas Gregor9da95e62011-01-16 16:03:23 +00003228
3229 // FIXME: This mimics what GCC implements, but doesn't match up with the
3230 // proposed resolution for core issue 692. This area needs to be sorted out,
3231 // but for now we attempt to maintain compatibility.
3232 bool Variadic1 = isVariadicFunctionTemplate(FT1);
3233 bool Variadic2 = isVariadicFunctionTemplate(FT2);
3234 if (Variadic1 != Variadic2)
3235 return Variadic1? FT2 : FT1;
3236
3237 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003238}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003239
Douglas Gregord5a423b2009-09-25 18:43:00 +00003240/// \brief Determine if the two templates are equivalent.
3241static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3242 if (T1 == T2)
3243 return true;
3244
3245 if (!T1 || !T2)
3246 return false;
3247
3248 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3249}
3250
3251/// \brief Retrieve the most specialized of the given function template
3252/// specializations.
3253///
John McCallc373d482010-01-27 01:50:18 +00003254/// \param SpecBegin the start iterator of the function template
3255/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003256///
John McCallc373d482010-01-27 01:50:18 +00003257/// \param SpecEnd the end iterator of the function template
3258/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003259///
3260/// \param TPOC the partial ordering context to use to compare the function
3261/// template specializations.
3262///
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003263/// \param NumCallArguments The number of arguments in a call, used only
3264/// when \c TPOC is \c TPOC_Call.
3265///
Douglas Gregord5a423b2009-09-25 18:43:00 +00003266/// \param Loc the location where the ambiguity or no-specializations
3267/// diagnostic should occur.
3268///
3269/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3270/// no matching candidates.
3271///
3272/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3273/// occurs.
3274///
3275/// \param CandidateDiag partial diagnostic used for each function template
3276/// specialization that is a candidate in the ambiguous ordering. One parameter
3277/// in this diagnostic should be unbound, which will correspond to the string
3278/// describing the template arguments for the function template specialization.
3279///
3280/// \param Index if non-NULL and the result of this function is non-nULL,
3281/// receives the index corresponding to the resulting function template
3282/// specialization.
3283///
3284/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003285/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003286///
3287/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3288/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003289UnresolvedSetIterator
3290Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003291 UnresolvedSetIterator SpecEnd,
John McCallc373d482010-01-27 01:50:18 +00003292 TemplatePartialOrderingContext TPOC,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003293 unsigned NumCallArguments,
John McCallc373d482010-01-27 01:50:18 +00003294 SourceLocation Loc,
3295 const PartialDiagnostic &NoneDiag,
3296 const PartialDiagnostic &AmbigDiag,
3297 const PartialDiagnostic &CandidateDiag) {
3298 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003299 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003300 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003301 }
3302
John McCallc373d482010-01-27 01:50:18 +00003303 if (SpecBegin + 1 == SpecEnd)
3304 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003305
3306 // Find the function template that is better than all of the templates it
3307 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003308 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003309 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003310 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003311 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003312 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3313 FunctionTemplateDecl *Challenger
3314 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003315 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003316 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003317 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003318 Challenger)) {
3319 Best = I;
3320 BestTemplate = Challenger;
3321 }
3322 }
3323
3324 // Make sure that the "best" function template is more specialized than all
3325 // of the others.
3326 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003327 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3328 FunctionTemplateDecl *Challenger
3329 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003330 if (I != Best &&
3331 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003332 Loc, TPOC, NumCallArguments),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003333 BestTemplate)) {
3334 Ambiguous = true;
3335 break;
3336 }
3337 }
3338
3339 if (!Ambiguous) {
3340 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003341 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003342 }
3343
3344 // Diagnose the ambiguity.
3345 Diag(Loc, AmbigDiag);
3346
3347 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003348 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3349 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003350 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003351 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3352 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003353
John McCallc373d482010-01-27 01:50:18 +00003354 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003355}
3356
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003357/// \brief Returns the more specialized class template partial specialization
3358/// according to the rules of partial ordering of class template partial
3359/// specializations (C++ [temp.class.order]).
3360///
3361/// \param PS1 the first class template partial specialization
3362///
3363/// \param PS2 the second class template partial specialization
3364///
3365/// \returns the more specialized class template partial specialization. If
3366/// neither partial specialization is more specialized, returns NULL.
3367ClassTemplatePartialSpecializationDecl *
3368Sema::getMoreSpecializedPartialSpecialization(
3369 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003370 ClassTemplatePartialSpecializationDecl *PS2,
3371 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003372 // C++ [temp.class.order]p1:
3373 // For two class template partial specializations, the first is at least as
3374 // specialized as the second if, given the following rewrite to two
3375 // function templates, the first function template is at least as
3376 // specialized as the second according to the ordering rules for function
3377 // templates (14.6.6.2):
3378 // - the first function template has the same template parameters as the
3379 // first partial specialization and has a single function parameter
3380 // whose type is a class template specialization with the template
3381 // arguments of the first partial specialization, and
3382 // - the second function template has the same template parameters as the
3383 // second partial specialization and has a single function parameter
3384 // whose type is a class template specialization with the template
3385 // arguments of the second partial specialization.
3386 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003387 // Rather than synthesize function templates, we merely perform the
3388 // equivalent partial ordering by performing deduction directly on
3389 // the template arguments of the class template partial
3390 // specializations. This computation is slightly simpler than the
3391 // general problem of function template partial ordering, because
3392 // class template partial specializations are more constrained. We
3393 // know that every template parameter is deducible from the class
3394 // template partial specialization's template arguments, for
3395 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003396 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003397 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003398
3399 QualType PT1 = PS1->getInjectedSpecializationType();
3400 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003401
3402 // Determine whether PS1 is at least as specialized as PS2
3403 Deduced.resize(PS2->getTemplateParameters()->size());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003404 bool Better1 = !::DeduceTemplateArguments(*this, PS2->getTemplateParameters(),
3405 PT2, PT1, Info, Deduced, TDF_None,
3406 /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003407 /*RefParamComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003408 if (Better1) {
3409 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3410 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003411 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3412 PS1->getTemplateArgs(),
3413 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003414 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003415
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003416 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003417 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003418 Deduced.resize(PS1->getTemplateParameters()->size());
Douglas Gregor5c7bf422011-01-11 17:34:58 +00003419 bool Better2 = !::DeduceTemplateArguments(*this, PS1->getTemplateParameters(),
3420 PT1, PT2, Info, Deduced, TDF_None,
3421 /*PartialOrdering=*/true,
Douglas Gregorb939a192011-01-21 17:29:42 +00003422 /*RefParamComparisons=*/0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003423 if (Better2) {
3424 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3425 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003426 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3427 PS2->getTemplateArgs(),
3428 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003429 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003430
3431 if (Better1 == Better2)
3432 return 0;
3433
3434 return Better1? PS1 : PS2;
3435}
3436
Mike Stump1eb44332009-09-09 15:08:12 +00003437static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003438MarkUsedTemplateParameters(Sema &SemaRef,
3439 const TemplateArgument &TemplateArg,
3440 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003441 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003442 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003443
Douglas Gregore73bb602009-09-14 21:25:05 +00003444/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003445/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003446static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003447MarkUsedTemplateParameters(Sema &SemaRef,
3448 const Expr *E,
3449 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003450 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003451 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003452 // We can deduce from a pack expansion.
3453 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3454 E = Expansion->getPattern();
3455
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003456 // Skip through any implicit casts we added while type-checking.
3457 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3458 E = ICE->getSubExpr();
3459
Douglas Gregore73bb602009-09-14 21:25:05 +00003460 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3461 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003462 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003463 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003464 return;
3465
Mike Stump1eb44332009-09-09 15:08:12 +00003466 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003467 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3468 if (!NTTP)
3469 return;
3470
Douglas Gregored9c0f92009-10-29 00:04:11 +00003471 if (NTTP->getDepth() == Depth)
3472 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003473}
3474
Douglas Gregore73bb602009-09-14 21:25:05 +00003475/// \brief Mark the template parameters that are used by the given
3476/// nested name specifier.
3477static void
3478MarkUsedTemplateParameters(Sema &SemaRef,
3479 NestedNameSpecifier *NNS,
3480 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003481 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003482 llvm::SmallVectorImpl<bool> &Used) {
3483 if (!NNS)
3484 return;
3485
Douglas Gregored9c0f92009-10-29 00:04:11 +00003486 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3487 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003488 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003489 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003490}
3491
3492/// \brief Mark the template parameters that are used by the given
3493/// template name.
3494static void
3495MarkUsedTemplateParameters(Sema &SemaRef,
3496 TemplateName Name,
3497 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003498 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003499 llvm::SmallVectorImpl<bool> &Used) {
3500 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3501 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003502 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3503 if (TTP->getDepth() == Depth)
3504 Used[TTP->getIndex()] = true;
3505 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003506 return;
3507 }
3508
Douglas Gregor788cd062009-11-11 01:00:40 +00003509 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3510 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3511 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003512 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003513 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3514 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003515}
3516
3517/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003518/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003519static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003520MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3521 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003522 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003523 llvm::SmallVectorImpl<bool> &Used) {
3524 if (T.isNull())
3525 return;
3526
Douglas Gregor031a5882009-06-13 00:26:55 +00003527 // Non-dependent types have nothing deducible
3528 if (!T->isDependentType())
3529 return;
3530
3531 T = SemaRef.Context.getCanonicalType(T);
3532 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003533 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003534 MarkUsedTemplateParameters(SemaRef,
3535 cast<PointerType>(T)->getPointeeType(),
3536 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003537 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003538 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003539 break;
3540
3541 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003542 MarkUsedTemplateParameters(SemaRef,
3543 cast<BlockPointerType>(T)->getPointeeType(),
3544 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003545 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003546 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003547 break;
3548
3549 case Type::LValueReference:
3550 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003551 MarkUsedTemplateParameters(SemaRef,
3552 cast<ReferenceType>(T)->getPointeeType(),
3553 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003554 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003555 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003556 break;
3557
3558 case Type::MemberPointer: {
3559 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003560 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003561 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003562 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003563 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003564 break;
3565 }
3566
3567 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003568 MarkUsedTemplateParameters(SemaRef,
3569 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003570 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003571 // Fall through to check the element type
3572
3573 case Type::ConstantArray:
3574 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003575 MarkUsedTemplateParameters(SemaRef,
3576 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003577 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003578 break;
3579
3580 case Type::Vector:
3581 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003582 MarkUsedTemplateParameters(SemaRef,
3583 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003584 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003585 break;
3586
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003587 case Type::DependentSizedExtVector: {
3588 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003589 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003590 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003591 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003592 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003593 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003594 break;
3595 }
3596
Douglas Gregor031a5882009-06-13 00:26:55 +00003597 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003598 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003599 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003600 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003601 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003602 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003603 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003604 break;
3605 }
3606
Douglas Gregored9c0f92009-10-29 00:04:11 +00003607 case Type::TemplateTypeParm: {
3608 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3609 if (TTP->getDepth() == Depth)
3610 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003611 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003612 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003613
Douglas Gregor0bc15d92011-01-14 05:11:40 +00003614 case Type::SubstTemplateTypeParmPack: {
3615 const SubstTemplateTypeParmPackType *Subst
3616 = cast<SubstTemplateTypeParmPackType>(T);
3617 MarkUsedTemplateParameters(SemaRef,
3618 QualType(Subst->getReplacedParameter(), 0),
3619 OnlyDeduced, Depth, Used);
3620 MarkUsedTemplateParameters(SemaRef, Subst->getArgumentPack(),
3621 OnlyDeduced, Depth, Used);
3622 break;
3623 }
3624
John McCall31f17ec2010-04-27 00:57:59 +00003625 case Type::InjectedClassName:
3626 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3627 // fall through
3628
Douglas Gregor031a5882009-06-13 00:26:55 +00003629 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003630 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003631 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003632 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003633 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003634
3635 // C++0x [temp.deduct.type]p9:
3636 // If the template argument list of P contains a pack expansion that is not
3637 // the last template argument, the entire template argument list is a
3638 // non-deduced context.
3639 if (OnlyDeduced &&
3640 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3641 break;
3642
Douglas Gregore73bb602009-09-14 21:25:05 +00003643 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003644 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3645 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003646 break;
3647 }
3648
Douglas Gregore73bb602009-09-14 21:25:05 +00003649 case Type::Complex:
3650 if (!OnlyDeduced)
3651 MarkUsedTemplateParameters(SemaRef,
3652 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003653 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003654 break;
3655
Douglas Gregor4714c122010-03-31 17:34:00 +00003656 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003657 if (!OnlyDeduced)
3658 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003659 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003660 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003661 break;
3662
John McCall33500952010-06-11 00:33:02 +00003663 case Type::DependentTemplateSpecialization: {
3664 const DependentTemplateSpecializationType *Spec
3665 = cast<DependentTemplateSpecializationType>(T);
3666 if (!OnlyDeduced)
3667 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3668 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003669
3670 // C++0x [temp.deduct.type]p9:
3671 // If the template argument list of P contains a pack expansion that is not
3672 // the last template argument, the entire template argument list is a
3673 // non-deduced context.
3674 if (OnlyDeduced &&
3675 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3676 break;
3677
John McCall33500952010-06-11 00:33:02 +00003678 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3679 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3680 Used);
3681 break;
3682 }
3683
John McCallad5e7382010-03-01 23:49:17 +00003684 case Type::TypeOf:
3685 if (!OnlyDeduced)
3686 MarkUsedTemplateParameters(SemaRef,
3687 cast<TypeOfType>(T)->getUnderlyingType(),
3688 OnlyDeduced, Depth, Used);
3689 break;
3690
3691 case Type::TypeOfExpr:
3692 if (!OnlyDeduced)
3693 MarkUsedTemplateParameters(SemaRef,
3694 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3695 OnlyDeduced, Depth, Used);
3696 break;
3697
3698 case Type::Decltype:
3699 if (!OnlyDeduced)
3700 MarkUsedTemplateParameters(SemaRef,
3701 cast<DecltypeType>(T)->getUnderlyingExpr(),
3702 OnlyDeduced, Depth, Used);
3703 break;
3704
Douglas Gregor7536dd52010-12-20 02:24:11 +00003705 case Type::PackExpansion:
3706 MarkUsedTemplateParameters(SemaRef,
3707 cast<PackExpansionType>(T)->getPattern(),
3708 OnlyDeduced, Depth, Used);
3709 break;
3710
Douglas Gregore73bb602009-09-14 21:25:05 +00003711 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003712 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003713 case Type::VariableArray:
3714 case Type::FunctionNoProto:
3715 case Type::Record:
3716 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003717 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003718 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003719 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003720 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003721#define TYPE(Class, Base)
3722#define ABSTRACT_TYPE(Class, Base)
3723#define DEPENDENT_TYPE(Class, Base)
3724#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3725#include "clang/AST/TypeNodes.def"
3726 break;
3727 }
3728}
3729
Douglas Gregore73bb602009-09-14 21:25:05 +00003730/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003731/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003732static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003733MarkUsedTemplateParameters(Sema &SemaRef,
3734 const TemplateArgument &TemplateArg,
3735 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003736 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003737 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003738 switch (TemplateArg.getKind()) {
3739 case TemplateArgument::Null:
3740 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003741 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003742 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003743
Douglas Gregor031a5882009-06-13 00:26:55 +00003744 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003745 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003746 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003747 break;
3748
Douglas Gregor788cd062009-11-11 01:00:40 +00003749 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003750 case TemplateArgument::TemplateExpansion:
3751 MarkUsedTemplateParameters(SemaRef,
3752 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003753 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003754 break;
3755
3756 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003757 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003758 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003759 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003760
Anders Carlssond01b1da2009-06-15 17:04:53 +00003761 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003762 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3763 PEnd = TemplateArg.pack_end();
3764 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003765 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003766 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003767 }
3768}
3769
3770/// \brief Mark the template parameters can be deduced by the given
3771/// template argument list.
3772///
3773/// \param TemplateArgs the template argument list from which template
3774/// parameters will be deduced.
3775///
3776/// \param Deduced a bit vector whose elements will be set to \c true
3777/// to indicate when the corresponding template parameter will be
3778/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003779void
Douglas Gregore73bb602009-09-14 21:25:05 +00003780Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003781 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003782 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003783 // C++0x [temp.deduct.type]p9:
3784 // If the template argument list of P contains a pack expansion that is not
3785 // the last template argument, the entire template argument list is a
3786 // non-deduced context.
3787 if (OnlyDeduced &&
3788 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3789 return;
3790
Douglas Gregor031a5882009-06-13 00:26:55 +00003791 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003792 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3793 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003794}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003795
3796/// \brief Marks all of the template parameters that will be deduced by a
3797/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003798void
3799Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3800 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003801 TemplateParameterList *TemplateParams
3802 = FunctionTemplate->getTemplateParameters();
3803 Deduced.clear();
3804 Deduced.resize(TemplateParams->size());
3805
3806 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3807 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3808 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003809 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003810}