blob: a72a29378a8199c530b31ba5b7f41573870d064b [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 Gregord708c722009-06-09 16:35:58 +000083 const 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 Gregor20a55e22010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
90 const TemplateArgument *Params, unsigned NumParams,
91 const TemplateArgument *Args, unsigned NumArgs,
92 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000093 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +000095
Douglas Gregor199d9912009-06-05 00:53:49 +000096/// \brief If the given expression is of a form that permits the deduction
97/// of a non-type template parameter, return the declaration of that
98/// non-type template parameter.
99static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
100 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
101 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Douglas Gregor199d9912009-06-05 00:53:49 +0000103 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
104 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Douglas Gregor199d9912009-06-05 00:53:49 +0000106 return 0;
107}
108
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000109/// \brief Determine whether two declaration pointers refer to the same
110/// declaration.
111static bool isSameDeclaration(Decl *X, Decl *Y) {
112 if (!X || !Y)
113 return !X && !Y;
114
115 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
116 X = NX->getUnderlyingDecl();
117 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
118 Y = NY->getUnderlyingDecl();
119
120 return X->getCanonicalDecl() == Y->getCanonicalDecl();
121}
122
123/// \brief Verify that the given, deduced template arguments are compatible.
124///
125/// \returns The deduced template argument, or a NULL template argument if
126/// the deduced template arguments were incompatible.
127static DeducedTemplateArgument
128checkDeducedTemplateArguments(ASTContext &Context,
129 const DeducedTemplateArgument &X,
130 const DeducedTemplateArgument &Y) {
131 // We have no deduction for one or both of the arguments; they're compatible.
132 if (X.isNull())
133 return Y;
134 if (Y.isNull())
135 return X;
136
137 switch (X.getKind()) {
138 case TemplateArgument::Null:
139 llvm_unreachable("Non-deduced template arguments handled above");
140
141 case TemplateArgument::Type:
142 // If two template type arguments have the same type, they're compatible.
143 if (Y.getKind() == TemplateArgument::Type &&
144 Context.hasSameType(X.getAsType(), Y.getAsType()))
145 return X;
146
147 return DeducedTemplateArgument();
148
149 case TemplateArgument::Integral:
150 // If we deduced a constant in one case and either a dependent expression or
151 // declaration in another case, keep the integral constant.
152 // If both are integral constants with the same value, keep that value.
153 if (Y.getKind() == TemplateArgument::Expression ||
154 Y.getKind() == TemplateArgument::Declaration ||
155 (Y.getKind() == TemplateArgument::Integral &&
156 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
157 return DeducedTemplateArgument(X,
158 X.wasDeducedFromArrayBound() &&
159 Y.wasDeducedFromArrayBound());
160
161 // All other combinations are incompatible.
162 return DeducedTemplateArgument();
163
164 case TemplateArgument::Template:
165 if (Y.getKind() == TemplateArgument::Template &&
166 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
167 return X;
168
169 // All other combinations are incompatible.
170 return DeducedTemplateArgument();
171
172 case TemplateArgument::Expression:
173 // If we deduced a dependent expression in one case and either an integral
174 // constant or a declaration in another case, keep the integral constant
175 // or declaration.
176 if (Y.getKind() == TemplateArgument::Integral ||
177 Y.getKind() == TemplateArgument::Declaration)
178 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
179 Y.wasDeducedFromArrayBound());
180
181 if (Y.getKind() == TemplateArgument::Expression) {
182 // Compare the expressions for equality
183 llvm::FoldingSetNodeID ID1, ID2;
184 X.getAsExpr()->Profile(ID1, Context, true);
185 Y.getAsExpr()->Profile(ID2, Context, true);
186 if (ID1 == ID2)
187 return X;
188 }
189
190 // All other combinations are incompatible.
191 return DeducedTemplateArgument();
192
193 case TemplateArgument::Declaration:
194 // If we deduced a declaration and a dependent expression, keep the
195 // declaration.
196 if (Y.getKind() == TemplateArgument::Expression)
197 return X;
198
199 // If we deduced a declaration and an integral constant, keep the
200 // integral constant.
201 if (Y.getKind() == TemplateArgument::Integral)
202 return Y;
203
204 // If we deduced two declarations, make sure they they refer to the
205 // same declaration.
206 if (Y.getKind() == TemplateArgument::Declaration &&
207 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
208 return X;
209
210 // All other combinations are incompatible.
211 return DeducedTemplateArgument();
212
213 case TemplateArgument::Pack:
214 if (Y.getKind() != TemplateArgument::Pack ||
215 X.pack_size() != Y.pack_size())
216 return DeducedTemplateArgument();
217
218 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
219 XAEnd = X.pack_end(),
220 YA = Y.pack_begin();
221 XA != XAEnd; ++XA, ++YA) {
222 // FIXME: We've lost the "deduced from array bound" bit.
223 if (checkDeducedTemplateArguments(Context, *XA, *YA).isNull())
224 return DeducedTemplateArgument();
225 }
226
227 return X;
228 }
229
230 return DeducedTemplateArgument();
231}
232
Mike Stump1eb44332009-09-09 15:08:12 +0000233/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000234/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000235static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000236DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000237 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000238 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000239 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000240 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000241 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000242 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000243 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000245 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
246 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
247 Deduced[NTTP->getIndex()],
248 NewDeduced);
249 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000250 Info.Param = NTTP;
251 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000252 Info.SecondArg = NewDeduced;
253 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000254 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000255
256 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000257 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000258}
259
Mike Stump1eb44332009-09-09 15:08:12 +0000260/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000261/// from the given type- or value-dependent expression.
262///
263/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000264static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000265DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000266 NonTypeTemplateParmDecl *NTTP,
267 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000268 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000269 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000270 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000271 "Cannot deduce non-type template argument with depth > 0");
272 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
273 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000275 DeducedTemplateArgument NewDeduced(Value);
276 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
277 Deduced[NTTP->getIndex()],
278 NewDeduced);
279
280 if (Result.isNull()) {
281 Info.Param = NTTP;
282 Info.FirstArg = Deduced[NTTP->getIndex()];
283 Info.SecondArg = NewDeduced;
284 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000285 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000286
287 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000288 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000289}
290
Douglas Gregor15755cb2009-11-13 23:45:44 +0000291/// \brief Deduce the value of the given non-type template parameter
292/// from the given declaration.
293///
294/// \returns true if deduction succeeded, false otherwise.
295static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000296DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000297 NonTypeTemplateParmDecl *NTTP,
298 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000299 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000300 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000301 assert(NTTP->getDepth() == 0 &&
302 "Cannot deduce non-type template argument with depth > 0");
303
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000304 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
305 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
306 Deduced[NTTP->getIndex()],
307 NewDeduced);
308 if (Result.isNull()) {
309 Info.Param = NTTP;
310 Info.FirstArg = Deduced[NTTP->getIndex()];
311 Info.SecondArg = NewDeduced;
312 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000313 }
314
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000315 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000316 return Sema::TDK_Success;
317}
318
Douglas Gregorf67875d2009-06-12 18:26:56 +0000319static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000320DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000321 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000322 TemplateName Param,
323 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000324 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000325 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000326 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000327 if (!ParamDecl) {
328 // The parameter type is dependent and is not a template template parameter,
329 // so there is nothing that we can deduce.
330 return Sema::TDK_Success;
331 }
332
333 if (TemplateTemplateParmDecl *TempParam
334 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000335 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
336 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
337 Deduced[TempParam->getIndex()],
338 NewDeduced);
339 if (Result.isNull()) {
340 Info.Param = TempParam;
341 Info.FirstArg = Deduced[TempParam->getIndex()];
342 Info.SecondArg = NewDeduced;
343 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000344 }
345
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000346 Deduced[TempParam->getIndex()] = Result;
347 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000348 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000349
350 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000351 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000352 return Sema::TDK_Success;
353
354 // Mismatch of non-dependent template parameter to argument.
355 Info.FirstArg = TemplateArgument(Param);
356 Info.SecondArg = TemplateArgument(Arg);
357 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000358}
359
Mike Stump1eb44332009-09-09 15:08:12 +0000360/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000361/// type (which is a template-id) with the template argument type.
362///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000363/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000364///
365/// \param TemplateParams the template parameters that we are deducing
366///
367/// \param Param the parameter type
368///
369/// \param Arg the argument type
370///
371/// \param Info information about the template argument deduction itself
372///
373/// \param Deduced the deduced template arguments
374///
375/// \returns the result of template argument deduction so far. Note that a
376/// "success" result means that template argument deduction has not yet failed,
377/// but it may still fail, later, for other reasons.
378static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000379DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000380 TemplateParameterList *TemplateParams,
381 const TemplateSpecializationType *Param,
382 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000383 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000384 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000385 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000387 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000388 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000389 = dyn_cast<TemplateSpecializationType>(Arg)) {
390 // Perform template argument deduction for the template name.
391 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000392 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000393 Param->getTemplateName(),
394 SpecArg->getTemplateName(),
395 Info, Deduced))
396 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000399 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000400 // argument. Ignore any missing/extra arguments, since they could be
401 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000402 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000403 Param->getArgs(), Param->getNumArgs(),
404 SpecArg->getArgs(), SpecArg->getNumArgs(),
405 Info, Deduced,
406 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000409 // If the argument type is a class template specialization, we
410 // perform template argument deduction using its template
411 // arguments.
412 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
413 if (!RecordArg)
414 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000415
416 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000417 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
418 if (!SpecArg)
419 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000421 // Perform template argument deduction for the template name.
422 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000423 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000424 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000425 Param->getTemplateName(),
426 TemplateName(SpecArg->getSpecializedTemplate()),
427 Info, Deduced))
428 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Douglas Gregor20a55e22010-12-22 18:17:10 +0000430 // Perform template argument deduction for the template arguments.
431 return DeduceTemplateArguments(S, TemplateParams,
432 Param->getArgs(), Param->getNumArgs(),
433 SpecArg->getTemplateArgs().data(),
434 SpecArg->getTemplateArgs().size(),
435 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000436}
437
John McCallcd05e812010-08-28 22:14:41 +0000438/// \brief Determines whether the given type is an opaque type that
439/// might be more qualified when instantiated.
440static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
441 switch (T->getTypeClass()) {
442 case Type::TypeOfExpr:
443 case Type::TypeOf:
444 case Type::DependentName:
445 case Type::Decltype:
446 case Type::UnresolvedUsing:
447 return true;
448
449 case Type::ConstantArray:
450 case Type::IncompleteArray:
451 case Type::VariableArray:
452 case Type::DependentSizedArray:
453 return IsPossiblyOpaquelyQualifiedType(
454 cast<ArrayType>(T)->getElementType());
455
456 default:
457 return false;
458 }
459}
460
Douglas Gregor500d3312009-06-26 18:27:22 +0000461/// \brief Deduce the template arguments by comparing the parameter type and
462/// the argument type (C++ [temp.deduct.type]).
463///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000464/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000465///
466/// \param TemplateParams the template parameters that we are deducing
467///
468/// \param ParamIn the parameter type
469///
470/// \param ArgIn the argument type
471///
472/// \param Info information about the template argument deduction itself
473///
474/// \param Deduced the deduced template arguments
475///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000476/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000477/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000478///
479/// \returns the result of template argument deduction so far. Note that a
480/// "success" result means that template argument deduction has not yet failed,
481/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000482static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000483DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000484 TemplateParameterList *TemplateParams,
485 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000486 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000487 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000488 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000489 // We only want to look at the canonical types, since typedefs and
490 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000491 QualType Param = S.Context.getCanonicalType(ParamIn);
492 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000493
Douglas Gregor500d3312009-06-26 18:27:22 +0000494 // C++0x [temp.deduct.call]p4 bullet 1:
495 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000496 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000497 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000498 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000499 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000500 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000501 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
502 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000503 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000504 }
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000506 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000507 if (!Param->isDependentType()) {
508 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
509
510 return Sema::TDK_NonDeducedMismatch;
511 }
512
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000513 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000514 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000515
Douglas Gregor199d9912009-06-05 00:53:49 +0000516 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000517 // A template type argument T, a template template argument TT or a
518 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000519 // the following forms:
520 //
521 // T
522 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000523 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000524 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000525 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000526 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000528 // If the argument type is an array type, move the qualifiers up to the
529 // top level, so they can be matched with the qualifiers on the parameter.
530 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000531 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000532 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000533 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000534 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000535 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000536 RecanonicalizeArg = true;
537 }
538 }
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000540 // The argument type can not be less qualified than the parameter
541 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000542 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000543 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000544 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000545 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000546 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000547 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000548
549 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000550 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000551 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000552
553 // local manipulation is okay because it's canonical
554 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000555 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000556 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000558 DeducedTemplateArgument NewDeduced(DeducedType);
559 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
560 Deduced[Index],
561 NewDeduced);
562 if (Result.isNull()) {
563 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
564 Info.FirstArg = Deduced[Index];
565 Info.SecondArg = NewDeduced;
566 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000567 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000568
569 Deduced[Index] = Result;
570 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000571 }
572
Douglas Gregorf67875d2009-06-12 18:26:56 +0000573 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000574 Info.FirstArg = TemplateArgument(ParamIn);
575 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000576
Douglas Gregor508f1c82009-06-26 23:10:12 +0000577 // Check the cv-qualifiers on the parameter and argument types.
578 if (!(TDF & TDF_IgnoreQualifiers)) {
579 if (TDF & TDF_ParamWithReferenceType) {
580 if (Param.isMoreQualifiedThan(Arg))
581 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000582 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000583 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000584 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000585 }
586 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000587
Douglas Gregord560d502009-06-04 00:21:18 +0000588 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000589 // No deduction possible for these types
590 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000591 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Douglas Gregor199d9912009-06-05 00:53:49 +0000593 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000594 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000595 QualType PointeeType;
596 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
597 PointeeType = PointerArg->getPointeeType();
598 } else if (const ObjCObjectPointerType *PointerArg
599 = Arg->getAs<ObjCObjectPointerType>()) {
600 PointeeType = PointerArg->getPointeeType();
601 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000602 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000603 }
Mike Stump1eb44332009-09-09 15:08:12 +0000604
Douglas Gregor41128772009-06-26 23:27:24 +0000605 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000606 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000607 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000608 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000609 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000610 }
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Douglas Gregor199d9912009-06-05 00:53:49 +0000612 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000613 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000614 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000615 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000616 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000618 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000619 cast<LValueReferenceType>(Param)->getPointeeType(),
620 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000621 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000622 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000623
Douglas Gregor199d9912009-06-05 00:53:49 +0000624 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000625 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000626 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000627 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000628 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000630 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000631 cast<RValueReferenceType>(Param)->getPointeeType(),
632 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000633 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000634 }
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Douglas Gregor199d9912009-06-05 00:53:49 +0000636 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000637 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000638 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000639 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000640 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000641 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000642
John McCalle4f26e52010-08-19 00:20:19 +0000643 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000644 return DeduceTemplateArguments(S, TemplateParams,
645 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000646 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000647 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000648 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000649
650 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000651 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000652 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000653 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000654 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000655 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000656
657 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000658 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000659 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000660 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000661
John McCalle4f26e52010-08-19 00:20:19 +0000662 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000663 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000664 ConstantArrayParm->getElementType(),
665 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000666 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000667 }
668
Douglas Gregor199d9912009-06-05 00:53:49 +0000669 // type [i]
670 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000671 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000672 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000673 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000674
John McCalle4f26e52010-08-19 00:20:19 +0000675 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
676
Douglas Gregor199d9912009-06-05 00:53:49 +0000677 // Check the element type of the arrays
678 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000679 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000680 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000681 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000682 DependentArrayParm->getElementType(),
683 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000684 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000685 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Douglas Gregor199d9912009-06-05 00:53:49 +0000687 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000688 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000689 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
690 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000691 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000692
693 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000694 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000695 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000696 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000697 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000698 = dyn_cast<ConstantArrayType>(ArrayArg)) {
699 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000700 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
701 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000702 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000703 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000704 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000705 if (const DependentSizedArrayType *DependentArrayArg
706 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000707 if (DependentArrayArg->getSizeExpr())
708 return DeduceNonTypeTemplateArgument(S, NTTP,
709 DependentArrayArg->getSizeExpr(),
710 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Douglas Gregor199d9912009-06-05 00:53:49 +0000712 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000713 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000714 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
716 // type(*)(T)
717 // T(*)()
718 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000719 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000720 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000721 dyn_cast<FunctionProtoType>(Arg);
722 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000723 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000724
725 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000726 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000727
Mike Stump1eb44332009-09-09 15:08:12 +0000728 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000729 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000730 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000732 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000733 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000735 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000736 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000737
Anders Carlssona27fad52009-06-08 15:19:08 +0000738 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000739 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000740 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000741 FunctionProtoParam->getResultType(),
742 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000743 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000744 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Anders Carlssona27fad52009-06-08 15:19:08 +0000746 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
747 // Check argument types.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000748 // FIXME: Variadic templates.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000749 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000750 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000751 FunctionProtoParam->getArgType(I),
752 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000753 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000754 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Douglas Gregorf67875d2009-06-12 18:26:56 +0000757 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
John McCall3cb0ebd2010-03-10 03:28:59 +0000760 case Type::InjectedClassName: {
761 // Treat a template's injected-class-name as if the template
762 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000763 Param = cast<InjectedClassNameType>(Param)
764 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000765 assert(isa<TemplateSpecializationType>(Param) &&
766 "injected class name is not a template specialization type");
767 // fall through
768 }
769
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000770 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000771 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000772 // TT<T>
773 // TT<i>
774 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000775 case Type::TemplateSpecialization: {
776 const TemplateSpecializationType *SpecParam
777 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000779 // Try to deduce template arguments from the template-id.
780 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000781 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000782 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Douglas Gregor4a5c15f2009-09-30 22:13:51 +0000784 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000785 // C++ [temp.deduct.call]p3b3:
786 // If P is a class, and P has the form template-id, then A can be a
787 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +0000788 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000789 // class pointed to by the deduced A.
790 //
791 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +0000792 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000793 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000794 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
795 // We cannot inspect base classes as part of deduction when the type
796 // is incomplete, so either instantiate any templates necessary to
797 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +0000798 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000799 return Result;
800
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000801 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000802 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000803 // ToVisit is our stack of records that we still need to visit.
804 llvm::SmallPtrSet<const RecordType *, 8> Visited;
805 llvm::SmallVector<const RecordType *, 8> ToVisit;
806 ToVisit.push_back(RecordT);
807 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +0000808 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
809 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000810 while (!ToVisit.empty()) {
811 // Retrieve the next class in the inheritance hierarchy.
812 const RecordType *NextT = ToVisit.back();
813 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000815 // If we have already seen this type, skip it.
816 if (!Visited.insert(NextT))
817 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000819 // If this is a base class, try to perform template argument
820 // deduction from it.
821 if (NextT != RecordT) {
822 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000823 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000824 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000826 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +0000827 // note that we had some success. Otherwise, ignore any deductions
828 // from this base class.
829 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000830 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +0000831 DeducedOrig = Deduced;
832 }
833 else
834 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000835 }
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000837 // Visit base classes
838 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
839 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
840 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +0000841 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000842 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000843 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +0000844 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000845 }
846 }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000848 if (Successful)
849 return Sema::TDK_Success;
850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000852 }
Mike Stump1eb44332009-09-09 15:08:12 +0000853
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000854 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000855 }
856
Douglas Gregor637a4092009-06-10 23:47:09 +0000857 // T type::*
858 // T T::*
859 // T (type::*)()
860 // type (T::*)()
861 // type (type::*)(T)
862 // type (T::*)(T)
863 // T (type::*)(T)
864 // T (T::*)()
865 // T (T::*)(T)
866 case Type::MemberPointer: {
867 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
868 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
869 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000870 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000871
Douglas Gregorf67875d2009-06-12 18:26:56 +0000872 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000873 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000874 MemPtrParam->getPointeeType(),
875 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000876 Info, Deduced,
877 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000878 return Result;
879
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000880 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000881 QualType(MemPtrParam->getClass(), 0),
882 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000883 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000884 }
885
Anders Carlsson9a917e42009-06-12 22:56:54 +0000886 // (clang extension)
887 //
Mike Stump1eb44332009-09-09 15:08:12 +0000888 // type(^)(T)
889 // T(^)()
890 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +0000891 case Type::BlockPointer: {
892 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
893 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Anders Carlsson859ba502009-06-12 16:23:10 +0000895 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000896 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000898 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000899 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000900 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000901 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000902 }
903
Douglas Gregor637a4092009-06-10 23:47:09 +0000904 case Type::TypeOfExpr:
905 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +0000906 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +0000907 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000908 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000909
Douglas Gregord560d502009-06-04 00:21:18 +0000910 default:
911 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000912 }
913
914 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000915 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000916}
917
Douglas Gregorf67875d2009-06-12 18:26:56 +0000918static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000919DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000920 TemplateParameterList *TemplateParams,
921 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000922 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000923 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000924 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000925 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000926 case TemplateArgument::Null:
927 assert(false && "Null template argument in parameter list");
928 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000929
930 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +0000931 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000932 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000933 Arg.getAsType(), Info, Deduced, 0);
934 Info.FirstArg = Param;
935 Info.SecondArg = Arg;
936 return Sema::TDK_NonDeducedMismatch;
937
938 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000939 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000940 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +0000941 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000942 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +0000943 Info.FirstArg = Param;
944 Info.SecondArg = Arg;
945 return Sema::TDK_NonDeducedMismatch;
946
Douglas Gregor199d9912009-06-05 00:53:49 +0000947 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +0000948 if (Arg.getKind() == TemplateArgument::Declaration &&
949 Param.getAsDecl()->getCanonicalDecl() ==
950 Arg.getAsDecl()->getCanonicalDecl())
951 return Sema::TDK_Success;
952
Douglas Gregorf67875d2009-06-12 18:26:56 +0000953 Info.FirstArg = Param;
954 Info.SecondArg = Arg;
955 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Douglas Gregor199d9912009-06-05 00:53:49 +0000957 case TemplateArgument::Integral:
958 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000959 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000960 return Sema::TDK_Success;
961
962 Info.FirstArg = Param;
963 Info.SecondArg = Arg;
964 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000965 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000966
967 if (Arg.getKind() == TemplateArgument::Expression) {
968 Info.FirstArg = Param;
969 Info.SecondArg = Arg;
970 return Sema::TDK_NonDeducedMismatch;
971 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000972
Douglas Gregorf67875d2009-06-12 18:26:56 +0000973 Info.FirstArg = Param;
974 Info.SecondArg = Arg;
975 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Douglas Gregor199d9912009-06-05 00:53:49 +0000977 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +0000978 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000979 = getDeducedParameterFromExpr(Param.getAsExpr())) {
980 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000981 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +0000982 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000983 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000984 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000985 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000986 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000987 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000988 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +0000989 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000990 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +0000991 Info, Deduced);
992
Douglas Gregorf67875d2009-06-12 18:26:56 +0000993 Info.FirstArg = Param;
994 Info.SecondArg = Arg;
995 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000996 }
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Douglas Gregor199d9912009-06-05 00:53:49 +0000998 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000999 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001000 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001001 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001002 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001003 }
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Douglas Gregorf67875d2009-06-12 18:26:56 +00001005 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001006}
1007
Douglas Gregor20a55e22010-12-22 18:17:10 +00001008/// \brief Determine whether there is a template argument to be used for
1009/// deduction.
1010///
1011/// This routine "expands" argument packs in-place, overriding its input
1012/// parameters so that \c Args[ArgIdx] will be the available template argument.
1013///
1014/// \returns true if there is another template argument (which will be at
1015/// \c Args[ArgIdx]), false otherwise.
1016static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1017 unsigned &ArgIdx,
1018 unsigned &NumArgs) {
1019 if (ArgIdx == NumArgs)
1020 return false;
1021
1022 const TemplateArgument &Arg = Args[ArgIdx];
1023 if (Arg.getKind() != TemplateArgument::Pack)
1024 return true;
1025
1026 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1027 Args = Arg.pack_begin();
1028 NumArgs = Arg.pack_size();
1029 ArgIdx = 0;
1030 return ArgIdx < NumArgs;
1031}
1032
Douglas Gregore02e2622010-12-22 21:19:48 +00001033/// \brief Retrieve the depth and index of an unexpanded parameter pack.
1034static std::pair<unsigned, unsigned>
1035getDepthAndIndex(UnexpandedParameterPack UPP) {
1036 if (const TemplateTypeParmType *TTP
1037 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
1038 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1039
Douglas Gregor6e4e17d2010-12-24 00:35:52 +00001040 NamedDecl *ND = UPP.first.get<NamedDecl *>();
1041 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
Douglas Gregore02e2622010-12-22 21:19:48 +00001042 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1043
Douglas Gregor6e4e17d2010-12-24 00:35:52 +00001044 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
Douglas Gregore02e2622010-12-22 21:19:48 +00001045 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
1046
Douglas Gregor6e4e17d2010-12-24 00:35:52 +00001047 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
Douglas Gregore02e2622010-12-22 21:19:48 +00001048 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1049}
1050
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001051/// \brief Helper function to build a TemplateParameter when we don't
1052/// know its type statically.
1053static TemplateParameter makeTemplateParameter(Decl *D) {
1054 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
1055 return TemplateParameter(TTP);
1056 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
1057 return TemplateParameter(NTTP);
1058
1059 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
1060}
1061
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001062/// \brief Determine whether the given set of template arguments has a pack
1063/// expansion that is not the last template argument.
1064static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1065 unsigned NumArgs) {
1066 unsigned ArgIdx = 0;
1067 while (ArgIdx < NumArgs) {
1068 const TemplateArgument &Arg = Args[ArgIdx];
1069
1070 // Unwrap argument packs.
1071 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1072 Args = Arg.pack_begin();
1073 NumArgs = Arg.pack_size();
1074 ArgIdx = 0;
1075 continue;
1076 }
1077
1078 ++ArgIdx;
1079 if (ArgIdx == NumArgs)
1080 return false;
1081
1082 if (Arg.isPackExpansion())
1083 return true;
1084 }
1085
1086 return false;
1087}
1088
Douglas Gregor20a55e22010-12-22 18:17:10 +00001089static Sema::TemplateDeductionResult
1090DeduceTemplateArguments(Sema &S,
1091 TemplateParameterList *TemplateParams,
1092 const TemplateArgument *Params, unsigned NumParams,
1093 const TemplateArgument *Args, unsigned NumArgs,
1094 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001095 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1096 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001097 // C++0x [temp.deduct.type]p9:
1098 // If the template argument list of P contains a pack expansion that is not
1099 // the last template argument, the entire template argument list is a
1100 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001101 if (hasPackExpansionBeforeEnd(Params, NumParams))
1102 return Sema::TDK_Success;
1103
Douglas Gregore02e2622010-12-22 21:19:48 +00001104 // C++0x [temp.deduct.type]p9:
1105 // If P has a form that contains <T> or <i>, then each argument Pi of the
1106 // respective template argument list P is compared with the corresponding
1107 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001108 unsigned ArgIdx = 0, ParamIdx = 0;
1109 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1110 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001111 // FIXME: Variadic templates.
1112 // What do we do if the argument is a pack expansion?
1113
Douglas Gregor20a55e22010-12-22 18:17:10 +00001114 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001115 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001116
1117 // Check whether we have enough arguments.
1118 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001119 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1120 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001121
Douglas Gregore02e2622010-12-22 21:19:48 +00001122 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001123 if (Sema::TemplateDeductionResult Result
1124 = DeduceTemplateArguments(S, TemplateParams,
1125 Params[ParamIdx], Args[ArgIdx],
1126 Info, Deduced))
1127 return Result;
1128
1129 // Move to the next argument.
1130 ++ArgIdx;
1131 continue;
1132 }
1133
Douglas Gregore02e2622010-12-22 21:19:48 +00001134 // The parameter is a pack expansion.
1135
1136 // C++0x [temp.deduct.type]p9:
1137 // If Pi is a pack expansion, then the pattern of Pi is compared with
1138 // each remaining argument in the template argument list of A. Each
1139 // comparison deduces template arguments for subsequent positions in the
1140 // template parameter packs expanded by Pi.
1141 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1142
1143 // Compute the set of template parameter indices that correspond to
1144 // parameter packs expanded by the pack expansion.
1145 llvm::SmallVector<unsigned, 2> PackIndices;
1146 {
1147 llvm::BitVector SawIndices(TemplateParams->size());
1148 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1149 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1150 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1151 unsigned Depth, Index;
1152 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1153 if (Depth == 0 && !SawIndices[Index]) {
1154 SawIndices[Index] = true;
1155 PackIndices.push_back(Index);
1156 }
1157 }
1158 }
1159 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1160
1161 // FIXME: If there are no remaining arguments, we can bail out early
1162 // and set any deduced parameter packs to an empty argument pack.
1163 // The latter part of this is a (minor) correctness issue.
1164
1165 // Save the deduced template arguments for each parameter pack expanded
1166 // by this pack expansion, then clear out the deduction.
1167 llvm::SmallVector<DeducedTemplateArgument, 2>
1168 SavedPacks(PackIndices.size());
1169 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1170 SavedPacks[I] = Deduced[PackIndices[I]];
1171 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1172 }
1173
1174 // Keep track of the deduced template arguments for each parameter pack
1175 // expanded by this pack expansion (the outer index) and for each
1176 // template argument (the inner SmallVectors).
1177 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1178 NewlyDeducedPacks(PackIndices.size());
1179 bool HasAnyArguments = false;
1180 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1181 HasAnyArguments = true;
1182
1183 // Deduce template arguments from the pattern.
1184 if (Sema::TemplateDeductionResult Result
1185 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1186 Info, Deduced))
1187 return Result;
1188
1189 // Capture the deduced template arguments for each parameter pack expanded
1190 // by this pack expansion, add them to the list of arguments we've deduced
1191 // for that pack, then clear out the deduced argument.
1192 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1193 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1194 if (!DeducedArg.isNull()) {
1195 NewlyDeducedPacks[I].push_back(DeducedArg);
1196 DeducedArg = DeducedTemplateArgument();
1197 }
1198 }
1199
1200 ++ArgIdx;
1201 }
1202
1203 // Build argument packs for each of the parameter packs expanded by this
1204 // pack expansion.
1205 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1206 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1207 // We were not able to deduce anything for this parameter pack,
1208 // so just restore the saved argument pack.
1209 Deduced[PackIndices[I]] = SavedPacks[I];
1210 continue;
1211 }
1212
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001213 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001214
1215 if (NewlyDeducedPacks[I].empty()) {
1216 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001217 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1218 } else {
1219 TemplateArgument *ArgumentPack
1220 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1221 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1222 ArgumentPack);
1223 NewPack
1224 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001225 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001226 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1227 }
1228
1229 DeducedTemplateArgument Result
1230 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1231 if (Result.isNull()) {
1232 Info.Param
1233 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1234 Info.FirstArg = SavedPacks[I];
1235 Info.SecondArg = NewPack;
1236 return Sema::TDK_Inconsistent;
1237 }
1238
1239 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001240 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001241 }
1242
1243 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001244 if (NumberOfArgumentsMustMatch &&
1245 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001246 return Sema::TDK_TooManyArguments;
1247
1248 return Sema::TDK_Success;
1249}
1250
Mike Stump1eb44332009-09-09 15:08:12 +00001251static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001252DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001253 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001254 const TemplateArgumentList &ParamList,
1255 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001256 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001257 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001258 return DeduceTemplateArguments(S, TemplateParams,
1259 ParamList.data(), ParamList.size(),
1260 ArgList.data(), ArgList.size(),
1261 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001262}
1263
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001264/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001265static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001266 const TemplateArgument &X,
1267 const TemplateArgument &Y) {
1268 if (X.getKind() != Y.getKind())
1269 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001271 switch (X.getKind()) {
1272 case TemplateArgument::Null:
1273 assert(false && "Comparing NULL template argument");
1274 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001276 case TemplateArgument::Type:
1277 return Context.getCanonicalType(X.getAsType()) ==
1278 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001280 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001281 return X.getAsDecl()->getCanonicalDecl() ==
1282 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Douglas Gregor788cd062009-11-11 01:00:40 +00001284 case TemplateArgument::Template:
1285 return Context.getCanonicalTemplateName(X.getAsTemplate())
1286 .getAsVoidPointer() ==
1287 Context.getCanonicalTemplateName(Y.getAsTemplate())
1288 .getAsVoidPointer();
1289
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001290 case TemplateArgument::Integral:
1291 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Douglas Gregor788cd062009-11-11 01:00:40 +00001293 case TemplateArgument::Expression: {
1294 llvm::FoldingSetNodeID XID, YID;
1295 X.getAsExpr()->Profile(XID, Context, true);
1296 Y.getAsExpr()->Profile(YID, Context, true);
1297 return XID == YID;
1298 }
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001300 case TemplateArgument::Pack:
1301 if (X.pack_size() != Y.pack_size())
1302 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001303
1304 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1305 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001306 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001307 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001308 if (!isSameTemplateArg(Context, *XP, *YP))
1309 return false;
1310
1311 return true;
1312 }
1313
1314 return false;
1315}
1316
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001317/// \brief Allocate a TemplateArgumentLoc where all locations have
1318/// been initialized to the given location.
1319///
1320/// \param S The semantic analysis object.
1321///
1322/// \param The template argument we are producing template argument
1323/// location information for.
1324///
1325/// \param NTTPType For a declaration template argument, the type of
1326/// the non-type template parameter that corresponds to this template
1327/// argument.
1328///
1329/// \param Loc The source location to use for the resulting template
1330/// argument.
1331static TemplateArgumentLoc
1332getTrivialTemplateArgumentLoc(Sema &S,
1333 const TemplateArgument &Arg,
1334 QualType NTTPType,
1335 SourceLocation Loc) {
1336 switch (Arg.getKind()) {
1337 case TemplateArgument::Null:
1338 llvm_unreachable("Can't get a NULL template argument here");
1339 break;
1340
1341 case TemplateArgument::Type:
1342 return TemplateArgumentLoc(Arg,
1343 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1344
1345 case TemplateArgument::Declaration: {
1346 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001347 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001348 .takeAs<Expr>();
1349 return TemplateArgumentLoc(TemplateArgument(E), E);
1350 }
1351
1352 case TemplateArgument::Integral: {
1353 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001354 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001355 return TemplateArgumentLoc(TemplateArgument(E), E);
1356 }
1357
1358 case TemplateArgument::Template:
Douglas Gregorba68eca2011-01-05 17:40:24 +00001359 return TemplateArgumentLoc(Arg, SourceRange(), Loc,
1360 Arg.isPackExpansion()? Loc : SourceLocation());
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001361
1362 case TemplateArgument::Expression:
1363 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1364
1365 case TemplateArgument::Pack:
1366 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1367 }
1368
1369 return TemplateArgumentLoc();
1370}
1371
1372
1373/// \brief Convert the given deduced template argument and add it to the set of
1374/// fully-converted template arguments.
1375static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1376 DeducedTemplateArgument Arg,
1377 NamedDecl *Template,
1378 QualType NTTPType,
1379 TemplateDeductionInfo &Info,
1380 bool InFunctionTemplate,
1381 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1382 if (Arg.getKind() == TemplateArgument::Pack) {
1383 // This is a template argument pack, so check each of its arguments against
1384 // the template parameter.
1385 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1386 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
1387 PAEnd = Arg.pack_end();
1388 PA != PAEnd; ++PA) {
1389 DeducedTemplateArgument InnerArg(*PA);
1390 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1391 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1392 NTTPType, Info,
1393 InFunctionTemplate, PackedArgsBuilder))
1394 return true;
1395 }
1396
1397 // Create the resulting argument pack.
1398 TemplateArgument *PackedArgs = 0;
1399 if (!PackedArgsBuilder.empty()) {
1400 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1401 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1402 }
1403 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1404 return false;
1405 }
1406
1407 // Convert the deduced template argument into a template
1408 // argument that we can check, almost as if the user had written
1409 // the template argument explicitly.
1410 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1411 Info.getLocation());
1412
1413 // Check the template argument, converting it as necessary.
1414 return S.CheckTemplateArgument(Param, ArgLoc,
1415 Template,
1416 Template->getLocation(),
1417 Template->getSourceRange().getEnd(),
1418 Output,
1419 InFunctionTemplate
1420 ? (Arg.wasDeducedFromArrayBound()
1421 ? Sema::CTAK_DeducedFromArrayBound
1422 : Sema::CTAK_Deduced)
1423 : Sema::CTAK_Specified);
1424}
1425
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001426/// Complete template argument deduction for a class template partial
1427/// specialization.
1428static Sema::TemplateDeductionResult
1429FinishTemplateArgumentDeduction(Sema &S,
1430 ClassTemplatePartialSpecializationDecl *Partial,
1431 const TemplateArgumentList &TemplateArgs,
1432 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001433 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001434 // Trap errors.
1435 Sema::SFINAETrap Trap(S);
1436
1437 Sema::ContextRAII SavedContext(S, Partial);
1438
1439 // C++ [temp.deduct.type]p2:
1440 // [...] or if any template argument remains neither deduced nor
1441 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001442 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001443 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1444 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001445 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001446 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001447 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001448 return Sema::TDK_Incomplete;
1449 }
1450
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001451 // We have deduced this argument, so it still needs to be
1452 // checked and converted.
1453
1454 // First, for a non-type template parameter type that is
1455 // initialized by a declaration, we need the type of the
1456 // corresponding non-type template parameter.
1457 QualType NTTPType;
1458 if (NonTypeTemplateParmDecl *NTTP
1459 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1460 NTTPType = NTTP->getType();
1461
1462 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1463 Partial, NTTPType, Info, false,
1464 Builder)) {
1465 Info.Param = makeTemplateParameter(Param);
1466 // FIXME: These template arguments are temporary. Free them!
1467 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1468 Builder.size()));
1469 return Sema::TDK_SubstitutionFailure;
1470 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001471 }
1472
1473 // Form the template argument list from the deduced template arguments.
1474 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001475 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1476 Builder.size());
1477
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001478 Info.reset(DeducedArgumentList);
1479
1480 // Substitute the deduced template arguments into the template
1481 // arguments of the class template partial specialization, and
1482 // verify that the instantiated template arguments are both valid
1483 // and are equivalent to the template arguments originally provided
1484 // to the class template.
1485 // FIXME: Do we have to correct the types of deduced non-type template
1486 // arguments (in particular, integral non-type template arguments?).
John McCall2a7fb272010-08-25 05:32:35 +00001487 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001488 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1489 const TemplateArgumentLoc *PartialTemplateArgs
1490 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001491
1492 // Note that we don't provide the langle and rangle locations.
1493 TemplateArgumentListInfo InstArgs;
1494
Douglas Gregore02e2622010-12-22 21:19:48 +00001495 if (S.Subst(PartialTemplateArgs,
1496 Partial->getNumTemplateArgsAsWritten(),
1497 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1498 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1499 if (ParamIdx >= Partial->getTemplateParameters()->size())
1500 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1501
1502 Decl *Param
1503 = const_cast<NamedDecl *>(
1504 Partial->getTemplateParameters()->getParam(ParamIdx));
1505 Info.Param = makeTemplateParameter(Param);
1506 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1507 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001508 }
1509
Douglas Gregor910f8002010-11-07 23:05:16 +00001510 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001511 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001512 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001513 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001514
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001515 TemplateParameterList *TemplateParams
1516 = ClassTemplate->getTemplateParameters();
1517 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001518 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001519 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001520 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001521 Info.FirstArg = TemplateArgs[I];
1522 Info.SecondArg = InstArg;
1523 return Sema::TDK_NonDeducedMismatch;
1524 }
1525 }
1526
1527 if (Trap.hasErrorOccurred())
1528 return Sema::TDK_SubstitutionFailure;
1529
1530 return Sema::TDK_Success;
1531}
1532
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001533/// \brief Perform template argument deduction to determine whether
1534/// the given template arguments match the given class template
1535/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001536Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001537Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001538 const TemplateArgumentList &TemplateArgs,
1539 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001540 // C++ [temp.class.spec.match]p2:
1541 // A partial specialization matches a given actual template
1542 // argument list if the template arguments of the partial
1543 // specialization can be deduced from the actual template argument
1544 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001545 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001546 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001547 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001548 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001549 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001550 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001551 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001552 TemplateArgs, Info, Deduced))
1553 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001554
Douglas Gregor637a4092009-06-10 23:47:09 +00001555 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001556 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001557 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001558 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001559
Douglas Gregorbb260412009-06-14 08:02:22 +00001560 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001561 return Sema::TDK_SubstitutionFailure;
1562
1563 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1564 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001565}
Douglas Gregor031a5882009-06-13 00:26:55 +00001566
Douglas Gregor41128772009-06-26 23:27:24 +00001567/// \brief Determine whether the given type T is a simple-template-id type.
1568static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001569 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001570 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001571 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Douglas Gregor41128772009-06-26 23:27:24 +00001573 return false;
1574}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001575
1576/// \brief Substitute the explicitly-provided template arguments into the
1577/// given function template according to C++ [temp.arg.explicit].
1578///
1579/// \param FunctionTemplate the function template into which the explicit
1580/// template arguments will be substituted.
1581///
Mike Stump1eb44332009-09-09 15:08:12 +00001582/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001583/// arguments.
1584///
Mike Stump1eb44332009-09-09 15:08:12 +00001585/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001586/// with the converted and checked explicit template arguments.
1587///
Mike Stump1eb44332009-09-09 15:08:12 +00001588/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001589/// parameters.
1590///
1591/// \param FunctionType if non-NULL, the result type of the function template
1592/// will also be instantiated and the pointed-to value will be updated with
1593/// the instantiated function type.
1594///
1595/// \param Info if substitution fails for any reason, this object will be
1596/// populated with more information about the failure.
1597///
1598/// \returns TDK_Success if substitution was successful, or some failure
1599/// condition.
1600Sema::TemplateDeductionResult
1601Sema::SubstituteExplicitTemplateArguments(
1602 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001603 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001604 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001605 llvm::SmallVectorImpl<QualType> &ParamTypes,
1606 QualType *FunctionType,
1607 TemplateDeductionInfo &Info) {
1608 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1609 TemplateParameterList *TemplateParams
1610 = FunctionTemplate->getTemplateParameters();
1611
John McCalld5532b62009-11-23 01:53:49 +00001612 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001613 // No arguments to substitute; just copy over the parameter types and
1614 // fill in the function type.
1615 for (FunctionDecl::param_iterator P = Function->param_begin(),
1616 PEnd = Function->param_end();
1617 P != PEnd;
1618 ++P)
1619 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Douglas Gregor83314aa2009-07-08 20:55:45 +00001621 if (FunctionType)
1622 *FunctionType = Function->getType();
1623 return TDK_Success;
1624 }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Douglas Gregor83314aa2009-07-08 20:55:45 +00001626 // Substitution of the explicit template arguments into a function template
1627 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001628 SFINAETrap Trap(*this);
1629
Douglas Gregor83314aa2009-07-08 20:55:45 +00001630 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001631 // Template arguments that are present shall be specified in the
1632 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001633 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001634 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001635 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001636
1637 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001638 // explicitly-specified template arguments against this function template,
1639 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001640 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001641 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001642 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1643 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001644 if (Inst)
1645 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Douglas Gregor83314aa2009-07-08 20:55:45 +00001647 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001648 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001649 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001650 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001651 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001652 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001653 if (Index >= TemplateParams->size())
1654 Index = TemplateParams->size() - 1;
1655 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001656 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001657 }
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Douglas Gregor83314aa2009-07-08 20:55:45 +00001659 // Form the template argument list from the explicitly-specified
1660 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001661 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001662 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001663 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001664
John McCalldf41f182010-10-12 19:40:14 +00001665 // Template argument deduction and the final substitution should be
1666 // done in the context of the templated declaration. Explicit
1667 // argument substitution, on the other hand, needs to happen in the
1668 // calling context.
1669 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1670
Douglas Gregor83314aa2009-07-08 20:55:45 +00001671 // Instantiate the types of each of the function parameters given the
1672 // explicitly-specified template arguments.
1673 for (FunctionDecl::param_iterator P = Function->param_begin(),
1674 PEnd = Function->param_end();
1675 P != PEnd;
1676 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001677 QualType ParamType
1678 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001679 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1680 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001681 if (ParamType.isNull() || Trap.hasErrorOccurred())
1682 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001683
Douglas Gregor83314aa2009-07-08 20:55:45 +00001684 ParamTypes.push_back(ParamType);
1685 }
1686
1687 // If the caller wants a full function type back, instantiate the return
1688 // type and form that function type.
1689 if (FunctionType) {
1690 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001691 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001692 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001693 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001694
1695 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001696 = SubstType(Proto->getResultType(),
1697 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1698 Function->getTypeSpecStartLoc(),
1699 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001700 if (ResultType.isNull() || Trap.hasErrorOccurred())
1701 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001702
1703 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001704 ParamTypes.data(), ParamTypes.size(),
1705 Proto->isVariadic(),
1706 Proto->getTypeQuals(),
1707 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001708 Function->getDeclName(),
1709 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001710 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1711 return TDK_SubstitutionFailure;
1712 }
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Douglas Gregor83314aa2009-07-08 20:55:45 +00001714 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001715 // Trailing template arguments that can be deduced (14.8.2) may be
1716 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001717 // template arguments can be deduced, they may all be omitted; in this
1718 // case, the empty template argument list <> itself may also be omitted.
1719 //
1720 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001721 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001722 Deduced.reserve(TemplateParams->size());
1723 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001724 Deduced.push_back(ExplicitArgumentList->get(I));
1725
Douglas Gregor83314aa2009-07-08 20:55:45 +00001726 return TDK_Success;
1727}
1728
Mike Stump1eb44332009-09-09 15:08:12 +00001729/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001730/// checking the deduced template arguments for completeness and forming
1731/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001732Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001733Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001734 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1735 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001736 FunctionDecl *&Specialization,
1737 TemplateDeductionInfo &Info) {
1738 TemplateParameterList *TemplateParams
1739 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Douglas Gregor83314aa2009-07-08 20:55:45 +00001741 // Template argument deduction for function templates in a SFINAE context.
1742 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001743 SFINAETrap Trap(*this);
1744
Douglas Gregor83314aa2009-07-08 20:55:45 +00001745 // Enter a new template instantiation context while we instantiate the
1746 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001747 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001748 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001749 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1750 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001751 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001752 return TDK_InstantiationDepth;
1753
John McCall96db3102010-04-29 01:18:58 +00001754 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001755
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001756 // C++ [temp.deduct.type]p2:
1757 // [...] or if any template argument remains neither deduced nor
1758 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001759 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001760 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
1761 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001762
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001763 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001764 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001765 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001766 // argument, because it was explicitly-specified. Just record the
1767 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001768 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001769 continue;
1770 }
1771
1772 // We have deduced this argument, so it still needs to be
1773 // checked and converted.
1774
1775 // First, for a non-type template parameter type that is
1776 // initialized by a declaration, we need the type of the
1777 // corresponding non-type template parameter.
1778 QualType NTTPType;
1779 if (NonTypeTemplateParmDecl *NTTP
1780 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001781 NTTPType = NTTP->getType();
1782 if (NTTPType->isDependentType()) {
1783 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1784 Builder.data(), Builder.size());
1785 NTTPType = SubstType(NTTPType,
1786 MultiLevelTemplateArgumentList(TemplateArgs),
1787 NTTP->getLocation(),
1788 NTTP->getDeclName());
1789 if (NTTPType.isNull()) {
1790 Info.Param = makeTemplateParameter(Param);
1791 // FIXME: These template arguments are temporary. Free them!
1792 Info.reset(TemplateArgumentList::CreateCopy(Context,
1793 Builder.data(),
1794 Builder.size()));
1795 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00001796 }
1797 }
1798 }
1799
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001800 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
1801 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001802 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001803 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00001804 // FIXME: These template arguments are temporary. Free them!
1805 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001806 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001807 return TDK_SubstitutionFailure;
1808 }
1809
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001810 continue;
1811 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001812
1813 // C++0x [temp.arg.explicit]p3:
1814 // A trailing template parameter pack (14.5.3) not otherwise deduced will
1815 // be deduced to an empty sequence of template arguments.
1816 // FIXME: Where did the word "trailing" come from?
1817 if (Param->isTemplateParameterPack()) {
1818 Builder.push_back(TemplateArgument(0, 0));
1819 continue;
1820 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001821
1822 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001823 TemplateArgumentLoc DefArg
1824 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1825 FunctionTemplate->getLocation(),
1826 FunctionTemplate->getSourceRange().getEnd(),
1827 Param,
1828 Builder);
1829
1830 // If there was no default argument, deduction is incomplete.
1831 if (DefArg.getArgument().isNull()) {
1832 Info.Param = makeTemplateParameter(
1833 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1834 return TDK_Incomplete;
1835 }
1836
1837 // Check whether we can actually use the default argument.
1838 if (CheckTemplateArgument(Param, DefArg,
1839 FunctionTemplate,
1840 FunctionTemplate->getLocation(),
1841 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001842 Builder,
1843 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001844 Info.Param = makeTemplateParameter(
1845 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001846 // FIXME: These template arguments are temporary. Free them!
1847 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1848 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001849 return TDK_SubstitutionFailure;
1850 }
1851
1852 // If we get here, we successfully used the default template argument.
1853 }
1854
1855 // Form the template argument list from the deduced template arguments.
1856 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001857 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001858 Info.reset(DeducedArgumentList);
1859
Mike Stump1eb44332009-09-09 15:08:12 +00001860 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001861 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00001862 DeclContext *Owner = FunctionTemplate->getDeclContext();
1863 if (FunctionTemplate->getFriendObjectKind())
1864 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001865 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00001866 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00001867 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001868 if (!Specialization)
1869 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Douglas Gregorf8825742009-09-15 18:26:13 +00001871 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1872 FunctionTemplate->getCanonicalDecl());
1873
Mike Stump1eb44332009-09-09 15:08:12 +00001874 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001875 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00001876 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
1877 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00001878 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Douglas Gregor83314aa2009-07-08 20:55:45 +00001880 // There may have been an error that did not prevent us from constructing a
1881 // declaration. Mark the declaration invalid and return with a substitution
1882 // failure.
1883 if (Trap.hasErrorOccurred()) {
1884 Specialization->setInvalidDecl(true);
1885 return TDK_SubstitutionFailure;
1886 }
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Douglas Gregor9b623632010-10-12 23:32:35 +00001888 // If we suppressed any diagnostics while performing template argument
1889 // deduction, and if we haven't already instantiated this declaration,
1890 // keep track of these diagnostics. They'll be emitted if this specialization
1891 // is actually used.
1892 if (Info.diag_begin() != Info.diag_end()) {
1893 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
1894 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
1895 if (Pos == SuppressedDiagnostics.end())
1896 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
1897 .append(Info.diag_begin(), Info.diag_end());
1898 }
1899
Mike Stump1eb44332009-09-09 15:08:12 +00001900 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001901}
1902
John McCall9c72c602010-08-27 09:08:28 +00001903/// Gets the type of a function for template-argument-deducton
1904/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00001905static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00001906 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00001907 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00001908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00001909 if (Method->isInstance()) {
1910 // An instance method that's referenced in a form that doesn't
1911 // look like a member pointer is just invalid.
1912 if (!R.HasFormOfMemberPointer) return QualType();
1913
John McCalleff92132010-02-02 02:21:27 +00001914 return Context.getMemberPointerType(Fn->getType(),
1915 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00001916 }
1917
1918 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00001919 return Context.getPointerType(Fn->getType());
1920}
1921
1922/// Apply the deduction rules for overload sets.
1923///
1924/// \return the null type if this argument should be treated as an
1925/// undeduced context
1926static QualType
1927ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001928 Expr *Arg, QualType ParamType,
1929 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00001930
1931 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00001932
John McCall9c72c602010-08-27 09:08:28 +00001933 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00001934
Douglas Gregor75f21af2010-08-30 21:04:23 +00001935 // C++0x [temp.deduct.call]p4
1936 unsigned TDF = 0;
1937 if (ParamWasReference)
1938 TDF |= TDF_ParamWithReferenceType;
1939 if (R.IsAddressOfOperand)
1940 TDF |= TDF_IgnoreQualifiers;
1941
John McCalleff92132010-02-02 02:21:27 +00001942 // If there were explicit template arguments, we can only find
1943 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1944 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00001945 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00001946 // But we can still look for an explicit specialization.
1947 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00001948 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00001949 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00001950 return QualType();
1951 }
1952
1953 // C++0x [temp.deduct.call]p6:
1954 // When P is a function type, pointer to function type, or pointer
1955 // to member function type:
1956
1957 if (!ParamType->isFunctionType() &&
1958 !ParamType->isFunctionPointerType() &&
1959 !ParamType->isMemberFunctionPointerType())
1960 return QualType();
1961
1962 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00001963 for (UnresolvedSetIterator I = Ovl->decls_begin(),
1964 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00001965 NamedDecl *D = (*I)->getUnderlyingDecl();
1966
1967 // - If the argument is an overload set containing one or more
1968 // function templates, the parameter is treated as a
1969 // non-deduced context.
1970 if (isa<FunctionTemplateDecl>(D))
1971 return QualType();
1972
1973 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00001974 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
1975 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00001976
Douglas Gregor75f21af2010-08-30 21:04:23 +00001977 // Function-to-pointer conversion.
1978 if (!ParamWasReference && ParamType->isPointerType() &&
1979 ArgType->isFunctionType())
1980 ArgType = S.Context.getPointerType(ArgType);
1981
John McCalleff92132010-02-02 02:21:27 +00001982 // - If the argument is an overload set (not containing function
1983 // templates), trial argument deduction is attempted using each
1984 // of the members of the set. If deduction succeeds for only one
1985 // of the overload set members, that member is used as the
1986 // argument value for the deduction. If deduction succeeds for
1987 // more than one member of the overload set the parameter is
1988 // treated as a non-deduced context.
1989
1990 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
1991 // Type deduction is done independently for each P/A pair, and
1992 // the deduced template argument values are then combined.
1993 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00001994 llvm::SmallVector<DeducedTemplateArgument, 8>
1995 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00001996 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00001997 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001998 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00001999 ParamType, ArgType,
2000 Info, Deduced, TDF);
2001 if (Result) continue;
2002 if (!Match.isNull()) return QualType();
2003 Match = ArgType;
2004 }
2005
2006 return Match;
2007}
2008
Douglas Gregore53060f2009-06-25 22:08:12 +00002009/// \brief Perform template argument deduction from a function call
2010/// (C++ [temp.deduct.call]).
2011///
2012/// \param FunctionTemplate the function template for which we are performing
2013/// template argument deduction.
2014///
Douglas Gregor48026d22010-01-11 18:40:55 +00002015/// \param ExplicitTemplateArguments the explicit template arguments provided
2016/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002017///
Douglas Gregore53060f2009-06-25 22:08:12 +00002018/// \param Args the function call arguments
2019///
2020/// \param NumArgs the number of arguments in Args
2021///
Douglas Gregor48026d22010-01-11 18:40:55 +00002022/// \param Name the name of the function being called. This is only significant
2023/// when the function template is a conversion function template, in which
2024/// case this routine will also perform template argument deduction based on
2025/// the function to which
2026///
Douglas Gregore53060f2009-06-25 22:08:12 +00002027/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002028/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002029/// template argument deduction.
2030///
2031/// \param Info the argument will be updated to provide additional information
2032/// about template argument deduction.
2033///
2034/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002035Sema::TemplateDeductionResult
2036Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002037 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002038 Expr **Args, unsigned NumArgs,
2039 FunctionDecl *&Specialization,
2040 TemplateDeductionInfo &Info) {
2041 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002042
Douglas Gregore53060f2009-06-25 22:08:12 +00002043 // C++ [temp.deduct.call]p1:
2044 // Template argument deduction is done by comparing each function template
2045 // parameter type (call it P) with the type of the corresponding argument
2046 // of the call (call it A) as described below.
2047 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002048 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002049 return TDK_TooFewArguments;
2050 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002051 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002052 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregore53060f2009-06-25 22:08:12 +00002053 if (!Proto->isVariadic())
2054 return TDK_TooManyArguments;
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Douglas Gregore53060f2009-06-25 22:08:12 +00002056 CheckArgs = Function->getNumParams();
2057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002059 // The types of the parameters from which we will perform template argument
2060 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002061 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002062 TemplateParameterList *TemplateParams
2063 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002064 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002065 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002066 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002067 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002068 TemplateDeductionResult Result =
2069 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002070 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002071 Deduced,
2072 ParamTypes,
2073 0,
2074 Info);
2075 if (Result)
2076 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002077
2078 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002079 } else {
2080 // Just fill in the parameter types from the function declaration.
2081 for (unsigned I = 0; I != CheckArgs; ++I)
2082 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2083 }
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002085 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002086 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00002087 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002088 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00002089 QualType ArgType = Args[I]->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregor75f21af2010-08-30 21:04:23 +00002091 // C++0x [temp.deduct.call]p3:
2092 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2093 // are ignored for type deduction.
2094 if (ParamType.getCVRQualifiers())
2095 ParamType = ParamType.getLocalUnqualifiedType();
2096 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2097 if (ParamRefType) {
2098 // [...] If P is a reference type, the type referred to by P is used
2099 // for type deduction.
2100 ParamType = ParamRefType->getPointeeType();
2101 }
2102
John McCalleff92132010-02-02 02:21:27 +00002103 // Overload sets usually make this parameter an undeduced
2104 // context, but there are sometimes special circumstances.
2105 if (ArgType == Context.OverloadTy) {
2106 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002107 Args[I], ParamType,
2108 ParamRefType != 0);
John McCalleff92132010-02-02 02:21:27 +00002109 if (ArgType.isNull())
2110 continue;
2111 }
2112
Douglas Gregor75f21af2010-08-30 21:04:23 +00002113 if (ParamRefType) {
2114 // C++0x [temp.deduct.call]p3:
2115 // [...] If P is of the form T&&, where T is a template parameter, and
2116 // the argument is an lvalue, the type A& is used in place of A for
2117 // type deduction.
2118 if (ParamRefType->isRValueReferenceType() &&
2119 ParamRefType->getAs<TemplateTypeParmType>() &&
John McCall7eb0a9e2010-11-24 05:12:34 +00002120 Args[I]->isLValue())
Douglas Gregor75f21af2010-08-30 21:04:23 +00002121 ArgType = Context.getLValueReferenceType(ArgType);
2122 } else {
2123 // C++ [temp.deduct.call]p2:
2124 // If P is not a reference type:
Mike Stump1eb44332009-09-09 15:08:12 +00002125 // - If A is an array type, the pointer type produced by the
2126 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregore53060f2009-06-25 22:08:12 +00002127 // A for type deduction; otherwise,
2128 if (ArgType->isArrayType())
2129 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00002130 // - If A is a function type, the pointer type produced by the
2131 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregore53060f2009-06-25 22:08:12 +00002132 // of A for type deduction; otherwise,
2133 else if (ArgType->isFunctionType())
2134 ArgType = Context.getPointerType(ArgType);
2135 else {
2136 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2137 // type are ignored for type deduction.
2138 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor75f21af2010-08-30 21:04:23 +00002139 if (ArgType.getCVRQualifiers())
2140 ArgType = ArgType.getUnqualifiedType();
Douglas Gregore53060f2009-06-25 22:08:12 +00002141 }
2142 }
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Douglas Gregore53060f2009-06-25 22:08:12 +00002144 // C++0x [temp.deduct.call]p4:
2145 // In general, the deduction process attempts to find template argument
2146 // values that will make the deduced A identical to A (after the type A
2147 // is transformed as described above). [...]
Douglas Gregor12820292009-09-14 20:00:47 +00002148 unsigned TDF = TDF_SkipNonDependent;
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Douglas Gregor508f1c82009-06-26 23:10:12 +00002150 // - If the original P is a reference type, the deduced A (i.e., the
2151 // type referred to by the reference) can be more cv-qualified than
2152 // the transformed A.
Douglas Gregor75f21af2010-08-30 21:04:23 +00002153 if (ParamRefType)
Douglas Gregor508f1c82009-06-26 23:10:12 +00002154 TDF |= TDF_ParamWithReferenceType;
Mike Stump1eb44332009-09-09 15:08:12 +00002155 // - The transformed A can be another pointer or pointer to member
2156 // type that can be converted to the deduced A via a qualification
Douglas Gregor508f1c82009-06-26 23:10:12 +00002157 // conversion (4.4).
John McCalldb0bc472010-08-05 05:30:45 +00002158 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2159 ArgType->isObjCObjectPointerType())
Douglas Gregor508f1c82009-06-26 23:10:12 +00002160 TDF |= TDF_IgnoreQualifiers;
Mike Stump1eb44332009-09-09 15:08:12 +00002161 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor41128772009-06-26 23:27:24 +00002162 // transformed A can be a derived class of the deduced A. Likewise,
2163 // if P is a pointer to a class of the form simple-template-id, the
2164 // transformed A can be a pointer to a derived class pointed to by
2165 // the deduced A.
2166 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002167 (isa<PointerType>(ParamType) &&
Douglas Gregor41128772009-06-26 23:27:24 +00002168 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00002169 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00002170 TDF |= TDF_DerivedClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Douglas Gregore53060f2009-06-25 22:08:12 +00002172 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002173 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00002174 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00002175 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00002176 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002178 // FIXME: we need to check that the deduced A is the same as A,
2179 // modulo the various allowed differences.
Douglas Gregore53060f2009-06-25 22:08:12 +00002180 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002181
Mike Stump1eb44332009-09-09 15:08:12 +00002182 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002183 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002184 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002185}
2186
Douglas Gregor83314aa2009-07-08 20:55:45 +00002187/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002188/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2189/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002190///
2191/// \param FunctionTemplate the function template for which we are performing
2192/// template argument deduction.
2193///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002194/// \param ExplicitTemplateArguments the explicitly-specified template
2195/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002196///
2197/// \param ArgFunctionType the function type that will be used as the
2198/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002199/// function template's function type. This type may be NULL, if there is no
2200/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002201///
2202/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002203/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002204/// template argument deduction.
2205///
2206/// \param Info the argument will be updated to provide additional information
2207/// about template argument deduction.
2208///
2209/// \returns the result of template argument deduction.
2210Sema::TemplateDeductionResult
2211Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002212 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002213 QualType ArgFunctionType,
2214 FunctionDecl *&Specialization,
2215 TemplateDeductionInfo &Info) {
2216 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2217 TemplateParameterList *TemplateParams
2218 = FunctionTemplate->getTemplateParameters();
2219 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Douglas Gregor83314aa2009-07-08 20:55:45 +00002221 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002222 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002223 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2224 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002225 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002226 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002227 if (TemplateDeductionResult Result
2228 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002229 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002230 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002231 &FunctionType, Info))
2232 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002233
2234 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002235 }
2236
2237 // Template argument deduction for function templates in a SFINAE context.
2238 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002239 SFINAETrap Trap(*this);
2240
John McCalleff92132010-02-02 02:21:27 +00002241 Deduced.resize(TemplateParams->size());
2242
Douglas Gregor4b52e252009-12-21 23:17:24 +00002243 if (!ArgFunctionType.isNull()) {
2244 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002245 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002246 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002247 FunctionType, ArgFunctionType, Info,
2248 Deduced, 0))
2249 return Result;
2250 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002251
2252 if (TemplateDeductionResult Result
2253 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2254 NumExplicitlySpecified,
2255 Specialization, Info))
2256 return Result;
2257
2258 // If the requested function type does not match the actual type of the
2259 // specialization, template argument deduction fails.
2260 if (!ArgFunctionType.isNull() &&
2261 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2262 return TDK_NonDeducedMismatch;
2263
2264 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002265}
2266
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002267/// \brief Deduce template arguments for a templated conversion
2268/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2269/// conversion function template specialization.
2270Sema::TemplateDeductionResult
2271Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2272 QualType ToType,
2273 CXXConversionDecl *&Specialization,
2274 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002275 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002276 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2277 QualType FromType = Conv->getConversionType();
2278
2279 // Canonicalize the types for deduction.
2280 QualType P = Context.getCanonicalType(FromType);
2281 QualType A = Context.getCanonicalType(ToType);
2282
2283 // C++0x [temp.deduct.conv]p3:
2284 // If P is a reference type, the type referred to by P is used for
2285 // type deduction.
2286 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2287 P = PRef->getPointeeType();
2288
2289 // C++0x [temp.deduct.conv]p3:
2290 // If A is a reference type, the type referred to by A is used
2291 // for type deduction.
2292 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2293 A = ARef->getPointeeType();
2294 // C++ [temp.deduct.conv]p2:
2295 //
Mike Stump1eb44332009-09-09 15:08:12 +00002296 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002297 else {
2298 assert(!A->isReferenceType() && "Reference types were handled above");
2299
2300 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002301 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002302 // of P for type deduction; otherwise,
2303 if (P->isArrayType())
2304 P = Context.getArrayDecayedType(P);
2305 // - If P is a function type, the pointer type produced by the
2306 // function-to-pointer standard conversion (4.3) is used in
2307 // place of P for type deduction; otherwise,
2308 else if (P->isFunctionType())
2309 P = Context.getPointerType(P);
2310 // - If P is a cv-qualified type, the top level cv-qualifiers of
2311 // P’s type are ignored for type deduction.
2312 else
2313 P = P.getUnqualifiedType();
2314
2315 // C++0x [temp.deduct.conv]p3:
2316 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2317 // type are ignored for type deduction.
2318 A = A.getUnqualifiedType();
2319 }
2320
2321 // Template argument deduction for function templates in a SFINAE context.
2322 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002323 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002324
2325 // C++ [temp.deduct.conv]p1:
2326 // Template argument deduction is done by comparing the return
2327 // type of the template conversion function (call it P) with the
2328 // type that is required as the result of the conversion (call it
2329 // A) as described in 14.8.2.4.
2330 TemplateParameterList *TemplateParams
2331 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002332 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002333 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002334
2335 // C++0x [temp.deduct.conv]p4:
2336 // In general, the deduction process attempts to find template
2337 // argument values that will make the deduced A identical to
2338 // A. However, there are two cases that allow a difference:
2339 unsigned TDF = 0;
2340 // - If the original A is a reference type, A can be more
2341 // cv-qualified than the deduced A (i.e., the type referred to
2342 // by the reference)
2343 if (ToType->isReferenceType())
2344 TDF |= TDF_ParamWithReferenceType;
2345 // - The deduced A can be another pointer or pointer to member
2346 // type that can be converted to A via a qualification
2347 // conversion.
2348 //
2349 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2350 // both P and A are pointers or member pointers. In this case, we
2351 // just ignore cv-qualifiers completely).
2352 if ((P->isPointerType() && A->isPointerType()) ||
2353 (P->isMemberPointerType() && P->isMemberPointerType()))
2354 TDF |= TDF_IgnoreQualifiers;
2355 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002356 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002357 P, A, Info, Deduced, TDF))
2358 return Result;
2359
2360 // FIXME: we need to check that the deduced A is the same as A,
2361 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002362
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002363 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002364 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002365 FunctionDecl *Spec = 0;
2366 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002367 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2368 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002369 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2370 return Result;
2371}
2372
Douglas Gregor4b52e252009-12-21 23:17:24 +00002373/// \brief Deduce template arguments for a function template when there is
2374/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2375///
2376/// \param FunctionTemplate the function template for which we are performing
2377/// template argument deduction.
2378///
2379/// \param ExplicitTemplateArguments the explicitly-specified template
2380/// arguments.
2381///
2382/// \param Specialization if template argument deduction was successful,
2383/// this will be set to the function template specialization produced by
2384/// template argument deduction.
2385///
2386/// \param Info the argument will be updated to provide additional information
2387/// about template argument deduction.
2388///
2389/// \returns the result of template argument deduction.
2390Sema::TemplateDeductionResult
2391Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2392 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2393 FunctionDecl *&Specialization,
2394 TemplateDeductionInfo &Info) {
2395 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2396 QualType(), Specialization, Info);
2397}
2398
Douglas Gregor8a514912009-09-14 18:39:43 +00002399/// \brief Stores the result of comparing the qualifiers of two types.
2400enum DeductionQualifierComparison {
2401 NeitherMoreQualified = 0,
2402 ParamMoreQualified,
2403 ArgMoreQualified
2404};
2405
2406/// \brief Deduce the template arguments during partial ordering by comparing
2407/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2408///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002409/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002410///
2411/// \param TemplateParams the template parameters that we are deducing
2412///
2413/// \param ParamIn the parameter type
2414///
2415/// \param ArgIn the argument type
2416///
2417/// \param Info information about the template argument deduction itself
2418///
2419/// \param Deduced the deduced template arguments
2420///
2421/// \returns the result of template argument deduction so far. Note that a
2422/// "success" result means that template argument deduction has not yet failed,
2423/// but it may still fail, later, for other reasons.
2424static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002425DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002426 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002427 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002428 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002429 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2430 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002431 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2432 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002433
2434 // C++0x [temp.deduct.partial]p5:
2435 // Before the partial ordering is done, certain transformations are
2436 // performed on the types used for partial ordering:
2437 // - If P is a reference type, P is replaced by the type referred to.
2438 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002439 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002440 Param = ParamRef->getPointeeType();
2441
2442 // - If A is a reference type, A is replaced by the type referred to.
2443 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002444 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002445 Arg = ArgRef->getPointeeType();
2446
John McCalle27ec8a2009-10-23 23:03:21 +00002447 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002448 // C++0x [temp.deduct.partial]p6:
2449 // If both P and A were reference types (before being replaced with the
2450 // type referred to above), determine which of the two types (if any) is
2451 // more cv-qualified than the other; otherwise the types are considered to
2452 // be equally cv-qualified for partial ordering purposes. The result of this
2453 // determination will be used below.
2454 //
2455 // We save this information for later, using it only when deduction
2456 // succeeds in both directions.
2457 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2458 if (Param.isMoreQualifiedThan(Arg))
2459 QualifierResult = ParamMoreQualified;
2460 else if (Arg.isMoreQualifiedThan(Param))
2461 QualifierResult = ArgMoreQualified;
2462 QualifierComparisons->push_back(QualifierResult);
2463 }
2464
2465 // C++0x [temp.deduct.partial]p7:
2466 // Remove any top-level cv-qualifiers:
2467 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2468 // version of P.
2469 Param = Param.getUnqualifiedType();
2470 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2471 // version of A.
2472 Arg = Arg.getUnqualifiedType();
2473
2474 // C++0x [temp.deduct.partial]p8:
2475 // Using the resulting types P and A the deduction is then done as
2476 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2477 // from the argument template is considered to be at least as specialized
2478 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002479 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002480 Deduced, TDF_None);
2481}
2482
2483static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002484MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2485 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002486 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002487 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002488
2489/// \brief If this is a non-static member function,
2490static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2491 CXXMethodDecl *Method,
2492 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2493 if (Method->isStatic())
2494 return;
2495
2496 // C++ [over.match.funcs]p4:
2497 //
2498 // For non-static member functions, the type of the implicit
2499 // object parameter is
2500 // — "lvalue reference to cv X" for functions declared without a
2501 // ref-qualifier or with the & ref-qualifier
2502 // - "rvalue reference to cv X" for functions declared with the
2503 // && ref-qualifier
2504 //
2505 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2506 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2507 ArgTy = Context.getQualifiedType(ArgTy,
2508 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2509 ArgTy = Context.getLValueReferenceType(ArgTy);
2510 ArgTypes.push_back(ArgTy);
2511}
2512
Douglas Gregor8a514912009-09-14 18:39:43 +00002513/// \brief Determine whether the function template \p FT1 is at least as
2514/// specialized as \p FT2.
2515static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002516 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002517 FunctionTemplateDecl *FT1,
2518 FunctionTemplateDecl *FT2,
2519 TemplatePartialOrderingContext TPOC,
2520 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2521 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2522 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2523 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2524 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2525
2526 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2527 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002528 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002529 Deduced.resize(TemplateParams->size());
2530
2531 // C++0x [temp.deduct.partial]p3:
2532 // The types used to determine the ordering depend on the context in which
2533 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002534 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002535 CXXMethodDecl *Method1 = 0;
2536 CXXMethodDecl *Method2 = 0;
2537 bool IsNonStatic2 = false;
2538 bool IsNonStatic1 = false;
2539 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002540 switch (TPOC) {
2541 case TPOC_Call: {
2542 // - In the context of a function call, the function parameter types are
2543 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002544 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2545 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2546 IsNonStatic1 = Method1 && !Method1->isStatic();
2547 IsNonStatic2 = Method2 && !Method2->isStatic();
2548
2549 // C++0x [temp.func.order]p3:
2550 // [...] If only one of the function templates is a non-static
2551 // member, that function template is considered to have a new
2552 // first parameter inserted in its function parameter list. The
2553 // new parameter is of type "reference to cv A," where cv are
2554 // the cv-qualifiers of the function template (if any) and A is
2555 // the class of which the function template is a member.
2556 //
2557 // C++98/03 doesn't have this provision, so instead we drop the
2558 // first argument of the free function or static member, which
2559 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002560 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002561 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2562 IsNonStatic2 && !IsNonStatic1;
2563 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002564 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2565 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002566 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002567
2568 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002569 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2570 IsNonStatic1 && !IsNonStatic2;
2571 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002572 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2573 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002574 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002575
2576 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002577 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002578 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002579 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002580 Args2[I],
2581 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002582 Info,
2583 Deduced,
2584 QualifierComparisons))
2585 return false;
2586
2587 break;
2588 }
2589
2590 case TPOC_Conversion:
2591 // - In the context of a call to a conversion operator, the return types
2592 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002593 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002594 TemplateParams,
2595 Proto2->getResultType(),
2596 Proto1->getResultType(),
2597 Info,
2598 Deduced,
2599 QualifierComparisons))
2600 return false;
2601 break;
2602
2603 case TPOC_Other:
2604 // - In other contexts (14.6.6.2) the function template’s function type
2605 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002606 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002607 TemplateParams,
2608 FD2->getType(),
2609 FD1->getType(),
2610 Info,
2611 Deduced,
2612 QualifierComparisons))
2613 return false;
2614 break;
2615 }
2616
2617 // C++0x [temp.deduct.partial]p11:
2618 // In most cases, all template parameters must have values in order for
2619 // deduction to succeed, but for partial ordering purposes a template
2620 // parameter may remain without a value provided it is not used in the
2621 // types being used for partial ordering. [ Note: a template parameter used
2622 // in a non-deduced context is considered used. -end note]
2623 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2624 for (; ArgIdx != NumArgs; ++ArgIdx)
2625 if (Deduced[ArgIdx].isNull())
2626 break;
2627
2628 if (ArgIdx == NumArgs) {
2629 // All template arguments were deduced. FT1 is at least as specialized
2630 // as FT2.
2631 return true;
2632 }
2633
Douglas Gregore73bb602009-09-14 21:25:05 +00002634 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002635 llvm::SmallVector<bool, 4> UsedParameters;
2636 UsedParameters.resize(TemplateParams->size());
2637 switch (TPOC) {
2638 case TPOC_Call: {
2639 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002640 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2641 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2642 TemplateParams->getDepth(), UsedParameters);
2643 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002644 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2645 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002646 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002647 break;
2648 }
2649
2650 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002651 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2652 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002653 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002654 break;
2655
2656 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002657 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2658 TemplateParams->getDepth(),
2659 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002660 break;
2661 }
2662
2663 for (; ArgIdx != NumArgs; ++ArgIdx)
2664 // If this argument had no value deduced but was used in one of the types
2665 // used for partial ordering, then deduction fails.
2666 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2667 return false;
2668
2669 return true;
2670}
2671
2672
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002673/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002674/// to the rules of function template partial ordering (C++ [temp.func.order]).
2675///
2676/// \param FT1 the first function template
2677///
2678/// \param FT2 the second function template
2679///
Douglas Gregor8a514912009-09-14 18:39:43 +00002680/// \param TPOC the context in which we are performing partial ordering of
2681/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00002682///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002683/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002684/// template is more specialized, returns NULL.
2685FunctionTemplateDecl *
2686Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2687 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00002688 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002689 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002690 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00002691 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2692 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00002693 &QualifierComparisons);
2694
2695 if (Better1 != Better2) // We have a clear winner
2696 return Better1? FT1 : FT2;
2697
2698 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002699 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002700
2701
2702 // C++0x [temp.deduct.partial]p10:
2703 // If for each type being considered a given template is at least as
2704 // specialized for all types and more specialized for some set of types and
2705 // the other template is not more specialized for any types or is not at
2706 // least as specialized for any types, then the given template is more
2707 // specialized than the other template. Otherwise, neither template is more
2708 // specialized than the other.
2709 Better1 = false;
2710 Better2 = false;
2711 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2712 // C++0x [temp.deduct.partial]p9:
2713 // If, for a given type, deduction succeeds in both directions (i.e., the
2714 // types are identical after the transformations above) and if the type
2715 // from the argument template is more cv-qualified than the type from the
2716 // parameter template (as described above) that type is considered to be
2717 // more specialized than the other. If neither type is more cv-qualified
2718 // than the other then neither type is more specialized than the other.
2719 switch (QualifierComparisons[I]) {
2720 case NeitherMoreQualified:
2721 break;
2722
2723 case ParamMoreQualified:
2724 Better1 = true;
2725 if (Better2)
2726 return 0;
2727 break;
2728
2729 case ArgMoreQualified:
2730 Better2 = true;
2731 if (Better1)
2732 return 0;
2733 break;
2734 }
2735 }
2736
2737 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002738 if (Better1)
2739 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00002740 else if (Better2)
2741 return FT2;
2742 else
2743 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002744}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002745
Douglas Gregord5a423b2009-09-25 18:43:00 +00002746/// \brief Determine if the two templates are equivalent.
2747static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2748 if (T1 == T2)
2749 return true;
2750
2751 if (!T1 || !T2)
2752 return false;
2753
2754 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2755}
2756
2757/// \brief Retrieve the most specialized of the given function template
2758/// specializations.
2759///
John McCallc373d482010-01-27 01:50:18 +00002760/// \param SpecBegin the start iterator of the function template
2761/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002762///
John McCallc373d482010-01-27 01:50:18 +00002763/// \param SpecEnd the end iterator of the function template
2764/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002765///
2766/// \param TPOC the partial ordering context to use to compare the function
2767/// template specializations.
2768///
2769/// \param Loc the location where the ambiguity or no-specializations
2770/// diagnostic should occur.
2771///
2772/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2773/// no matching candidates.
2774///
2775/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2776/// occurs.
2777///
2778/// \param CandidateDiag partial diagnostic used for each function template
2779/// specialization that is a candidate in the ambiguous ordering. One parameter
2780/// in this diagnostic should be unbound, which will correspond to the string
2781/// describing the template arguments for the function template specialization.
2782///
2783/// \param Index if non-NULL and the result of this function is non-nULL,
2784/// receives the index corresponding to the resulting function template
2785/// specialization.
2786///
2787/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00002788/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002789///
2790/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2791/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00002792UnresolvedSetIterator
2793Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
2794 UnresolvedSetIterator SpecEnd,
2795 TemplatePartialOrderingContext TPOC,
2796 SourceLocation Loc,
2797 const PartialDiagnostic &NoneDiag,
2798 const PartialDiagnostic &AmbigDiag,
2799 const PartialDiagnostic &CandidateDiag) {
2800 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00002801 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00002802 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002803 }
2804
John McCallc373d482010-01-27 01:50:18 +00002805 if (SpecBegin + 1 == SpecEnd)
2806 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002807
2808 // Find the function template that is better than all of the templates it
2809 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00002810 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002811 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00002812 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002813 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002814 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
2815 FunctionTemplateDecl *Challenger
2816 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002817 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002818 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002819 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002820 Challenger)) {
2821 Best = I;
2822 BestTemplate = Challenger;
2823 }
2824 }
2825
2826 // Make sure that the "best" function template is more specialized than all
2827 // of the others.
2828 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00002829 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
2830 FunctionTemplateDecl *Challenger
2831 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002832 if (I != Best &&
2833 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002834 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002835 BestTemplate)) {
2836 Ambiguous = true;
2837 break;
2838 }
2839 }
2840
2841 if (!Ambiguous) {
2842 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00002843 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002844 }
2845
2846 // Diagnose the ambiguity.
2847 Diag(Loc, AmbigDiag);
2848
2849 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00002850 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
2851 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00002852 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00002853 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
2854 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00002855
John McCallc373d482010-01-27 01:50:18 +00002856 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002857}
2858
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002859/// \brief Returns the more specialized class template partial specialization
2860/// according to the rules of partial ordering of class template partial
2861/// specializations (C++ [temp.class.order]).
2862///
2863/// \param PS1 the first class template partial specialization
2864///
2865/// \param PS2 the second class template partial specialization
2866///
2867/// \returns the more specialized class template partial specialization. If
2868/// neither partial specialization is more specialized, returns NULL.
2869ClassTemplatePartialSpecializationDecl *
2870Sema::getMoreSpecializedPartialSpecialization(
2871 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00002872 ClassTemplatePartialSpecializationDecl *PS2,
2873 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002874 // C++ [temp.class.order]p1:
2875 // For two class template partial specializations, the first is at least as
2876 // specialized as the second if, given the following rewrite to two
2877 // function templates, the first function template is at least as
2878 // specialized as the second according to the ordering rules for function
2879 // templates (14.6.6.2):
2880 // - the first function template has the same template parameters as the
2881 // first partial specialization and has a single function parameter
2882 // whose type is a class template specialization with the template
2883 // arguments of the first partial specialization, and
2884 // - the second function template has the same template parameters as the
2885 // second partial specialization and has a single function parameter
2886 // whose type is a class template specialization with the template
2887 // arguments of the second partial specialization.
2888 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002889 // Rather than synthesize function templates, we merely perform the
2890 // equivalent partial ordering by performing deduction directly on
2891 // the template arguments of the class template partial
2892 // specializations. This computation is slightly simpler than the
2893 // general problem of function template partial ordering, because
2894 // class template partial specializations are more constrained. We
2895 // know that every template parameter is deducible from the class
2896 // template partial specialization's template arguments, for
2897 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00002898 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00002899 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00002900
2901 QualType PT1 = PS1->getInjectedSpecializationType();
2902 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002903
2904 // Determine whether PS1 is at least as specialized as PS2
2905 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002906 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002907 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002908 PT2,
2909 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002910 Info,
2911 Deduced,
2912 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002913 if (Better1) {
2914 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
2915 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002916 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
2917 PS1->getTemplateArgs(),
2918 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002919 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00002920
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002921 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002922 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002923 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002924 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002925 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002926 PT1,
2927 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002928 Info,
2929 Deduced,
2930 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002931 if (Better2) {
2932 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
2933 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002934 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
2935 PS2->getTemplateArgs(),
2936 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002937 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002938
2939 if (Better1 == Better2)
2940 return 0;
2941
2942 return Better1? PS1 : PS2;
2943}
2944
Mike Stump1eb44332009-09-09 15:08:12 +00002945static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002946MarkUsedTemplateParameters(Sema &SemaRef,
2947 const TemplateArgument &TemplateArg,
2948 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002949 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002950 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002951
Douglas Gregore73bb602009-09-14 21:25:05 +00002952/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002953/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002954static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002955MarkUsedTemplateParameters(Sema &SemaRef,
2956 const Expr *E,
2957 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002958 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002959 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00002960 // We can deduce from a pack expansion.
2961 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
2962 E = Expansion->getPattern();
2963
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002964 // Skip through any implicit casts we added while type-checking.
2965 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
2966 E = ICE->getSubExpr();
2967
Douglas Gregore73bb602009-09-14 21:25:05 +00002968 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2969 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002970 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00002971 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00002972 return;
2973
Mike Stump1eb44332009-09-09 15:08:12 +00002974 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00002975 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2976 if (!NTTP)
2977 return;
2978
Douglas Gregored9c0f92009-10-29 00:04:11 +00002979 if (NTTP->getDepth() == Depth)
2980 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00002981}
2982
Douglas Gregore73bb602009-09-14 21:25:05 +00002983/// \brief Mark the template parameters that are used by the given
2984/// nested name specifier.
2985static void
2986MarkUsedTemplateParameters(Sema &SemaRef,
2987 NestedNameSpecifier *NNS,
2988 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002989 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002990 llvm::SmallVectorImpl<bool> &Used) {
2991 if (!NNS)
2992 return;
2993
Douglas Gregored9c0f92009-10-29 00:04:11 +00002994 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
2995 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002996 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002997 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002998}
2999
3000/// \brief Mark the template parameters that are used by the given
3001/// template name.
3002static void
3003MarkUsedTemplateParameters(Sema &SemaRef,
3004 TemplateName Name,
3005 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003006 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003007 llvm::SmallVectorImpl<bool> &Used) {
3008 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3009 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003010 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3011 if (TTP->getDepth() == Depth)
3012 Used[TTP->getIndex()] = true;
3013 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003014 return;
3015 }
3016
Douglas Gregor788cd062009-11-11 01:00:40 +00003017 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3018 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3019 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003020 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003021 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3022 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003023}
3024
3025/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003026/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003027static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003028MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3029 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003030 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003031 llvm::SmallVectorImpl<bool> &Used) {
3032 if (T.isNull())
3033 return;
3034
Douglas Gregor031a5882009-06-13 00:26:55 +00003035 // Non-dependent types have nothing deducible
3036 if (!T->isDependentType())
3037 return;
3038
3039 T = SemaRef.Context.getCanonicalType(T);
3040 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003041 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003042 MarkUsedTemplateParameters(SemaRef,
3043 cast<PointerType>(T)->getPointeeType(),
3044 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003045 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003046 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003047 break;
3048
3049 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003050 MarkUsedTemplateParameters(SemaRef,
3051 cast<BlockPointerType>(T)->getPointeeType(),
3052 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003053 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003054 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003055 break;
3056
3057 case Type::LValueReference:
3058 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003059 MarkUsedTemplateParameters(SemaRef,
3060 cast<ReferenceType>(T)->getPointeeType(),
3061 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003062 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003063 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003064 break;
3065
3066 case Type::MemberPointer: {
3067 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003068 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003069 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003070 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003071 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003072 break;
3073 }
3074
3075 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003076 MarkUsedTemplateParameters(SemaRef,
3077 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003078 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003079 // Fall through to check the element type
3080
3081 case Type::ConstantArray:
3082 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003083 MarkUsedTemplateParameters(SemaRef,
3084 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003085 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003086 break;
3087
3088 case Type::Vector:
3089 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003090 MarkUsedTemplateParameters(SemaRef,
3091 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003092 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003093 break;
3094
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003095 case Type::DependentSizedExtVector: {
3096 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003097 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003098 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003099 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003100 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003101 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003102 break;
3103 }
3104
Douglas Gregor031a5882009-06-13 00:26:55 +00003105 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003106 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003107 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003108 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003109 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003110 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003111 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003112 break;
3113 }
3114
Douglas Gregored9c0f92009-10-29 00:04:11 +00003115 case Type::TemplateTypeParm: {
3116 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3117 if (TTP->getDepth() == Depth)
3118 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003119 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003120 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003121
John McCall31f17ec2010-04-27 00:57:59 +00003122 case Type::InjectedClassName:
3123 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3124 // fall through
3125
Douglas Gregor031a5882009-06-13 00:26:55 +00003126 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003127 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003128 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003129 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003130 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003131
3132 // C++0x [temp.deduct.type]p9:
3133 // If the template argument list of P contains a pack expansion that is not
3134 // the last template argument, the entire template argument list is a
3135 // non-deduced context.
3136 if (OnlyDeduced &&
3137 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3138 break;
3139
Douglas Gregore73bb602009-09-14 21:25:05 +00003140 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003141 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3142 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003143 break;
3144 }
3145
Douglas Gregore73bb602009-09-14 21:25:05 +00003146 case Type::Complex:
3147 if (!OnlyDeduced)
3148 MarkUsedTemplateParameters(SemaRef,
3149 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003150 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003151 break;
3152
Douglas Gregor4714c122010-03-31 17:34:00 +00003153 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003154 if (!OnlyDeduced)
3155 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003156 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003157 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003158 break;
3159
John McCall33500952010-06-11 00:33:02 +00003160 case Type::DependentTemplateSpecialization: {
3161 const DependentTemplateSpecializationType *Spec
3162 = cast<DependentTemplateSpecializationType>(T);
3163 if (!OnlyDeduced)
3164 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3165 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003166
3167 // C++0x [temp.deduct.type]p9:
3168 // If the template argument list of P contains a pack expansion that is not
3169 // the last template argument, the entire template argument list is a
3170 // non-deduced context.
3171 if (OnlyDeduced &&
3172 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3173 break;
3174
John McCall33500952010-06-11 00:33:02 +00003175 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3176 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3177 Used);
3178 break;
3179 }
3180
John McCallad5e7382010-03-01 23:49:17 +00003181 case Type::TypeOf:
3182 if (!OnlyDeduced)
3183 MarkUsedTemplateParameters(SemaRef,
3184 cast<TypeOfType>(T)->getUnderlyingType(),
3185 OnlyDeduced, Depth, Used);
3186 break;
3187
3188 case Type::TypeOfExpr:
3189 if (!OnlyDeduced)
3190 MarkUsedTemplateParameters(SemaRef,
3191 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3192 OnlyDeduced, Depth, Used);
3193 break;
3194
3195 case Type::Decltype:
3196 if (!OnlyDeduced)
3197 MarkUsedTemplateParameters(SemaRef,
3198 cast<DecltypeType>(T)->getUnderlyingExpr(),
3199 OnlyDeduced, Depth, Used);
3200 break;
3201
Douglas Gregor7536dd52010-12-20 02:24:11 +00003202 case Type::PackExpansion:
3203 MarkUsedTemplateParameters(SemaRef,
3204 cast<PackExpansionType>(T)->getPattern(),
3205 OnlyDeduced, Depth, Used);
3206 break;
3207
Douglas Gregore73bb602009-09-14 21:25:05 +00003208 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003209 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003210 case Type::VariableArray:
3211 case Type::FunctionNoProto:
3212 case Type::Record:
3213 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003214 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003215 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003216 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003217 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003218#define TYPE(Class, Base)
3219#define ABSTRACT_TYPE(Class, Base)
3220#define DEPENDENT_TYPE(Class, Base)
3221#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3222#include "clang/AST/TypeNodes.def"
3223 break;
3224 }
3225}
3226
Douglas Gregore73bb602009-09-14 21:25:05 +00003227/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003228/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003229static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003230MarkUsedTemplateParameters(Sema &SemaRef,
3231 const TemplateArgument &TemplateArg,
3232 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003233 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003234 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003235 switch (TemplateArg.getKind()) {
3236 case TemplateArgument::Null:
3237 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003238 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003239 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003240
Douglas Gregor031a5882009-06-13 00:26:55 +00003241 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003242 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003243 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003244 break;
3245
Douglas Gregor788cd062009-11-11 01:00:40 +00003246 case TemplateArgument::Template:
3247 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsTemplate(),
3248 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003249 break;
3250
3251 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003252 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003253 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003254 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003255
Anders Carlssond01b1da2009-06-15 17:04:53 +00003256 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003257 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3258 PEnd = TemplateArg.pack_end();
3259 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003260 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003261 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003262 }
3263}
3264
3265/// \brief Mark the template parameters can be deduced by the given
3266/// template argument list.
3267///
3268/// \param TemplateArgs the template argument list from which template
3269/// parameters will be deduced.
3270///
3271/// \param Deduced a bit vector whose elements will be set to \c true
3272/// to indicate when the corresponding template parameter will be
3273/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003274void
Douglas Gregore73bb602009-09-14 21:25:05 +00003275Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003276 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003277 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003278 // C++0x [temp.deduct.type]p9:
3279 // If the template argument list of P contains a pack expansion that is not
3280 // the last template argument, the entire template argument list is a
3281 // non-deduced context.
3282 if (OnlyDeduced &&
3283 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3284 return;
3285
Douglas Gregor031a5882009-06-13 00:26:55 +00003286 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003287 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3288 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003289}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003290
3291/// \brief Marks all of the template parameters that will be deduced by a
3292/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003293void
3294Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3295 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003296 TemplateParameterList *TemplateParams
3297 = FunctionTemplate->getTemplateParameters();
3298 Deduced.clear();
3299 Deduced.resize(TemplateParams->size());
3300
3301 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3302 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3303 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003304 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003305}