blob: c80e2e0c1e7ff7e0e0db57c3e13723f832643d61 [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))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000707 return DeduceNonTypeTemplateArgument(S, NTTP,
Douglas Gregor199d9912009-06-05 00:53:49 +0000708 DependentArrayArg->getSizeExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000709 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Douglas Gregor199d9912009-06-05 00:53:49 +0000711 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000712 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000713 }
Mike Stump1eb44332009-09-09 15:08:12 +0000714
715 // type(*)(T)
716 // T(*)()
717 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000718 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000719 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000720 dyn_cast<FunctionProtoType>(Arg);
721 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000722 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000723
724 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000725 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000726
Mike Stump1eb44332009-09-09 15:08:12 +0000727 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000728 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000729 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000731 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000732 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000734 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000735 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000736
Anders Carlssona27fad52009-06-08 15:19:08 +0000737 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000738 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000739 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000740 FunctionProtoParam->getResultType(),
741 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000742 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000743 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Anders Carlssona27fad52009-06-08 15:19:08 +0000745 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
746 // Check argument types.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000747 // FIXME: Variadic templates.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000748 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000749 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000750 FunctionProtoParam->getArgType(I),
751 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000752 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000753 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000754 }
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Douglas Gregorf67875d2009-06-12 18:26:56 +0000756 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000757 }
Mike Stump1eb44332009-09-09 15:08:12 +0000758
John McCall3cb0ebd2010-03-10 03:28:59 +0000759 case Type::InjectedClassName: {
760 // Treat a template's injected-class-name as if the template
761 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000762 Param = cast<InjectedClassNameType>(Param)
763 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000764 assert(isa<TemplateSpecializationType>(Param) &&
765 "injected class name is not a template specialization type");
766 // fall through
767 }
768
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000769 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000770 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000771 // TT<T>
772 // TT<i>
773 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000774 case Type::TemplateSpecialization: {
775 const TemplateSpecializationType *SpecParam
776 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000778 // Try to deduce template arguments from the template-id.
779 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000780 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000781 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Douglas Gregor4a5c15f2009-09-30 22:13:51 +0000783 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000784 // C++ [temp.deduct.call]p3b3:
785 // If P is a class, and P has the form template-id, then A can be a
786 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +0000787 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000788 // class pointed to by the deduced A.
789 //
790 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +0000791 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000792 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000793 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
794 // We cannot inspect base classes as part of deduction when the type
795 // is incomplete, so either instantiate any templates necessary to
796 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +0000797 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000798 return Result;
799
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000800 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000801 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000802 // ToVisit is our stack of records that we still need to visit.
803 llvm::SmallPtrSet<const RecordType *, 8> Visited;
804 llvm::SmallVector<const RecordType *, 8> ToVisit;
805 ToVisit.push_back(RecordT);
806 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +0000807 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
808 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000809 while (!ToVisit.empty()) {
810 // Retrieve the next class in the inheritance hierarchy.
811 const RecordType *NextT = ToVisit.back();
812 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000814 // If we have already seen this type, skip it.
815 if (!Visited.insert(NextT))
816 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000818 // If this is a base class, try to perform template argument
819 // deduction from it.
820 if (NextT != RecordT) {
821 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000822 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000823 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000825 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +0000826 // note that we had some success. Otherwise, ignore any deductions
827 // from this base class.
828 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000829 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +0000830 DeducedOrig = Deduced;
831 }
832 else
833 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000834 }
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000836 // Visit base classes
837 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
838 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
839 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +0000840 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000841 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000842 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +0000843 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000844 }
845 }
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000847 if (Successful)
848 return Sema::TDK_Success;
849 }
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000851 }
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000853 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000854 }
855
Douglas Gregor637a4092009-06-10 23:47:09 +0000856 // T type::*
857 // T T::*
858 // T (type::*)()
859 // type (T::*)()
860 // type (type::*)(T)
861 // type (T::*)(T)
862 // T (type::*)(T)
863 // T (T::*)()
864 // T (T::*)(T)
865 case Type::MemberPointer: {
866 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
867 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
868 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000869 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000870
Douglas Gregorf67875d2009-06-12 18:26:56 +0000871 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000872 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000873 MemPtrParam->getPointeeType(),
874 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000875 Info, Deduced,
876 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000877 return Result;
878
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000879 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000880 QualType(MemPtrParam->getClass(), 0),
881 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000882 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000883 }
884
Anders Carlsson9a917e42009-06-12 22:56:54 +0000885 // (clang extension)
886 //
Mike Stump1eb44332009-09-09 15:08:12 +0000887 // type(^)(T)
888 // T(^)()
889 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +0000890 case Type::BlockPointer: {
891 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
892 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Anders Carlsson859ba502009-06-12 16:23:10 +0000894 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000895 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000897 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000898 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000899 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000900 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000901 }
902
Douglas Gregor637a4092009-06-10 23:47:09 +0000903 case Type::TypeOfExpr:
904 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +0000905 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +0000906 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000907 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000908
Douglas Gregord560d502009-06-04 00:21:18 +0000909 default:
910 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000911 }
912
913 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000914 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000915}
916
Douglas Gregorf67875d2009-06-12 18:26:56 +0000917static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000918DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000919 TemplateParameterList *TemplateParams,
920 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000921 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000922 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000923 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000924 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000925 case TemplateArgument::Null:
926 assert(false && "Null template argument in parameter list");
927 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000928
929 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +0000930 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000931 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000932 Arg.getAsType(), Info, Deduced, 0);
933 Info.FirstArg = Param;
934 Info.SecondArg = Arg;
935 return Sema::TDK_NonDeducedMismatch;
936
937 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000938 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000939 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +0000940 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000941 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +0000942 Info.FirstArg = Param;
943 Info.SecondArg = Arg;
944 return Sema::TDK_NonDeducedMismatch;
945
Douglas Gregor199d9912009-06-05 00:53:49 +0000946 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +0000947 if (Arg.getKind() == TemplateArgument::Declaration &&
948 Param.getAsDecl()->getCanonicalDecl() ==
949 Arg.getAsDecl()->getCanonicalDecl())
950 return Sema::TDK_Success;
951
Douglas Gregorf67875d2009-06-12 18:26:56 +0000952 Info.FirstArg = Param;
953 Info.SecondArg = Arg;
954 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Douglas Gregor199d9912009-06-05 00:53:49 +0000956 case TemplateArgument::Integral:
957 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000958 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000959 return Sema::TDK_Success;
960
961 Info.FirstArg = Param;
962 Info.SecondArg = Arg;
963 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000964 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000965
966 if (Arg.getKind() == TemplateArgument::Expression) {
967 Info.FirstArg = Param;
968 Info.SecondArg = Arg;
969 return Sema::TDK_NonDeducedMismatch;
970 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000971
Douglas Gregorf67875d2009-06-12 18:26:56 +0000972 Info.FirstArg = Param;
973 Info.SecondArg = Arg;
974 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Douglas Gregor199d9912009-06-05 00:53:49 +0000976 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +0000977 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000978 = getDeducedParameterFromExpr(Param.getAsExpr())) {
979 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000980 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +0000981 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000982 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000983 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000984 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000985 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000986 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000987 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +0000988 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000989 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +0000990 Info, Deduced);
991
Douglas Gregorf67875d2009-06-12 18:26:56 +0000992 Info.FirstArg = Param;
993 Info.SecondArg = Arg;
994 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000995 }
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Douglas Gregor199d9912009-06-05 00:53:49 +0000997 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000998 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000999 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001000 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001001 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001002 }
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Douglas Gregorf67875d2009-06-12 18:26:56 +00001004 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001005}
1006
Douglas Gregor20a55e22010-12-22 18:17:10 +00001007/// \brief Determine whether there is a template argument to be used for
1008/// deduction.
1009///
1010/// This routine "expands" argument packs in-place, overriding its input
1011/// parameters so that \c Args[ArgIdx] will be the available template argument.
1012///
1013/// \returns true if there is another template argument (which will be at
1014/// \c Args[ArgIdx]), false otherwise.
1015static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1016 unsigned &ArgIdx,
1017 unsigned &NumArgs) {
1018 if (ArgIdx == NumArgs)
1019 return false;
1020
1021 const TemplateArgument &Arg = Args[ArgIdx];
1022 if (Arg.getKind() != TemplateArgument::Pack)
1023 return true;
1024
1025 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1026 Args = Arg.pack_begin();
1027 NumArgs = Arg.pack_size();
1028 ArgIdx = 0;
1029 return ArgIdx < NumArgs;
1030}
1031
Douglas Gregore02e2622010-12-22 21:19:48 +00001032/// \brief Retrieve the depth and index of an unexpanded parameter pack.
1033static std::pair<unsigned, unsigned>
1034getDepthAndIndex(UnexpandedParameterPack UPP) {
1035 if (const TemplateTypeParmType *TTP
1036 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
1037 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1038
1039 if (TemplateTypeParmDecl *TTP = UPP.first.dyn_cast<TemplateTypeParmDecl *>())
1040 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1041
1042 if (NonTypeTemplateParmDecl *NTTP
1043 = UPP.first.dyn_cast<NonTypeTemplateParmDecl *>())
1044 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
1045
1046 TemplateTemplateParmDecl *TTP = UPP.first.get<TemplateTemplateParmDecl *>();
1047 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1048}
1049
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001050/// \brief Helper function to build a TemplateParameter when we don't
1051/// know its type statically.
1052static TemplateParameter makeTemplateParameter(Decl *D) {
1053 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
1054 return TemplateParameter(TTP);
1055 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
1056 return TemplateParameter(NTTP);
1057
1058 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
1059}
1060
Douglas Gregor20a55e22010-12-22 18:17:10 +00001061static Sema::TemplateDeductionResult
1062DeduceTemplateArguments(Sema &S,
1063 TemplateParameterList *TemplateParams,
1064 const TemplateArgument *Params, unsigned NumParams,
1065 const TemplateArgument *Args, unsigned NumArgs,
1066 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001067 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1068 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001069 // C++0x [temp.deduct.type]p9:
1070 // If the template argument list of P contains a pack expansion that is not
1071 // the last template argument, the entire template argument list is a
1072 // non-deduced context.
1073 // FIXME: Implement this.
1074
1075
1076 // C++0x [temp.deduct.type]p9:
1077 // If P has a form that contains <T> or <i>, then each argument Pi of the
1078 // respective template argument list P is compared with the corresponding
1079 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001080 unsigned ArgIdx = 0, ParamIdx = 0;
1081 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1082 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001083 // FIXME: Variadic templates.
1084 // What do we do if the argument is a pack expansion?
1085
Douglas Gregor20a55e22010-12-22 18:17:10 +00001086 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001087 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001088
1089 // Check whether we have enough arguments.
1090 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001091 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1092 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001093
Douglas Gregore02e2622010-12-22 21:19:48 +00001094 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001095 if (Sema::TemplateDeductionResult Result
1096 = DeduceTemplateArguments(S, TemplateParams,
1097 Params[ParamIdx], Args[ArgIdx],
1098 Info, Deduced))
1099 return Result;
1100
1101 // Move to the next argument.
1102 ++ArgIdx;
1103 continue;
1104 }
1105
Douglas Gregore02e2622010-12-22 21:19:48 +00001106 // The parameter is a pack expansion.
1107
1108 // C++0x [temp.deduct.type]p9:
1109 // If Pi is a pack expansion, then the pattern of Pi is compared with
1110 // each remaining argument in the template argument list of A. Each
1111 // comparison deduces template arguments for subsequent positions in the
1112 // template parameter packs expanded by Pi.
1113 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1114
1115 // Compute the set of template parameter indices that correspond to
1116 // parameter packs expanded by the pack expansion.
1117 llvm::SmallVector<unsigned, 2> PackIndices;
1118 {
1119 llvm::BitVector SawIndices(TemplateParams->size());
1120 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1121 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1122 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1123 unsigned Depth, Index;
1124 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1125 if (Depth == 0 && !SawIndices[Index]) {
1126 SawIndices[Index] = true;
1127 PackIndices.push_back(Index);
1128 }
1129 }
1130 }
1131 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1132
1133 // FIXME: If there are no remaining arguments, we can bail out early
1134 // and set any deduced parameter packs to an empty argument pack.
1135 // The latter part of this is a (minor) correctness issue.
1136
1137 // Save the deduced template arguments for each parameter pack expanded
1138 // by this pack expansion, then clear out the deduction.
1139 llvm::SmallVector<DeducedTemplateArgument, 2>
1140 SavedPacks(PackIndices.size());
1141 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1142 SavedPacks[I] = Deduced[PackIndices[I]];
1143 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1144 }
1145
1146 // Keep track of the deduced template arguments for each parameter pack
1147 // expanded by this pack expansion (the outer index) and for each
1148 // template argument (the inner SmallVectors).
1149 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1150 NewlyDeducedPacks(PackIndices.size());
1151 bool HasAnyArguments = false;
1152 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1153 HasAnyArguments = true;
1154
1155 // Deduce template arguments from the pattern.
1156 if (Sema::TemplateDeductionResult Result
1157 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1158 Info, Deduced))
1159 return Result;
1160
1161 // Capture the deduced template arguments for each parameter pack expanded
1162 // by this pack expansion, add them to the list of arguments we've deduced
1163 // for that pack, then clear out the deduced argument.
1164 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1165 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1166 if (!DeducedArg.isNull()) {
1167 NewlyDeducedPacks[I].push_back(DeducedArg);
1168 DeducedArg = DeducedTemplateArgument();
1169 }
1170 }
1171
1172 ++ArgIdx;
1173 }
1174
1175 // Build argument packs for each of the parameter packs expanded by this
1176 // pack expansion.
1177 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1178 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1179 // We were not able to deduce anything for this parameter pack,
1180 // so just restore the saved argument pack.
1181 Deduced[PackIndices[I]] = SavedPacks[I];
1182 continue;
1183 }
1184
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001185 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001186
1187 if (NewlyDeducedPacks[I].empty()) {
1188 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001189 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1190 } else {
1191 TemplateArgument *ArgumentPack
1192 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1193 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1194 ArgumentPack);
1195 NewPack
1196 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001197 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001198 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1199 }
1200
1201 DeducedTemplateArgument Result
1202 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1203 if (Result.isNull()) {
1204 Info.Param
1205 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1206 Info.FirstArg = SavedPacks[I];
1207 Info.SecondArg = NewPack;
1208 return Sema::TDK_Inconsistent;
1209 }
1210
1211 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001212 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001213 }
1214
1215 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001216 if (NumberOfArgumentsMustMatch &&
1217 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001218 return Sema::TDK_TooManyArguments;
1219
1220 return Sema::TDK_Success;
1221}
1222
Mike Stump1eb44332009-09-09 15:08:12 +00001223static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001224DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001225 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001226 const TemplateArgumentList &ParamList,
1227 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001228 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001229 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001230 return DeduceTemplateArguments(S, TemplateParams,
1231 ParamList.data(), ParamList.size(),
1232 ArgList.data(), ArgList.size(),
1233 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001234}
1235
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001236/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001237static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001238 const TemplateArgument &X,
1239 const TemplateArgument &Y) {
1240 if (X.getKind() != Y.getKind())
1241 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001243 switch (X.getKind()) {
1244 case TemplateArgument::Null:
1245 assert(false && "Comparing NULL template argument");
1246 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001248 case TemplateArgument::Type:
1249 return Context.getCanonicalType(X.getAsType()) ==
1250 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001252 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001253 return X.getAsDecl()->getCanonicalDecl() ==
1254 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Douglas Gregor788cd062009-11-11 01:00:40 +00001256 case TemplateArgument::Template:
1257 return Context.getCanonicalTemplateName(X.getAsTemplate())
1258 .getAsVoidPointer() ==
1259 Context.getCanonicalTemplateName(Y.getAsTemplate())
1260 .getAsVoidPointer();
1261
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001262 case TemplateArgument::Integral:
1263 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Douglas Gregor788cd062009-11-11 01:00:40 +00001265 case TemplateArgument::Expression: {
1266 llvm::FoldingSetNodeID XID, YID;
1267 X.getAsExpr()->Profile(XID, Context, true);
1268 Y.getAsExpr()->Profile(YID, Context, true);
1269 return XID == YID;
1270 }
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001272 case TemplateArgument::Pack:
1273 if (X.pack_size() != Y.pack_size())
1274 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001275
1276 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1277 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001278 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001279 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001280 if (!isSameTemplateArg(Context, *XP, *YP))
1281 return false;
1282
1283 return true;
1284 }
1285
1286 return false;
1287}
1288
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001289/// Complete template argument deduction for a class template partial
1290/// specialization.
1291static Sema::TemplateDeductionResult
1292FinishTemplateArgumentDeduction(Sema &S,
1293 ClassTemplatePartialSpecializationDecl *Partial,
1294 const TemplateArgumentList &TemplateArgs,
1295 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001296 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001297 // Trap errors.
1298 Sema::SFINAETrap Trap(S);
1299
1300 Sema::ContextRAII SavedContext(S, Partial);
1301
1302 // C++ [temp.deduct.type]p2:
1303 // [...] or if any template argument remains neither deduced nor
1304 // explicitly specified, template argument deduction fails.
Douglas Gregore02e2622010-12-22 21:19:48 +00001305 // FIXME: Variadic templates Empty parameter packs?
Douglas Gregor910f8002010-11-07 23:05:16 +00001306 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001307 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1308 if (Deduced[I].isNull()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001309 unsigned ParamIdx = I;
1310 if (ParamIdx >= Partial->getTemplateParameters()->size())
1311 ParamIdx = Partial->getTemplateParameters()->size() - 1;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001312 Decl *Param
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001313 = const_cast<NamedDecl *>(
Douglas Gregore02e2622010-12-22 21:19:48 +00001314 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001315 Info.Param = makeTemplateParameter(Param);
1316 return Sema::TDK_Incomplete;
1317 }
1318
Douglas Gregor910f8002010-11-07 23:05:16 +00001319 Builder.push_back(Deduced[I]);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001320 }
1321
1322 // Form the template argument list from the deduced template arguments.
1323 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001324 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1325 Builder.size());
1326
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001327 Info.reset(DeducedArgumentList);
1328
1329 // Substitute the deduced template arguments into the template
1330 // arguments of the class template partial specialization, and
1331 // verify that the instantiated template arguments are both valid
1332 // and are equivalent to the template arguments originally provided
1333 // to the class template.
1334 // FIXME: Do we have to correct the types of deduced non-type template
1335 // arguments (in particular, integral non-type template arguments?).
John McCall2a7fb272010-08-25 05:32:35 +00001336 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001337 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1338 const TemplateArgumentLoc *PartialTemplateArgs
1339 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001340
1341 // Note that we don't provide the langle and rangle locations.
1342 TemplateArgumentListInfo InstArgs;
1343
Douglas Gregore02e2622010-12-22 21:19:48 +00001344 if (S.Subst(PartialTemplateArgs,
1345 Partial->getNumTemplateArgsAsWritten(),
1346 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1347 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1348 if (ParamIdx >= Partial->getTemplateParameters()->size())
1349 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1350
1351 Decl *Param
1352 = const_cast<NamedDecl *>(
1353 Partial->getTemplateParameters()->getParam(ParamIdx));
1354 Info.Param = makeTemplateParameter(Param);
1355 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1356 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001357 }
1358
Douglas Gregor910f8002010-11-07 23:05:16 +00001359 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001360 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorec20f462010-05-08 20:07:26 +00001361 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001362 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001363
Douglas Gregor910f8002010-11-07 23:05:16 +00001364 for (unsigned I = 0, E = ConvertedInstArgs.size(); I != E; ++I) {
1365 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001366
1367 Decl *Param = const_cast<NamedDecl *>(
1368 ClassTemplate->getTemplateParameters()->getParam(I));
1369
1370 if (InstArg.getKind() == TemplateArgument::Expression) {
1371 // When the argument is an expression, check the expression result
1372 // against the actual template parameter to get down to the canonical
1373 // template argument.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001374 // FIXME: Variadic templates.
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001375 Expr *InstExpr = InstArg.getAsExpr();
1376 if (NonTypeTemplateParmDecl *NTTP
1377 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1378 if (S.CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
1379 Info.Param = makeTemplateParameter(Param);
1380 Info.FirstArg = Partial->getTemplateArgs()[I];
1381 return Sema::TDK_SubstitutionFailure;
1382 }
1383 }
1384 }
1385
1386 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
1387 Info.Param = makeTemplateParameter(Param);
1388 Info.FirstArg = TemplateArgs[I];
1389 Info.SecondArg = InstArg;
1390 return Sema::TDK_NonDeducedMismatch;
1391 }
1392 }
1393
1394 if (Trap.hasErrorOccurred())
1395 return Sema::TDK_SubstitutionFailure;
1396
1397 return Sema::TDK_Success;
1398}
1399
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001400/// \brief Perform template argument deduction to determine whether
1401/// the given template arguments match the given class template
1402/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001403Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001404Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001405 const TemplateArgumentList &TemplateArgs,
1406 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001407 // C++ [temp.class.spec.match]p2:
1408 // A partial specialization matches a given actual template
1409 // argument list if the template arguments of the partial
1410 // specialization can be deduced from the actual template argument
1411 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001412 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001413 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001414 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001415 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001416 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001417 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001418 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001419 TemplateArgs, Info, Deduced))
1420 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001421
Douglas Gregor637a4092009-06-10 23:47:09 +00001422 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001423 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001424 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001425 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001426
Douglas Gregorbb260412009-06-14 08:02:22 +00001427 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001428 return Sema::TDK_SubstitutionFailure;
1429
1430 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1431 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001432}
Douglas Gregor031a5882009-06-13 00:26:55 +00001433
Douglas Gregor41128772009-06-26 23:27:24 +00001434/// \brief Determine whether the given type T is a simple-template-id type.
1435static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001436 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001437 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001438 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Douglas Gregor41128772009-06-26 23:27:24 +00001440 return false;
1441}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001442
1443/// \brief Substitute the explicitly-provided template arguments into the
1444/// given function template according to C++ [temp.arg.explicit].
1445///
1446/// \param FunctionTemplate the function template into which the explicit
1447/// template arguments will be substituted.
1448///
Mike Stump1eb44332009-09-09 15:08:12 +00001449/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001450/// arguments.
1451///
Mike Stump1eb44332009-09-09 15:08:12 +00001452/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001453/// with the converted and checked explicit template arguments.
1454///
Mike Stump1eb44332009-09-09 15:08:12 +00001455/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001456/// parameters.
1457///
1458/// \param FunctionType if non-NULL, the result type of the function template
1459/// will also be instantiated and the pointed-to value will be updated with
1460/// the instantiated function type.
1461///
1462/// \param Info if substitution fails for any reason, this object will be
1463/// populated with more information about the failure.
1464///
1465/// \returns TDK_Success if substitution was successful, or some failure
1466/// condition.
1467Sema::TemplateDeductionResult
1468Sema::SubstituteExplicitTemplateArguments(
1469 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001470 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001471 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001472 llvm::SmallVectorImpl<QualType> &ParamTypes,
1473 QualType *FunctionType,
1474 TemplateDeductionInfo &Info) {
1475 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1476 TemplateParameterList *TemplateParams
1477 = FunctionTemplate->getTemplateParameters();
1478
John McCalld5532b62009-11-23 01:53:49 +00001479 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001480 // No arguments to substitute; just copy over the parameter types and
1481 // fill in the function type.
1482 for (FunctionDecl::param_iterator P = Function->param_begin(),
1483 PEnd = Function->param_end();
1484 P != PEnd;
1485 ++P)
1486 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Douglas Gregor83314aa2009-07-08 20:55:45 +00001488 if (FunctionType)
1489 *FunctionType = Function->getType();
1490 return TDK_Success;
1491 }
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Douglas Gregor83314aa2009-07-08 20:55:45 +00001493 // Substitution of the explicit template arguments into a function template
1494 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001495 SFINAETrap Trap(*this);
1496
Douglas Gregor83314aa2009-07-08 20:55:45 +00001497 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001498 // Template arguments that are present shall be specified in the
1499 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001500 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001501 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001502 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001503
1504 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001505 // explicitly-specified template arguments against this function template,
1506 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001507 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001508 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001509 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1510 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001511 if (Inst)
1512 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Douglas Gregor83314aa2009-07-08 20:55:45 +00001514 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001515 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001516 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001517 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001518 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001519 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001520 if (Index >= TemplateParams->size())
1521 Index = TemplateParams->size() - 1;
1522 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001523 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001524 }
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Douglas Gregor83314aa2009-07-08 20:55:45 +00001526 // Form the template argument list from the explicitly-specified
1527 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001528 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001529 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001530 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001531
John McCalldf41f182010-10-12 19:40:14 +00001532 // Template argument deduction and the final substitution should be
1533 // done in the context of the templated declaration. Explicit
1534 // argument substitution, on the other hand, needs to happen in the
1535 // calling context.
1536 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1537
Douglas Gregor83314aa2009-07-08 20:55:45 +00001538 // Instantiate the types of each of the function parameters given the
1539 // explicitly-specified template arguments.
1540 for (FunctionDecl::param_iterator P = Function->param_begin(),
1541 PEnd = Function->param_end();
1542 P != PEnd;
1543 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001544 QualType ParamType
1545 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001546 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1547 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001548 if (ParamType.isNull() || Trap.hasErrorOccurred())
1549 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001550
Douglas Gregor83314aa2009-07-08 20:55:45 +00001551 ParamTypes.push_back(ParamType);
1552 }
1553
1554 // If the caller wants a full function type back, instantiate the return
1555 // type and form that function type.
1556 if (FunctionType) {
1557 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001558 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001559 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001560 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001561
1562 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001563 = SubstType(Proto->getResultType(),
1564 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1565 Function->getTypeSpecStartLoc(),
1566 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001567 if (ResultType.isNull() || Trap.hasErrorOccurred())
1568 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001569
1570 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001571 ParamTypes.data(), ParamTypes.size(),
1572 Proto->isVariadic(),
1573 Proto->getTypeQuals(),
1574 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001575 Function->getDeclName(),
1576 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001577 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1578 return TDK_SubstitutionFailure;
1579 }
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Douglas Gregor83314aa2009-07-08 20:55:45 +00001581 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001582 // Trailing template arguments that can be deduced (14.8.2) may be
1583 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001584 // template arguments can be deduced, they may all be omitted; in this
1585 // case, the empty template argument list <> itself may also be omitted.
1586 //
1587 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001588 // set of deduced template arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001589 //
1590 // FIXME: Variadic templates?
Douglas Gregor83314aa2009-07-08 20:55:45 +00001591 Deduced.reserve(TemplateParams->size());
1592 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001593 Deduced.push_back(ExplicitArgumentList->get(I));
1594
Douglas Gregor83314aa2009-07-08 20:55:45 +00001595 return TDK_Success;
1596}
1597
Douglas Gregor02024a92010-03-28 02:42:43 +00001598/// \brief Allocate a TemplateArgumentLoc where all locations have
1599/// been initialized to the given location.
1600///
1601/// \param S The semantic analysis object.
1602///
1603/// \param The template argument we are producing template argument
1604/// location information for.
1605///
1606/// \param NTTPType For a declaration template argument, the type of
1607/// the non-type template parameter that corresponds to this template
1608/// argument.
1609///
1610/// \param Loc The source location to use for the resulting template
1611/// argument.
1612static TemplateArgumentLoc
1613getTrivialTemplateArgumentLoc(Sema &S,
1614 const TemplateArgument &Arg,
1615 QualType NTTPType,
1616 SourceLocation Loc) {
1617 switch (Arg.getKind()) {
1618 case TemplateArgument::Null:
1619 llvm_unreachable("Can't get a NULL template argument here");
1620 break;
1621
1622 case TemplateArgument::Type:
1623 return TemplateArgumentLoc(Arg,
1624 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1625
1626 case TemplateArgument::Declaration: {
1627 Expr *E
1628 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1629 .takeAs<Expr>();
1630 return TemplateArgumentLoc(TemplateArgument(E), E);
1631 }
1632
1633 case TemplateArgument::Integral: {
1634 Expr *E
1635 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
1636 return TemplateArgumentLoc(TemplateArgument(E), E);
1637 }
1638
1639 case TemplateArgument::Template:
1640 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1641
1642 case TemplateArgument::Expression:
1643 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1644
1645 case TemplateArgument::Pack:
Douglas Gregor87dd6972010-12-20 16:52:59 +00001646 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
Douglas Gregor02024a92010-03-28 02:42:43 +00001647 }
1648
1649 return TemplateArgumentLoc();
1650}
1651
Mike Stump1eb44332009-09-09 15:08:12 +00001652/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001653/// checking the deduced template arguments for completeness and forming
1654/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001655Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001656Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001657 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1658 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001659 FunctionDecl *&Specialization,
1660 TemplateDeductionInfo &Info) {
1661 TemplateParameterList *TemplateParams
1662 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001663
Douglas Gregor83314aa2009-07-08 20:55:45 +00001664 // Template argument deduction for function templates in a SFINAE context.
1665 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001666 SFINAETrap Trap(*this);
1667
Douglas Gregor83314aa2009-07-08 20:55:45 +00001668 // Enter a new template instantiation context while we instantiate the
1669 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001670 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001671 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001672 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1673 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001674 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001675 return TDK_InstantiationDepth;
1676
John McCall96db3102010-04-29 01:18:58 +00001677 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001678
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001679 // C++ [temp.deduct.type]p2:
1680 // [...] or if any template argument remains neither deduced nor
1681 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001682 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001683 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001684 // FIXME: Variadic templates. Unwrap argument packs?
Douglas Gregor02024a92010-03-28 02:42:43 +00001685 NamedDecl *Param = FunctionTemplate->getTemplateParameters()->getParam(I);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001686 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001687 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001688 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001689 // argument, because it was explicitly-specified. Just record the
1690 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001691 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001692 continue;
1693 }
1694
1695 // We have deduced this argument, so it still needs to be
1696 // checked and converted.
1697
1698 // First, for a non-type template parameter type that is
1699 // initialized by a declaration, we need the type of the
1700 // corresponding non-type template parameter.
1701 QualType NTTPType;
1702 if (NonTypeTemplateParmDecl *NTTP
1703 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1704 if (Deduced[I].getKind() == TemplateArgument::Declaration) {
1705 NTTPType = NTTP->getType();
1706 if (NTTPType->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001707 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1708 Builder.data(), Builder.size());
Douglas Gregor02024a92010-03-28 02:42:43 +00001709 NTTPType = SubstType(NTTPType,
1710 MultiLevelTemplateArgumentList(TemplateArgs),
1711 NTTP->getLocation(),
1712 NTTP->getDeclName());
1713 if (NTTPType.isNull()) {
1714 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00001715 // FIXME: These template arguments are temporary. Free them!
1716 Info.reset(TemplateArgumentList::CreateCopy(Context,
1717 Builder.data(),
1718 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001719 return TDK_SubstitutionFailure;
1720 }
1721 }
1722 }
1723 }
1724
1725 // Convert the deduced template argument into a template
1726 // argument that we can check, almost as if the user had written
1727 // the template argument explicitly.
1728 TemplateArgumentLoc Arg = getTrivialTemplateArgumentLoc(*this,
1729 Deduced[I],
1730 NTTPType,
Douglas Gregor9b623632010-10-12 23:32:35 +00001731 Info.getLocation());
Douglas Gregor02024a92010-03-28 02:42:43 +00001732
1733 // Check the template argument, converting it as necessary.
1734 if (CheckTemplateArgument(Param, Arg,
1735 FunctionTemplate,
1736 FunctionTemplate->getLocation(),
1737 FunctionTemplate->getSourceRange().getEnd(),
1738 Builder,
1739 Deduced[I].wasDeducedFromArrayBound()
1740 ? CTAK_DeducedFromArrayBound
1741 : CTAK_Deduced)) {
1742 Info.Param = makeTemplateParameter(
1743 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001744 // FIXME: These template arguments are temporary. Free them!
1745 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1746 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001747 return TDK_SubstitutionFailure;
1748 }
1749
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001750 continue;
1751 }
1752
1753 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001754 TemplateArgumentLoc DefArg
1755 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1756 FunctionTemplate->getLocation(),
1757 FunctionTemplate->getSourceRange().getEnd(),
1758 Param,
1759 Builder);
1760
1761 // If there was no default argument, deduction is incomplete.
1762 if (DefArg.getArgument().isNull()) {
1763 Info.Param = makeTemplateParameter(
1764 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1765 return TDK_Incomplete;
1766 }
1767
1768 // Check whether we can actually use the default argument.
1769 if (CheckTemplateArgument(Param, DefArg,
1770 FunctionTemplate,
1771 FunctionTemplate->getLocation(),
1772 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001773 Builder,
1774 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001775 Info.Param = makeTemplateParameter(
1776 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001777 // FIXME: These template arguments are temporary. Free them!
1778 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1779 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001780 return TDK_SubstitutionFailure;
1781 }
1782
1783 // If we get here, we successfully used the default template argument.
1784 }
1785
1786 // Form the template argument list from the deduced template arguments.
1787 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001788 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001789 Info.reset(DeducedArgumentList);
1790
Mike Stump1eb44332009-09-09 15:08:12 +00001791 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001792 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00001793 DeclContext *Owner = FunctionTemplate->getDeclContext();
1794 if (FunctionTemplate->getFriendObjectKind())
1795 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001796 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00001797 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00001798 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001799 if (!Specialization)
1800 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Douglas Gregorf8825742009-09-15 18:26:13 +00001802 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1803 FunctionTemplate->getCanonicalDecl());
1804
Mike Stump1eb44332009-09-09 15:08:12 +00001805 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001806 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00001807 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
1808 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00001809 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Douglas Gregor83314aa2009-07-08 20:55:45 +00001811 // There may have been an error that did not prevent us from constructing a
1812 // declaration. Mark the declaration invalid and return with a substitution
1813 // failure.
1814 if (Trap.hasErrorOccurred()) {
1815 Specialization->setInvalidDecl(true);
1816 return TDK_SubstitutionFailure;
1817 }
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Douglas Gregor9b623632010-10-12 23:32:35 +00001819 // If we suppressed any diagnostics while performing template argument
1820 // deduction, and if we haven't already instantiated this declaration,
1821 // keep track of these diagnostics. They'll be emitted if this specialization
1822 // is actually used.
1823 if (Info.diag_begin() != Info.diag_end()) {
1824 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
1825 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
1826 if (Pos == SuppressedDiagnostics.end())
1827 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
1828 .append(Info.diag_begin(), Info.diag_end());
1829 }
1830
Mike Stump1eb44332009-09-09 15:08:12 +00001831 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001832}
1833
John McCall9c72c602010-08-27 09:08:28 +00001834/// Gets the type of a function for template-argument-deducton
1835/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00001836static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00001837 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00001838 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00001839 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00001840 if (Method->isInstance()) {
1841 // An instance method that's referenced in a form that doesn't
1842 // look like a member pointer is just invalid.
1843 if (!R.HasFormOfMemberPointer) return QualType();
1844
John McCalleff92132010-02-02 02:21:27 +00001845 return Context.getMemberPointerType(Fn->getType(),
1846 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00001847 }
1848
1849 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00001850 return Context.getPointerType(Fn->getType());
1851}
1852
1853/// Apply the deduction rules for overload sets.
1854///
1855/// \return the null type if this argument should be treated as an
1856/// undeduced context
1857static QualType
1858ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001859 Expr *Arg, QualType ParamType,
1860 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00001861
1862 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00001863
John McCall9c72c602010-08-27 09:08:28 +00001864 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00001865
Douglas Gregor75f21af2010-08-30 21:04:23 +00001866 // C++0x [temp.deduct.call]p4
1867 unsigned TDF = 0;
1868 if (ParamWasReference)
1869 TDF |= TDF_ParamWithReferenceType;
1870 if (R.IsAddressOfOperand)
1871 TDF |= TDF_IgnoreQualifiers;
1872
John McCalleff92132010-02-02 02:21:27 +00001873 // If there were explicit template arguments, we can only find
1874 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1875 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00001876 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00001877 // But we can still look for an explicit specialization.
1878 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00001879 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00001880 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00001881 return QualType();
1882 }
1883
1884 // C++0x [temp.deduct.call]p6:
1885 // When P is a function type, pointer to function type, or pointer
1886 // to member function type:
1887
1888 if (!ParamType->isFunctionType() &&
1889 !ParamType->isFunctionPointerType() &&
1890 !ParamType->isMemberFunctionPointerType())
1891 return QualType();
1892
1893 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00001894 for (UnresolvedSetIterator I = Ovl->decls_begin(),
1895 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00001896 NamedDecl *D = (*I)->getUnderlyingDecl();
1897
1898 // - If the argument is an overload set containing one or more
1899 // function templates, the parameter is treated as a
1900 // non-deduced context.
1901 if (isa<FunctionTemplateDecl>(D))
1902 return QualType();
1903
1904 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00001905 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
1906 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00001907
Douglas Gregor75f21af2010-08-30 21:04:23 +00001908 // Function-to-pointer conversion.
1909 if (!ParamWasReference && ParamType->isPointerType() &&
1910 ArgType->isFunctionType())
1911 ArgType = S.Context.getPointerType(ArgType);
1912
John McCalleff92132010-02-02 02:21:27 +00001913 // - If the argument is an overload set (not containing function
1914 // templates), trial argument deduction is attempted using each
1915 // of the members of the set. If deduction succeeds for only one
1916 // of the overload set members, that member is used as the
1917 // argument value for the deduction. If deduction succeeds for
1918 // more than one member of the overload set the parameter is
1919 // treated as a non-deduced context.
1920
1921 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
1922 // Type deduction is done independently for each P/A pair, and
1923 // the deduced template argument values are then combined.
1924 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00001925 llvm::SmallVector<DeducedTemplateArgument, 8>
1926 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00001927 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00001928 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001929 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00001930 ParamType, ArgType,
1931 Info, Deduced, TDF);
1932 if (Result) continue;
1933 if (!Match.isNull()) return QualType();
1934 Match = ArgType;
1935 }
1936
1937 return Match;
1938}
1939
Douglas Gregore53060f2009-06-25 22:08:12 +00001940/// \brief Perform template argument deduction from a function call
1941/// (C++ [temp.deduct.call]).
1942///
1943/// \param FunctionTemplate the function template for which we are performing
1944/// template argument deduction.
1945///
Douglas Gregor48026d22010-01-11 18:40:55 +00001946/// \param ExplicitTemplateArguments the explicit template arguments provided
1947/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001948///
Douglas Gregore53060f2009-06-25 22:08:12 +00001949/// \param Args the function call arguments
1950///
1951/// \param NumArgs the number of arguments in Args
1952///
Douglas Gregor48026d22010-01-11 18:40:55 +00001953/// \param Name the name of the function being called. This is only significant
1954/// when the function template is a conversion function template, in which
1955/// case this routine will also perform template argument deduction based on
1956/// the function to which
1957///
Douglas Gregore53060f2009-06-25 22:08:12 +00001958/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00001959/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00001960/// template argument deduction.
1961///
1962/// \param Info the argument will be updated to provide additional information
1963/// about template argument deduction.
1964///
1965/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001966Sema::TemplateDeductionResult
1967Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00001968 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00001969 Expr **Args, unsigned NumArgs,
1970 FunctionDecl *&Specialization,
1971 TemplateDeductionInfo &Info) {
1972 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001973
Douglas Gregore53060f2009-06-25 22:08:12 +00001974 // C++ [temp.deduct.call]p1:
1975 // Template argument deduction is done by comparing each function template
1976 // parameter type (call it P) with the type of the corresponding argument
1977 // of the call (call it A) as described below.
1978 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001979 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00001980 return TDK_TooFewArguments;
1981 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001982 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001983 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregore53060f2009-06-25 22:08:12 +00001984 if (!Proto->isVariadic())
1985 return TDK_TooManyArguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Douglas Gregore53060f2009-06-25 22:08:12 +00001987 CheckArgs = Function->getNumParams();
1988 }
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001990 // The types of the parameters from which we will perform template argument
1991 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00001992 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00001993 TemplateParameterList *TemplateParams
1994 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00001995 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001996 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00001997 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00001998 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001999 TemplateDeductionResult Result =
2000 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002001 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002002 Deduced,
2003 ParamTypes,
2004 0,
2005 Info);
2006 if (Result)
2007 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002008
2009 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002010 } else {
2011 // Just fill in the parameter types from the function declaration.
2012 for (unsigned I = 0; I != CheckArgs; ++I)
2013 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2014 }
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002016 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002017 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00002018 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002019 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00002020 QualType ArgType = Args[I]->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Douglas Gregor75f21af2010-08-30 21:04:23 +00002022 // C++0x [temp.deduct.call]p3:
2023 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2024 // are ignored for type deduction.
2025 if (ParamType.getCVRQualifiers())
2026 ParamType = ParamType.getLocalUnqualifiedType();
2027 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2028 if (ParamRefType) {
2029 // [...] If P is a reference type, the type referred to by P is used
2030 // for type deduction.
2031 ParamType = ParamRefType->getPointeeType();
2032 }
2033
John McCalleff92132010-02-02 02:21:27 +00002034 // Overload sets usually make this parameter an undeduced
2035 // context, but there are sometimes special circumstances.
2036 if (ArgType == Context.OverloadTy) {
2037 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002038 Args[I], ParamType,
2039 ParamRefType != 0);
John McCalleff92132010-02-02 02:21:27 +00002040 if (ArgType.isNull())
2041 continue;
2042 }
2043
Douglas Gregor75f21af2010-08-30 21:04:23 +00002044 if (ParamRefType) {
2045 // C++0x [temp.deduct.call]p3:
2046 // [...] If P is of the form T&&, where T is a template parameter, and
2047 // the argument is an lvalue, the type A& is used in place of A for
2048 // type deduction.
2049 if (ParamRefType->isRValueReferenceType() &&
2050 ParamRefType->getAs<TemplateTypeParmType>() &&
John McCall7eb0a9e2010-11-24 05:12:34 +00002051 Args[I]->isLValue())
Douglas Gregor75f21af2010-08-30 21:04:23 +00002052 ArgType = Context.getLValueReferenceType(ArgType);
2053 } else {
2054 // C++ [temp.deduct.call]p2:
2055 // If P is not a reference type:
Mike Stump1eb44332009-09-09 15:08:12 +00002056 // - If A is an array type, the pointer type produced by the
2057 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregore53060f2009-06-25 22:08:12 +00002058 // A for type deduction; otherwise,
2059 if (ArgType->isArrayType())
2060 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00002061 // - If A is a function type, the pointer type produced by the
2062 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregore53060f2009-06-25 22:08:12 +00002063 // of A for type deduction; otherwise,
2064 else if (ArgType->isFunctionType())
2065 ArgType = Context.getPointerType(ArgType);
2066 else {
2067 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2068 // type are ignored for type deduction.
2069 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor75f21af2010-08-30 21:04:23 +00002070 if (ArgType.getCVRQualifiers())
2071 ArgType = ArgType.getUnqualifiedType();
Douglas Gregore53060f2009-06-25 22:08:12 +00002072 }
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Douglas Gregore53060f2009-06-25 22:08:12 +00002075 // C++0x [temp.deduct.call]p4:
2076 // In general, the deduction process attempts to find template argument
2077 // values that will make the deduced A identical to A (after the type A
2078 // is transformed as described above). [...]
Douglas Gregor12820292009-09-14 20:00:47 +00002079 unsigned TDF = TDF_SkipNonDependent;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Douglas Gregor508f1c82009-06-26 23:10:12 +00002081 // - If the original P is a reference type, the deduced A (i.e., the
2082 // type referred to by the reference) can be more cv-qualified than
2083 // the transformed A.
Douglas Gregor75f21af2010-08-30 21:04:23 +00002084 if (ParamRefType)
Douglas Gregor508f1c82009-06-26 23:10:12 +00002085 TDF |= TDF_ParamWithReferenceType;
Mike Stump1eb44332009-09-09 15:08:12 +00002086 // - The transformed A can be another pointer or pointer to member
2087 // type that can be converted to the deduced A via a qualification
Douglas Gregor508f1c82009-06-26 23:10:12 +00002088 // conversion (4.4).
John McCalldb0bc472010-08-05 05:30:45 +00002089 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2090 ArgType->isObjCObjectPointerType())
Douglas Gregor508f1c82009-06-26 23:10:12 +00002091 TDF |= TDF_IgnoreQualifiers;
Mike Stump1eb44332009-09-09 15:08:12 +00002092 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor41128772009-06-26 23:27:24 +00002093 // transformed A can be a derived class of the deduced A. Likewise,
2094 // if P is a pointer to a class of the form simple-template-id, the
2095 // transformed A can be a pointer to a derived class pointed to by
2096 // the deduced A.
2097 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002098 (isa<PointerType>(ParamType) &&
Douglas Gregor41128772009-06-26 23:27:24 +00002099 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00002100 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00002101 TDF |= TDF_DerivedClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Douglas Gregore53060f2009-06-25 22:08:12 +00002103 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002104 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00002105 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00002106 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00002107 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002109 // FIXME: we need to check that the deduced A is the same as A,
2110 // modulo the various allowed differences.
Douglas Gregore53060f2009-06-25 22:08:12 +00002111 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002112
Mike Stump1eb44332009-09-09 15:08:12 +00002113 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002114 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002115 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002116}
2117
Douglas Gregor83314aa2009-07-08 20:55:45 +00002118/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002119/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2120/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002121///
2122/// \param FunctionTemplate the function template for which we are performing
2123/// template argument deduction.
2124///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002125/// \param ExplicitTemplateArguments the explicitly-specified template
2126/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002127///
2128/// \param ArgFunctionType the function type that will be used as the
2129/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002130/// function template's function type. This type may be NULL, if there is no
2131/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002132///
2133/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002134/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002135/// template argument deduction.
2136///
2137/// \param Info the argument will be updated to provide additional information
2138/// about template argument deduction.
2139///
2140/// \returns the result of template argument deduction.
2141Sema::TemplateDeductionResult
2142Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002143 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002144 QualType ArgFunctionType,
2145 FunctionDecl *&Specialization,
2146 TemplateDeductionInfo &Info) {
2147 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2148 TemplateParameterList *TemplateParams
2149 = FunctionTemplate->getTemplateParameters();
2150 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Douglas Gregor83314aa2009-07-08 20:55:45 +00002152 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002153 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002154 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2155 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002156 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002157 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002158 if (TemplateDeductionResult Result
2159 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002160 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002161 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002162 &FunctionType, Info))
2163 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002164
2165 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002166 }
2167
2168 // Template argument deduction for function templates in a SFINAE context.
2169 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002170 SFINAETrap Trap(*this);
2171
John McCalleff92132010-02-02 02:21:27 +00002172 Deduced.resize(TemplateParams->size());
2173
Douglas Gregor4b52e252009-12-21 23:17:24 +00002174 if (!ArgFunctionType.isNull()) {
2175 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002176 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002177 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002178 FunctionType, ArgFunctionType, Info,
2179 Deduced, 0))
2180 return Result;
2181 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002182
2183 if (TemplateDeductionResult Result
2184 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2185 NumExplicitlySpecified,
2186 Specialization, Info))
2187 return Result;
2188
2189 // If the requested function type does not match the actual type of the
2190 // specialization, template argument deduction fails.
2191 if (!ArgFunctionType.isNull() &&
2192 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2193 return TDK_NonDeducedMismatch;
2194
2195 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002196}
2197
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002198/// \brief Deduce template arguments for a templated conversion
2199/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2200/// conversion function template specialization.
2201Sema::TemplateDeductionResult
2202Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2203 QualType ToType,
2204 CXXConversionDecl *&Specialization,
2205 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002206 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002207 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2208 QualType FromType = Conv->getConversionType();
2209
2210 // Canonicalize the types for deduction.
2211 QualType P = Context.getCanonicalType(FromType);
2212 QualType A = Context.getCanonicalType(ToType);
2213
2214 // C++0x [temp.deduct.conv]p3:
2215 // If P is a reference type, the type referred to by P is used for
2216 // type deduction.
2217 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2218 P = PRef->getPointeeType();
2219
2220 // C++0x [temp.deduct.conv]p3:
2221 // If A is a reference type, the type referred to by A is used
2222 // for type deduction.
2223 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2224 A = ARef->getPointeeType();
2225 // C++ [temp.deduct.conv]p2:
2226 //
Mike Stump1eb44332009-09-09 15:08:12 +00002227 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002228 else {
2229 assert(!A->isReferenceType() && "Reference types were handled above");
2230
2231 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002232 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002233 // of P for type deduction; otherwise,
2234 if (P->isArrayType())
2235 P = Context.getArrayDecayedType(P);
2236 // - If P is a function type, the pointer type produced by the
2237 // function-to-pointer standard conversion (4.3) is used in
2238 // place of P for type deduction; otherwise,
2239 else if (P->isFunctionType())
2240 P = Context.getPointerType(P);
2241 // - If P is a cv-qualified type, the top level cv-qualifiers of
2242 // P’s type are ignored for type deduction.
2243 else
2244 P = P.getUnqualifiedType();
2245
2246 // C++0x [temp.deduct.conv]p3:
2247 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2248 // type are ignored for type deduction.
2249 A = A.getUnqualifiedType();
2250 }
2251
2252 // Template argument deduction for function templates in a SFINAE context.
2253 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002254 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002255
2256 // C++ [temp.deduct.conv]p1:
2257 // Template argument deduction is done by comparing the return
2258 // type of the template conversion function (call it P) with the
2259 // type that is required as the result of the conversion (call it
2260 // A) as described in 14.8.2.4.
2261 TemplateParameterList *TemplateParams
2262 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002263 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002264 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002265
2266 // C++0x [temp.deduct.conv]p4:
2267 // In general, the deduction process attempts to find template
2268 // argument values that will make the deduced A identical to
2269 // A. However, there are two cases that allow a difference:
2270 unsigned TDF = 0;
2271 // - If the original A is a reference type, A can be more
2272 // cv-qualified than the deduced A (i.e., the type referred to
2273 // by the reference)
2274 if (ToType->isReferenceType())
2275 TDF |= TDF_ParamWithReferenceType;
2276 // - The deduced A can be another pointer or pointer to member
2277 // type that can be converted to A via a qualification
2278 // conversion.
2279 //
2280 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2281 // both P and A are pointers or member pointers. In this case, we
2282 // just ignore cv-qualifiers completely).
2283 if ((P->isPointerType() && A->isPointerType()) ||
2284 (P->isMemberPointerType() && P->isMemberPointerType()))
2285 TDF |= TDF_IgnoreQualifiers;
2286 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002287 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002288 P, A, Info, Deduced, TDF))
2289 return Result;
2290
2291 // FIXME: we need to check that the deduced A is the same as A,
2292 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002294 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002295 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002296 FunctionDecl *Spec = 0;
2297 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002298 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2299 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002300 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2301 return Result;
2302}
2303
Douglas Gregor4b52e252009-12-21 23:17:24 +00002304/// \brief Deduce template arguments for a function template when there is
2305/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2306///
2307/// \param FunctionTemplate the function template for which we are performing
2308/// template argument deduction.
2309///
2310/// \param ExplicitTemplateArguments the explicitly-specified template
2311/// arguments.
2312///
2313/// \param Specialization if template argument deduction was successful,
2314/// this will be set to the function template specialization produced by
2315/// template argument deduction.
2316///
2317/// \param Info the argument will be updated to provide additional information
2318/// about template argument deduction.
2319///
2320/// \returns the result of template argument deduction.
2321Sema::TemplateDeductionResult
2322Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2323 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2324 FunctionDecl *&Specialization,
2325 TemplateDeductionInfo &Info) {
2326 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2327 QualType(), Specialization, Info);
2328}
2329
Douglas Gregor8a514912009-09-14 18:39:43 +00002330/// \brief Stores the result of comparing the qualifiers of two types.
2331enum DeductionQualifierComparison {
2332 NeitherMoreQualified = 0,
2333 ParamMoreQualified,
2334 ArgMoreQualified
2335};
2336
2337/// \brief Deduce the template arguments during partial ordering by comparing
2338/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2339///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002340/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002341///
2342/// \param TemplateParams the template parameters that we are deducing
2343///
2344/// \param ParamIn the parameter type
2345///
2346/// \param ArgIn the argument type
2347///
2348/// \param Info information about the template argument deduction itself
2349///
2350/// \param Deduced the deduced template arguments
2351///
2352/// \returns the result of template argument deduction so far. Note that a
2353/// "success" result means that template argument deduction has not yet failed,
2354/// but it may still fail, later, for other reasons.
2355static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002356DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002357 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002358 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002359 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002360 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2361 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002362 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2363 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002364
2365 // C++0x [temp.deduct.partial]p5:
2366 // Before the partial ordering is done, certain transformations are
2367 // performed on the types used for partial ordering:
2368 // - If P is a reference type, P is replaced by the type referred to.
2369 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002370 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002371 Param = ParamRef->getPointeeType();
2372
2373 // - If A is a reference type, A is replaced by the type referred to.
2374 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002375 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002376 Arg = ArgRef->getPointeeType();
2377
John McCalle27ec8a2009-10-23 23:03:21 +00002378 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002379 // C++0x [temp.deduct.partial]p6:
2380 // If both P and A were reference types (before being replaced with the
2381 // type referred to above), determine which of the two types (if any) is
2382 // more cv-qualified than the other; otherwise the types are considered to
2383 // be equally cv-qualified for partial ordering purposes. The result of this
2384 // determination will be used below.
2385 //
2386 // We save this information for later, using it only when deduction
2387 // succeeds in both directions.
2388 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2389 if (Param.isMoreQualifiedThan(Arg))
2390 QualifierResult = ParamMoreQualified;
2391 else if (Arg.isMoreQualifiedThan(Param))
2392 QualifierResult = ArgMoreQualified;
2393 QualifierComparisons->push_back(QualifierResult);
2394 }
2395
2396 // C++0x [temp.deduct.partial]p7:
2397 // Remove any top-level cv-qualifiers:
2398 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2399 // version of P.
2400 Param = Param.getUnqualifiedType();
2401 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2402 // version of A.
2403 Arg = Arg.getUnqualifiedType();
2404
2405 // C++0x [temp.deduct.partial]p8:
2406 // Using the resulting types P and A the deduction is then done as
2407 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2408 // from the argument template is considered to be at least as specialized
2409 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002410 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002411 Deduced, TDF_None);
2412}
2413
2414static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002415MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2416 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002417 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002418 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002419
2420/// \brief If this is a non-static member function,
2421static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2422 CXXMethodDecl *Method,
2423 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2424 if (Method->isStatic())
2425 return;
2426
2427 // C++ [over.match.funcs]p4:
2428 //
2429 // For non-static member functions, the type of the implicit
2430 // object parameter is
2431 // — "lvalue reference to cv X" for functions declared without a
2432 // ref-qualifier or with the & ref-qualifier
2433 // - "rvalue reference to cv X" for functions declared with the
2434 // && ref-qualifier
2435 //
2436 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2437 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2438 ArgTy = Context.getQualifiedType(ArgTy,
2439 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2440 ArgTy = Context.getLValueReferenceType(ArgTy);
2441 ArgTypes.push_back(ArgTy);
2442}
2443
Douglas Gregor8a514912009-09-14 18:39:43 +00002444/// \brief Determine whether the function template \p FT1 is at least as
2445/// specialized as \p FT2.
2446static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002447 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002448 FunctionTemplateDecl *FT1,
2449 FunctionTemplateDecl *FT2,
2450 TemplatePartialOrderingContext TPOC,
2451 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2452 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2453 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2454 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2455 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2456
2457 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2458 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002459 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002460 Deduced.resize(TemplateParams->size());
2461
2462 // C++0x [temp.deduct.partial]p3:
2463 // The types used to determine the ordering depend on the context in which
2464 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002465 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002466 CXXMethodDecl *Method1 = 0;
2467 CXXMethodDecl *Method2 = 0;
2468 bool IsNonStatic2 = false;
2469 bool IsNonStatic1 = false;
2470 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002471 switch (TPOC) {
2472 case TPOC_Call: {
2473 // - In the context of a function call, the function parameter types are
2474 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002475 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2476 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2477 IsNonStatic1 = Method1 && !Method1->isStatic();
2478 IsNonStatic2 = Method2 && !Method2->isStatic();
2479
2480 // C++0x [temp.func.order]p3:
2481 // [...] If only one of the function templates is a non-static
2482 // member, that function template is considered to have a new
2483 // first parameter inserted in its function parameter list. The
2484 // new parameter is of type "reference to cv A," where cv are
2485 // the cv-qualifiers of the function template (if any) and A is
2486 // the class of which the function template is a member.
2487 //
2488 // C++98/03 doesn't have this provision, so instead we drop the
2489 // first argument of the free function or static member, which
2490 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002491 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002492 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2493 IsNonStatic2 && !IsNonStatic1;
2494 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002495 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2496 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002497 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002498
2499 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002500 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2501 IsNonStatic1 && !IsNonStatic2;
2502 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002503 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2504 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002505 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002506
2507 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002508 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002509 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002510 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002511 Args2[I],
2512 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002513 Info,
2514 Deduced,
2515 QualifierComparisons))
2516 return false;
2517
2518 break;
2519 }
2520
2521 case TPOC_Conversion:
2522 // - In the context of a call to a conversion operator, the return types
2523 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002524 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002525 TemplateParams,
2526 Proto2->getResultType(),
2527 Proto1->getResultType(),
2528 Info,
2529 Deduced,
2530 QualifierComparisons))
2531 return false;
2532 break;
2533
2534 case TPOC_Other:
2535 // - In other contexts (14.6.6.2) the function template’s function type
2536 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002537 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002538 TemplateParams,
2539 FD2->getType(),
2540 FD1->getType(),
2541 Info,
2542 Deduced,
2543 QualifierComparisons))
2544 return false;
2545 break;
2546 }
2547
2548 // C++0x [temp.deduct.partial]p11:
2549 // In most cases, all template parameters must have values in order for
2550 // deduction to succeed, but for partial ordering purposes a template
2551 // parameter may remain without a value provided it is not used in the
2552 // types being used for partial ordering. [ Note: a template parameter used
2553 // in a non-deduced context is considered used. -end note]
2554 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2555 for (; ArgIdx != NumArgs; ++ArgIdx)
2556 if (Deduced[ArgIdx].isNull())
2557 break;
2558
2559 if (ArgIdx == NumArgs) {
2560 // All template arguments were deduced. FT1 is at least as specialized
2561 // as FT2.
2562 return true;
2563 }
2564
Douglas Gregore73bb602009-09-14 21:25:05 +00002565 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002566 llvm::SmallVector<bool, 4> UsedParameters;
2567 UsedParameters.resize(TemplateParams->size());
2568 switch (TPOC) {
2569 case TPOC_Call: {
2570 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002571 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2572 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2573 TemplateParams->getDepth(), UsedParameters);
2574 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002575 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2576 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002577 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002578 break;
2579 }
2580
2581 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002582 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2583 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002584 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002585 break;
2586
2587 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002588 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2589 TemplateParams->getDepth(),
2590 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002591 break;
2592 }
2593
2594 for (; ArgIdx != NumArgs; ++ArgIdx)
2595 // If this argument had no value deduced but was used in one of the types
2596 // used for partial ordering, then deduction fails.
2597 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2598 return false;
2599
2600 return true;
2601}
2602
2603
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002604/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002605/// to the rules of function template partial ordering (C++ [temp.func.order]).
2606///
2607/// \param FT1 the first function template
2608///
2609/// \param FT2 the second function template
2610///
Douglas Gregor8a514912009-09-14 18:39:43 +00002611/// \param TPOC the context in which we are performing partial ordering of
2612/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00002613///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002614/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002615/// template is more specialized, returns NULL.
2616FunctionTemplateDecl *
2617Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2618 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00002619 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002620 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002621 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00002622 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2623 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00002624 &QualifierComparisons);
2625
2626 if (Better1 != Better2) // We have a clear winner
2627 return Better1? FT1 : FT2;
2628
2629 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002630 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002631
2632
2633 // C++0x [temp.deduct.partial]p10:
2634 // If for each type being considered a given template is at least as
2635 // specialized for all types and more specialized for some set of types and
2636 // the other template is not more specialized for any types or is not at
2637 // least as specialized for any types, then the given template is more
2638 // specialized than the other template. Otherwise, neither template is more
2639 // specialized than the other.
2640 Better1 = false;
2641 Better2 = false;
2642 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2643 // C++0x [temp.deduct.partial]p9:
2644 // If, for a given type, deduction succeeds in both directions (i.e., the
2645 // types are identical after the transformations above) and if the type
2646 // from the argument template is more cv-qualified than the type from the
2647 // parameter template (as described above) that type is considered to be
2648 // more specialized than the other. If neither type is more cv-qualified
2649 // than the other then neither type is more specialized than the other.
2650 switch (QualifierComparisons[I]) {
2651 case NeitherMoreQualified:
2652 break;
2653
2654 case ParamMoreQualified:
2655 Better1 = true;
2656 if (Better2)
2657 return 0;
2658 break;
2659
2660 case ArgMoreQualified:
2661 Better2 = true;
2662 if (Better1)
2663 return 0;
2664 break;
2665 }
2666 }
2667
2668 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002669 if (Better1)
2670 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00002671 else if (Better2)
2672 return FT2;
2673 else
2674 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002675}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002676
Douglas Gregord5a423b2009-09-25 18:43:00 +00002677/// \brief Determine if the two templates are equivalent.
2678static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2679 if (T1 == T2)
2680 return true;
2681
2682 if (!T1 || !T2)
2683 return false;
2684
2685 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2686}
2687
2688/// \brief Retrieve the most specialized of the given function template
2689/// specializations.
2690///
John McCallc373d482010-01-27 01:50:18 +00002691/// \param SpecBegin the start iterator of the function template
2692/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002693///
John McCallc373d482010-01-27 01:50:18 +00002694/// \param SpecEnd the end iterator of the function template
2695/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002696///
2697/// \param TPOC the partial ordering context to use to compare the function
2698/// template specializations.
2699///
2700/// \param Loc the location where the ambiguity or no-specializations
2701/// diagnostic should occur.
2702///
2703/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2704/// no matching candidates.
2705///
2706/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2707/// occurs.
2708///
2709/// \param CandidateDiag partial diagnostic used for each function template
2710/// specialization that is a candidate in the ambiguous ordering. One parameter
2711/// in this diagnostic should be unbound, which will correspond to the string
2712/// describing the template arguments for the function template specialization.
2713///
2714/// \param Index if non-NULL and the result of this function is non-nULL,
2715/// receives the index corresponding to the resulting function template
2716/// specialization.
2717///
2718/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00002719/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002720///
2721/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2722/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00002723UnresolvedSetIterator
2724Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
2725 UnresolvedSetIterator SpecEnd,
2726 TemplatePartialOrderingContext TPOC,
2727 SourceLocation Loc,
2728 const PartialDiagnostic &NoneDiag,
2729 const PartialDiagnostic &AmbigDiag,
2730 const PartialDiagnostic &CandidateDiag) {
2731 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00002732 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00002733 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002734 }
2735
John McCallc373d482010-01-27 01:50:18 +00002736 if (SpecBegin + 1 == SpecEnd)
2737 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002738
2739 // Find the function template that is better than all of the templates it
2740 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00002741 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002742 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00002743 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002744 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002745 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
2746 FunctionTemplateDecl *Challenger
2747 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002748 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002749 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002750 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002751 Challenger)) {
2752 Best = I;
2753 BestTemplate = Challenger;
2754 }
2755 }
2756
2757 // Make sure that the "best" function template is more specialized than all
2758 // of the others.
2759 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00002760 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
2761 FunctionTemplateDecl *Challenger
2762 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002763 if (I != Best &&
2764 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002765 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002766 BestTemplate)) {
2767 Ambiguous = true;
2768 break;
2769 }
2770 }
2771
2772 if (!Ambiguous) {
2773 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00002774 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002775 }
2776
2777 // Diagnose the ambiguity.
2778 Diag(Loc, AmbigDiag);
2779
2780 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00002781 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
2782 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00002783 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00002784 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
2785 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00002786
John McCallc373d482010-01-27 01:50:18 +00002787 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002788}
2789
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002790/// \brief Returns the more specialized class template partial specialization
2791/// according to the rules of partial ordering of class template partial
2792/// specializations (C++ [temp.class.order]).
2793///
2794/// \param PS1 the first class template partial specialization
2795///
2796/// \param PS2 the second class template partial specialization
2797///
2798/// \returns the more specialized class template partial specialization. If
2799/// neither partial specialization is more specialized, returns NULL.
2800ClassTemplatePartialSpecializationDecl *
2801Sema::getMoreSpecializedPartialSpecialization(
2802 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00002803 ClassTemplatePartialSpecializationDecl *PS2,
2804 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002805 // C++ [temp.class.order]p1:
2806 // For two class template partial specializations, the first is at least as
2807 // specialized as the second if, given the following rewrite to two
2808 // function templates, the first function template is at least as
2809 // specialized as the second according to the ordering rules for function
2810 // templates (14.6.6.2):
2811 // - the first function template has the same template parameters as the
2812 // first partial specialization and has a single function parameter
2813 // whose type is a class template specialization with the template
2814 // arguments of the first partial specialization, and
2815 // - the second function template has the same template parameters as the
2816 // second partial specialization and has a single function parameter
2817 // whose type is a class template specialization with the template
2818 // arguments of the second partial specialization.
2819 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002820 // Rather than synthesize function templates, we merely perform the
2821 // equivalent partial ordering by performing deduction directly on
2822 // the template arguments of the class template partial
2823 // specializations. This computation is slightly simpler than the
2824 // general problem of function template partial ordering, because
2825 // class template partial specializations are more constrained. We
2826 // know that every template parameter is deducible from the class
2827 // template partial specialization's template arguments, for
2828 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00002829 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00002830 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00002831
2832 QualType PT1 = PS1->getInjectedSpecializationType();
2833 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002834
2835 // Determine whether PS1 is at least as specialized as PS2
2836 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002837 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002838 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002839 PT2,
2840 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002841 Info,
2842 Deduced,
2843 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002844 if (Better1) {
2845 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
2846 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002847 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
2848 PS1->getTemplateArgs(),
2849 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002850 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00002851
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002852 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002853 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002854 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002855 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002856 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002857 PT1,
2858 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002859 Info,
2860 Deduced,
2861 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002862 if (Better2) {
2863 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
2864 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002865 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
2866 PS2->getTemplateArgs(),
2867 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002868 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002869
2870 if (Better1 == Better2)
2871 return 0;
2872
2873 return Better1? PS1 : PS2;
2874}
2875
Mike Stump1eb44332009-09-09 15:08:12 +00002876static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002877MarkUsedTemplateParameters(Sema &SemaRef,
2878 const TemplateArgument &TemplateArg,
2879 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002880 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002881 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002882
Douglas Gregore73bb602009-09-14 21:25:05 +00002883/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002884/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002885static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002886MarkUsedTemplateParameters(Sema &SemaRef,
2887 const Expr *E,
2888 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002889 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002890 llvm::SmallVectorImpl<bool> &Used) {
2891 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2892 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002893 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00002894 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00002895 return;
2896
Mike Stump1eb44332009-09-09 15:08:12 +00002897 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00002898 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2899 if (!NTTP)
2900 return;
2901
Douglas Gregored9c0f92009-10-29 00:04:11 +00002902 if (NTTP->getDepth() == Depth)
2903 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00002904}
2905
Douglas Gregore73bb602009-09-14 21:25:05 +00002906/// \brief Mark the template parameters that are used by the given
2907/// nested name specifier.
2908static void
2909MarkUsedTemplateParameters(Sema &SemaRef,
2910 NestedNameSpecifier *NNS,
2911 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002912 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002913 llvm::SmallVectorImpl<bool> &Used) {
2914 if (!NNS)
2915 return;
2916
Douglas Gregored9c0f92009-10-29 00:04:11 +00002917 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
2918 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002919 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002920 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002921}
2922
2923/// \brief Mark the template parameters that are used by the given
2924/// template name.
2925static void
2926MarkUsedTemplateParameters(Sema &SemaRef,
2927 TemplateName Name,
2928 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002929 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002930 llvm::SmallVectorImpl<bool> &Used) {
2931 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2932 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00002933 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
2934 if (TTP->getDepth() == Depth)
2935 Used[TTP->getIndex()] = true;
2936 }
Douglas Gregore73bb602009-09-14 21:25:05 +00002937 return;
2938 }
2939
Douglas Gregor788cd062009-11-11 01:00:40 +00002940 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
2941 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
2942 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002943 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00002944 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
2945 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002946}
2947
2948/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002949/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00002950static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002951MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2952 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002953 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002954 llvm::SmallVectorImpl<bool> &Used) {
2955 if (T.isNull())
2956 return;
2957
Douglas Gregor031a5882009-06-13 00:26:55 +00002958 // Non-dependent types have nothing deducible
2959 if (!T->isDependentType())
2960 return;
2961
2962 T = SemaRef.Context.getCanonicalType(T);
2963 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00002964 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00002965 MarkUsedTemplateParameters(SemaRef,
2966 cast<PointerType>(T)->getPointeeType(),
2967 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002968 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002969 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002970 break;
2971
2972 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00002973 MarkUsedTemplateParameters(SemaRef,
2974 cast<BlockPointerType>(T)->getPointeeType(),
2975 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002976 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002977 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002978 break;
2979
2980 case Type::LValueReference:
2981 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00002982 MarkUsedTemplateParameters(SemaRef,
2983 cast<ReferenceType>(T)->getPointeeType(),
2984 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002985 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002986 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002987 break;
2988
2989 case Type::MemberPointer: {
2990 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00002991 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002992 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002993 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002994 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002995 break;
2996 }
2997
2998 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00002999 MarkUsedTemplateParameters(SemaRef,
3000 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003001 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003002 // Fall through to check the element type
3003
3004 case Type::ConstantArray:
3005 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003006 MarkUsedTemplateParameters(SemaRef,
3007 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003008 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003009 break;
3010
3011 case Type::Vector:
3012 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003013 MarkUsedTemplateParameters(SemaRef,
3014 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003015 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003016 break;
3017
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003018 case Type::DependentSizedExtVector: {
3019 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003020 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003021 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003022 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003023 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003024 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003025 break;
3026 }
3027
Douglas Gregor031a5882009-06-13 00:26:55 +00003028 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003029 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003030 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003031 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003032 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003033 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003034 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003035 break;
3036 }
3037
Douglas Gregored9c0f92009-10-29 00:04:11 +00003038 case Type::TemplateTypeParm: {
3039 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3040 if (TTP->getDepth() == Depth)
3041 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003042 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003043 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003044
John McCall31f17ec2010-04-27 00:57:59 +00003045 case Type::InjectedClassName:
3046 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3047 // fall through
3048
Douglas Gregor031a5882009-06-13 00:26:55 +00003049 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003050 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003051 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003052 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003053 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003054 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003055 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3056 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003057 break;
3058 }
3059
Douglas Gregore73bb602009-09-14 21:25:05 +00003060 case Type::Complex:
3061 if (!OnlyDeduced)
3062 MarkUsedTemplateParameters(SemaRef,
3063 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003064 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003065 break;
3066
Douglas Gregor4714c122010-03-31 17:34:00 +00003067 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003068 if (!OnlyDeduced)
3069 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003070 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003071 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003072 break;
3073
John McCall33500952010-06-11 00:33:02 +00003074 case Type::DependentTemplateSpecialization: {
3075 const DependentTemplateSpecializationType *Spec
3076 = cast<DependentTemplateSpecializationType>(T);
3077 if (!OnlyDeduced)
3078 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3079 OnlyDeduced, Depth, Used);
3080 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3081 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3082 Used);
3083 break;
3084 }
3085
John McCallad5e7382010-03-01 23:49:17 +00003086 case Type::TypeOf:
3087 if (!OnlyDeduced)
3088 MarkUsedTemplateParameters(SemaRef,
3089 cast<TypeOfType>(T)->getUnderlyingType(),
3090 OnlyDeduced, Depth, Used);
3091 break;
3092
3093 case Type::TypeOfExpr:
3094 if (!OnlyDeduced)
3095 MarkUsedTemplateParameters(SemaRef,
3096 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3097 OnlyDeduced, Depth, Used);
3098 break;
3099
3100 case Type::Decltype:
3101 if (!OnlyDeduced)
3102 MarkUsedTemplateParameters(SemaRef,
3103 cast<DecltypeType>(T)->getUnderlyingExpr(),
3104 OnlyDeduced, Depth, Used);
3105 break;
3106
Douglas Gregor7536dd52010-12-20 02:24:11 +00003107 case Type::PackExpansion:
3108 MarkUsedTemplateParameters(SemaRef,
3109 cast<PackExpansionType>(T)->getPattern(),
3110 OnlyDeduced, Depth, Used);
3111 break;
3112
Douglas Gregore73bb602009-09-14 21:25:05 +00003113 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003114 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003115 case Type::VariableArray:
3116 case Type::FunctionNoProto:
3117 case Type::Record:
3118 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003119 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003120 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003121 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003122 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003123#define TYPE(Class, Base)
3124#define ABSTRACT_TYPE(Class, Base)
3125#define DEPENDENT_TYPE(Class, Base)
3126#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3127#include "clang/AST/TypeNodes.def"
3128 break;
3129 }
3130}
3131
Douglas Gregore73bb602009-09-14 21:25:05 +00003132/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003133/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003134static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003135MarkUsedTemplateParameters(Sema &SemaRef,
3136 const TemplateArgument &TemplateArg,
3137 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003138 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003139 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003140 switch (TemplateArg.getKind()) {
3141 case TemplateArgument::Null:
3142 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003143 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003144 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Douglas Gregor031a5882009-06-13 00:26:55 +00003146 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003147 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003148 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003149 break;
3150
Douglas Gregor788cd062009-11-11 01:00:40 +00003151 case TemplateArgument::Template:
3152 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsTemplate(),
3153 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003154 break;
3155
3156 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003157 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003158 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003159 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003160
Anders Carlssond01b1da2009-06-15 17:04:53 +00003161 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003162 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3163 PEnd = TemplateArg.pack_end();
3164 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003165 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003166 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003167 }
3168}
3169
3170/// \brief Mark the template parameters can be deduced by the given
3171/// template argument list.
3172///
3173/// \param TemplateArgs the template argument list from which template
3174/// parameters will be deduced.
3175///
3176/// \param Deduced a bit vector whose elements will be set to \c true
3177/// to indicate when the corresponding template parameter will be
3178/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003179void
Douglas Gregore73bb602009-09-14 21:25:05 +00003180Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003181 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003182 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003183 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003184 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3185 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003186}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003187
3188/// \brief Marks all of the template parameters that will be deduced by a
3189/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003190void
3191Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3192 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003193 TemplateParameterList *TemplateParams
3194 = FunctionTemplate->getTemplateParameters();
3195 Deduced.clear();
3196 Deduced.resize(TemplateParams->size());
3197
3198 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3199 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3200 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003201 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003202}