blob: 883244731415954a3a22008f9dde31f44a69b5d0 [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,
Douglas Gregor603cfb42011-01-05 23:12:31 +000090 QualType Param,
91 QualType Arg,
92 TemplateDeductionInfo &Info,
93 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 unsigned TDF);
95
96static Sema::TemplateDeductionResult
97DeduceTemplateArguments(Sema &S,
98 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +000099 const TemplateArgument *Params, unsigned NumParams,
100 const TemplateArgument *Args, unsigned NumArgs,
101 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000102 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
103 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000104
Douglas Gregor199d9912009-06-05 00:53:49 +0000105/// \brief If the given expression is of a form that permits the deduction
106/// of a non-type template parameter, return the declaration of that
107/// non-type template parameter.
108static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
109 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
110 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Douglas Gregor199d9912009-06-05 00:53:49 +0000112 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
113 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Douglas Gregor199d9912009-06-05 00:53:49 +0000115 return 0;
116}
117
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000118/// \brief Determine whether two declaration pointers refer to the same
119/// declaration.
120static bool isSameDeclaration(Decl *X, Decl *Y) {
121 if (!X || !Y)
122 return !X && !Y;
123
124 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
125 X = NX->getUnderlyingDecl();
126 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
127 Y = NY->getUnderlyingDecl();
128
129 return X->getCanonicalDecl() == Y->getCanonicalDecl();
130}
131
132/// \brief Verify that the given, deduced template arguments are compatible.
133///
134/// \returns The deduced template argument, or a NULL template argument if
135/// the deduced template arguments were incompatible.
136static DeducedTemplateArgument
137checkDeducedTemplateArguments(ASTContext &Context,
138 const DeducedTemplateArgument &X,
139 const DeducedTemplateArgument &Y) {
140 // We have no deduction for one or both of the arguments; they're compatible.
141 if (X.isNull())
142 return Y;
143 if (Y.isNull())
144 return X;
145
146 switch (X.getKind()) {
147 case TemplateArgument::Null:
148 llvm_unreachable("Non-deduced template arguments handled above");
149
150 case TemplateArgument::Type:
151 // If two template type arguments have the same type, they're compatible.
152 if (Y.getKind() == TemplateArgument::Type &&
153 Context.hasSameType(X.getAsType(), Y.getAsType()))
154 return X;
155
156 return DeducedTemplateArgument();
157
158 case TemplateArgument::Integral:
159 // If we deduced a constant in one case and either a dependent expression or
160 // declaration in another case, keep the integral constant.
161 // If both are integral constants with the same value, keep that value.
162 if (Y.getKind() == TemplateArgument::Expression ||
163 Y.getKind() == TemplateArgument::Declaration ||
164 (Y.getKind() == TemplateArgument::Integral &&
165 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
166 return DeducedTemplateArgument(X,
167 X.wasDeducedFromArrayBound() &&
168 Y.wasDeducedFromArrayBound());
169
170 // All other combinations are incompatible.
171 return DeducedTemplateArgument();
172
173 case TemplateArgument::Template:
174 if (Y.getKind() == TemplateArgument::Template &&
175 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
176 return X;
177
178 // All other combinations are incompatible.
179 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000180
181 case TemplateArgument::TemplateExpansion:
182 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
183 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
184 Y.getAsTemplateOrTemplatePattern()))
185 return X;
186
187 // All other combinations are incompatible.
188 return DeducedTemplateArgument();
189
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000190 case TemplateArgument::Expression:
191 // If we deduced a dependent expression in one case and either an integral
192 // constant or a declaration in another case, keep the integral constant
193 // or declaration.
194 if (Y.getKind() == TemplateArgument::Integral ||
195 Y.getKind() == TemplateArgument::Declaration)
196 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
197 Y.wasDeducedFromArrayBound());
198
199 if (Y.getKind() == TemplateArgument::Expression) {
200 // Compare the expressions for equality
201 llvm::FoldingSetNodeID ID1, ID2;
202 X.getAsExpr()->Profile(ID1, Context, true);
203 Y.getAsExpr()->Profile(ID2, Context, true);
204 if (ID1 == ID2)
205 return X;
206 }
207
208 // All other combinations are incompatible.
209 return DeducedTemplateArgument();
210
211 case TemplateArgument::Declaration:
212 // If we deduced a declaration and a dependent expression, keep the
213 // declaration.
214 if (Y.getKind() == TemplateArgument::Expression)
215 return X;
216
217 // If we deduced a declaration and an integral constant, keep the
218 // integral constant.
219 if (Y.getKind() == TemplateArgument::Integral)
220 return Y;
221
222 // If we deduced two declarations, make sure they they refer to the
223 // same declaration.
224 if (Y.getKind() == TemplateArgument::Declaration &&
225 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
226 return X;
227
228 // All other combinations are incompatible.
229 return DeducedTemplateArgument();
230
231 case TemplateArgument::Pack:
232 if (Y.getKind() != TemplateArgument::Pack ||
233 X.pack_size() != Y.pack_size())
234 return DeducedTemplateArgument();
235
236 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
237 XAEnd = X.pack_end(),
238 YA = Y.pack_begin();
239 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000240 if (checkDeducedTemplateArguments(Context,
241 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
242 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
243 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000244 return DeducedTemplateArgument();
245 }
246
247 return X;
248 }
249
250 return DeducedTemplateArgument();
251}
252
Mike Stump1eb44332009-09-09 15:08:12 +0000253/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000254/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000255static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000256DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000257 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000258 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000259 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000260 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000261 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000262 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000263 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000265 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
266 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
267 Deduced[NTTP->getIndex()],
268 NewDeduced);
269 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000270 Info.Param = NTTP;
271 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000272 Info.SecondArg = NewDeduced;
273 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000274 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000275
276 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000277 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000281/// from the given type- or value-dependent expression.
282///
283/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000284static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000285DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000286 NonTypeTemplateParmDecl *NTTP,
287 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000288 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000289 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000290 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000291 "Cannot deduce non-type template argument with depth > 0");
292 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
293 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000295 DeducedTemplateArgument NewDeduced(Value);
296 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
297 Deduced[NTTP->getIndex()],
298 NewDeduced);
299
300 if (Result.isNull()) {
301 Info.Param = NTTP;
302 Info.FirstArg = Deduced[NTTP->getIndex()];
303 Info.SecondArg = NewDeduced;
304 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000305 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000306
307 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000308 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000309}
310
Douglas Gregor15755cb2009-11-13 23:45:44 +0000311/// \brief Deduce the value of the given non-type template parameter
312/// from the given declaration.
313///
314/// \returns true if deduction succeeded, false otherwise.
315static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000316DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000317 NonTypeTemplateParmDecl *NTTP,
318 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000319 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000320 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000321 assert(NTTP->getDepth() == 0 &&
322 "Cannot deduce non-type template argument with depth > 0");
323
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000324 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
325 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
326 Deduced[NTTP->getIndex()],
327 NewDeduced);
328 if (Result.isNull()) {
329 Info.Param = NTTP;
330 Info.FirstArg = Deduced[NTTP->getIndex()];
331 Info.SecondArg = NewDeduced;
332 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000333 }
334
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000335 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000336 return Sema::TDK_Success;
337}
338
Douglas Gregorf67875d2009-06-12 18:26:56 +0000339static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000340DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000341 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000342 TemplateName Param,
343 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000344 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000345 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000346 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000347 if (!ParamDecl) {
348 // The parameter type is dependent and is not a template template parameter,
349 // so there is nothing that we can deduce.
350 return Sema::TDK_Success;
351 }
352
353 if (TemplateTemplateParmDecl *TempParam
354 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000355 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
356 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
357 Deduced[TempParam->getIndex()],
358 NewDeduced);
359 if (Result.isNull()) {
360 Info.Param = TempParam;
361 Info.FirstArg = Deduced[TempParam->getIndex()];
362 Info.SecondArg = NewDeduced;
363 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000364 }
365
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000366 Deduced[TempParam->getIndex()] = Result;
367 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000368 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000369
370 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000371 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000372 return Sema::TDK_Success;
373
374 // Mismatch of non-dependent template parameter to argument.
375 Info.FirstArg = TemplateArgument(Param);
376 Info.SecondArg = TemplateArgument(Arg);
377 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000378}
379
Mike Stump1eb44332009-09-09 15:08:12 +0000380/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000381/// type (which is a template-id) with the template argument type.
382///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000383/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000384///
385/// \param TemplateParams the template parameters that we are deducing
386///
387/// \param Param the parameter type
388///
389/// \param Arg the argument type
390///
391/// \param Info information about the template argument deduction itself
392///
393/// \param Deduced the deduced template arguments
394///
395/// \returns the result of template argument deduction so far. Note that a
396/// "success" result means that template argument deduction has not yet failed,
397/// but it may still fail, later, for other reasons.
398static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000399DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000400 TemplateParameterList *TemplateParams,
401 const TemplateSpecializationType *Param,
402 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000403 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000404 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000405 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000407 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000408 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000409 = dyn_cast<TemplateSpecializationType>(Arg)) {
410 // Perform template argument deduction for the template name.
411 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000412 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000413 Param->getTemplateName(),
414 SpecArg->getTemplateName(),
415 Info, Deduced))
416 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000419 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000420 // argument. Ignore any missing/extra arguments, since they could be
421 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000422 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000423 Param->getArgs(), Param->getNumArgs(),
424 SpecArg->getArgs(), SpecArg->getNumArgs(),
425 Info, Deduced,
426 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000429 // If the argument type is a class template specialization, we
430 // perform template argument deduction using its template
431 // arguments.
432 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
433 if (!RecordArg)
434 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
436 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000437 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
438 if (!SpecArg)
439 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000441 // Perform template argument deduction for the template name.
442 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000443 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000444 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000445 Param->getTemplateName(),
446 TemplateName(SpecArg->getSpecializedTemplate()),
447 Info, Deduced))
448 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Douglas Gregor20a55e22010-12-22 18:17:10 +0000450 // Perform template argument deduction for the template arguments.
451 return DeduceTemplateArguments(S, TemplateParams,
452 Param->getArgs(), Param->getNumArgs(),
453 SpecArg->getTemplateArgs().data(),
454 SpecArg->getTemplateArgs().size(),
455 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000456}
457
John McCallcd05e812010-08-28 22:14:41 +0000458/// \brief Determines whether the given type is an opaque type that
459/// might be more qualified when instantiated.
460static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
461 switch (T->getTypeClass()) {
462 case Type::TypeOfExpr:
463 case Type::TypeOf:
464 case Type::DependentName:
465 case Type::Decltype:
466 case Type::UnresolvedUsing:
467 return true;
468
469 case Type::ConstantArray:
470 case Type::IncompleteArray:
471 case Type::VariableArray:
472 case Type::DependentSizedArray:
473 return IsPossiblyOpaquelyQualifiedType(
474 cast<ArrayType>(T)->getElementType());
475
476 default:
477 return false;
478 }
479}
480
Douglas Gregor603cfb42011-01-05 23:12:31 +0000481/// \brief Retrieve the depth and index of an unexpanded parameter pack.
482static std::pair<unsigned, unsigned>
483getDepthAndIndex(UnexpandedParameterPack UPP) {
484 if (const TemplateTypeParmType *TTP
485 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
486 return std::make_pair(TTP->getDepth(), TTP->getIndex());
487
488 NamedDecl *ND = UPP.first.get<NamedDecl *>();
489 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
490 return std::make_pair(TTP->getDepth(), TTP->getIndex());
491
492 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
493 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
494
495 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
496 return std::make_pair(TTP->getDepth(), TTP->getIndex());
497}
498
499/// \brief Helper function to build a TemplateParameter when we don't
500/// know its type statically.
501static TemplateParameter makeTemplateParameter(Decl *D) {
502 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
503 return TemplateParameter(TTP);
504 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
505 return TemplateParameter(NTTP);
506
507 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
508}
509
510/// \brief Deduce the template arguments by comparing the list of parameter
511/// types to the list of argument types, as in the parameter-type-lists of
512/// function types (C++ [temp.deduct.type]p10).
513///
514/// \param S The semantic analysis object within which we are deducing
515///
516/// \param TemplateParams The template parameters that we are deducing
517///
518/// \param Params The list of parameter types
519///
520/// \param NumParams The number of types in \c Params
521///
522/// \param Args The list of argument types
523///
524/// \param NumArgs The number of types in \c Args
525///
526/// \param Info information about the template argument deduction itself
527///
528/// \param Deduced the deduced template arguments
529///
530/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
531/// how template argument deduction is performed.
532///
533/// \returns the result of template argument deduction so far. Note that a
534/// "success" result means that template argument deduction has not yet failed,
535/// but it may still fail, later, for other reasons.
536static Sema::TemplateDeductionResult
537DeduceTemplateArguments(Sema &S,
538 TemplateParameterList *TemplateParams,
539 const QualType *Params, unsigned NumParams,
540 const QualType *Args, unsigned NumArgs,
541 TemplateDeductionInfo &Info,
542 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
543 unsigned TDF) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000544 // Fast-path check to see if we have too many/too few arguments.
545 if (NumParams != NumArgs &&
546 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
547 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
548 return NumArgs < NumParams ? Sema::TDK_TooFewArguments
549 : Sema::TDK_TooManyArguments;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000550
551 // C++0x [temp.deduct.type]p10:
552 // Similarly, if P has a form that contains (T), then each parameter type
553 // Pi of the respective parameter-type- list of P is compared with the
554 // corresponding parameter type Ai of the corresponding parameter-type-list
555 // of A. [...]
556 unsigned ArgIdx = 0, ParamIdx = 0;
557 for (; ParamIdx != NumParams; ++ParamIdx) {
558 // Check argument types.
559 const PackExpansionType *Expansion
560 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
561 if (!Expansion) {
562 // Simple case: compare the parameter and argument types at this point.
563
564 // Make sure we have an argument.
565 if (ArgIdx >= NumArgs)
566 return Sema::TDK_TooFewArguments;
567
568 if (Sema::TemplateDeductionResult Result
569 = DeduceTemplateArguments(S, TemplateParams,
570 Params[ParamIdx],
571 Args[ArgIdx],
572 Info, Deduced, TDF))
573 return Result;
574
575 ++ArgIdx;
576 continue;
577 }
578
579 // C++0x [temp.deduct.type]p10:
580 // If the parameter-declaration corresponding to Pi is a function
581 // parameter pack, then the type of its declarator- id is compared with
582 // each remaining parameter type in the parameter-type-list of A. Each
583 // comparison deduces template arguments for subsequent positions in the
584 // template parameter packs expanded by the function parameter pack.
585
586 // Compute the set of template parameter indices that correspond to
587 // parameter packs expanded by the pack expansion.
588 llvm::SmallVector<unsigned, 2> PackIndices;
589 QualType Pattern = Expansion->getPattern();
590 {
591 llvm::BitVector SawIndices(TemplateParams->size());
592 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
593 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
594 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
595 unsigned Depth, Index;
596 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
597 if (Depth == 0 && !SawIndices[Index]) {
598 SawIndices[Index] = true;
599 PackIndices.push_back(Index);
600 }
601 }
602 }
603 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
604
605 // Save the deduced template arguments for each parameter pack expanded
606 // by this pack expansion, then clear out the deduction.
607 llvm::SmallVector<DeducedTemplateArgument, 2>
608 SavedPacks(PackIndices.size());
609 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
610 SavedPacks[I] = Deduced[PackIndices[I]];
611 Deduced[PackIndices[I]] = DeducedTemplateArgument();
612 }
613
614 // Keep track of the deduced template arguments for each parameter pack
615 // expanded by this pack expansion (the outer index) and for each
616 // template argument (the inner SmallVectors).
617 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
618 NewlyDeducedPacks(PackIndices.size());
619 bool HasAnyArguments = false;
620 for (; ArgIdx < NumArgs; ++ArgIdx) {
621 HasAnyArguments = true;
622
623 // Deduce template arguments from the pattern.
624 if (Sema::TemplateDeductionResult Result
625 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
626 Info, Deduced))
627 return Result;
628
629 // Capture the deduced template arguments for each parameter pack expanded
630 // by this pack expansion, add them to the list of arguments we've deduced
631 // for that pack, then clear out the deduced argument.
632 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
633 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
634 if (!DeducedArg.isNull()) {
635 NewlyDeducedPacks[I].push_back(DeducedArg);
636 DeducedArg = DeducedTemplateArgument();
637 }
638 }
639 }
640
641 // Build argument packs for each of the parameter packs expanded by this
642 // pack expansion.
643 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
644 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
645 // We were not able to deduce anything for this parameter pack,
646 // so just restore the saved argument pack.
647 Deduced[PackIndices[I]] = SavedPacks[I];
648 continue;
649 }
650
651 DeducedTemplateArgument NewPack;
652
653 if (NewlyDeducedPacks[I].empty()) {
654 // If we deduced an empty argument pack, create it now.
655 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
656 } else {
657 TemplateArgument *ArgumentPack
658 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
659 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
660 ArgumentPack);
661 NewPack
662 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
663 NewlyDeducedPacks[I].size()),
664 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
665 }
666
667 DeducedTemplateArgument Result
668 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
669 if (Result.isNull()) {
670 Info.Param
671 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
672 Info.FirstArg = SavedPacks[I];
673 Info.SecondArg = NewPack;
674 return Sema::TDK_Inconsistent;
675 }
676
677 Deduced[PackIndices[I]] = Result;
678 }
679 }
680
681 // Make sure we don't have any extra arguments.
682 if (ArgIdx < NumArgs)
683 return Sema::TDK_TooManyArguments;
684
685 return Sema::TDK_Success;
686}
687
Douglas Gregor500d3312009-06-26 18:27:22 +0000688/// \brief Deduce the template arguments by comparing the parameter type and
689/// the argument type (C++ [temp.deduct.type]).
690///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000691/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000692///
693/// \param TemplateParams the template parameters that we are deducing
694///
695/// \param ParamIn the parameter type
696///
697/// \param ArgIn the argument type
698///
699/// \param Info information about the template argument deduction itself
700///
701/// \param Deduced the deduced template arguments
702///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000703/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000704/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000705///
706/// \returns the result of template argument deduction so far. Note that a
707/// "success" result means that template argument deduction has not yet failed,
708/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000709static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000710DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000711 TemplateParameterList *TemplateParams,
712 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000713 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000714 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000715 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000716 // We only want to look at the canonical types, since typedefs and
717 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000718 QualType Param = S.Context.getCanonicalType(ParamIn);
719 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000720
Douglas Gregor500d3312009-06-26 18:27:22 +0000721 // C++0x [temp.deduct.call]p4 bullet 1:
722 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000723 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000724 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000725 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000726 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000727 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000728 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
729 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000730 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000731 }
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000733 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000734 if (!Param->isDependentType()) {
735 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
736
737 return Sema::TDK_NonDeducedMismatch;
738 }
739
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000740 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000741 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000742
Douglas Gregor199d9912009-06-05 00:53:49 +0000743 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000744 // A template type argument T, a template template argument TT or a
745 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000746 // the following forms:
747 //
748 // T
749 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000750 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000751 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000752 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000753 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000755 // If the argument type is an array type, move the qualifiers up to the
756 // top level, so they can be matched with the qualifiers on the parameter.
757 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000758 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000759 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000760 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000761 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000762 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000763 RecanonicalizeArg = true;
764 }
765 }
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000767 // The argument type can not be less qualified than the parameter
768 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000769 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000770 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000771 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000772 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000773 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000774 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000775
776 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000777 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000778 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000779
780 // local manipulation is okay because it's canonical
781 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000782 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000783 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000785 DeducedTemplateArgument NewDeduced(DeducedType);
786 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
787 Deduced[Index],
788 NewDeduced);
789 if (Result.isNull()) {
790 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
791 Info.FirstArg = Deduced[Index];
792 Info.SecondArg = NewDeduced;
793 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000794 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000795
796 Deduced[Index] = Result;
797 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000798 }
799
Douglas Gregorf67875d2009-06-12 18:26:56 +0000800 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000801 Info.FirstArg = TemplateArgument(ParamIn);
802 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000803
Douglas Gregor508f1c82009-06-26 23:10:12 +0000804 // Check the cv-qualifiers on the parameter and argument types.
805 if (!(TDF & TDF_IgnoreQualifiers)) {
806 if (TDF & TDF_ParamWithReferenceType) {
807 if (Param.isMoreQualifiedThan(Arg))
808 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000809 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000810 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000811 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000812 }
813 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000814
Douglas Gregord560d502009-06-04 00:21:18 +0000815 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000816 // No deduction possible for these types
817 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000818 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Douglas Gregor199d9912009-06-05 00:53:49 +0000820 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000821 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000822 QualType PointeeType;
823 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
824 PointeeType = PointerArg->getPointeeType();
825 } else if (const ObjCObjectPointerType *PointerArg
826 = Arg->getAs<ObjCObjectPointerType>()) {
827 PointeeType = PointerArg->getPointeeType();
828 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000829 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Douglas Gregor41128772009-06-26 23:27:24 +0000832 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000833 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000834 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000835 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000836 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Douglas Gregor199d9912009-06-05 00:53:49 +0000839 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000840 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000841 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000842 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000843 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000845 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000846 cast<LValueReferenceType>(Param)->getPointeeType(),
847 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000848 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000849 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000850
Douglas Gregor199d9912009-06-05 00:53:49 +0000851 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000852 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000853 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000854 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000855 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000857 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000858 cast<RValueReferenceType>(Param)->getPointeeType(),
859 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000860 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregor199d9912009-06-05 00:53:49 +0000863 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000864 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000865 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000866 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000867 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000868 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000869
John McCalle4f26e52010-08-19 00:20:19 +0000870 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000871 return DeduceTemplateArguments(S, TemplateParams,
872 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000873 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000874 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000875 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000876
877 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000878 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000879 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000880 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000881 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000882 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000883
884 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000885 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000886 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000887 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
John McCalle4f26e52010-08-19 00:20:19 +0000889 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000890 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000891 ConstantArrayParm->getElementType(),
892 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000893 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000894 }
895
Douglas Gregor199d9912009-06-05 00:53:49 +0000896 // type [i]
897 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000898 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000899 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000900 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000901
John McCalle4f26e52010-08-19 00:20:19 +0000902 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
903
Douglas Gregor199d9912009-06-05 00:53:49 +0000904 // Check the element type of the arrays
905 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000906 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000907 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000908 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000909 DependentArrayParm->getElementType(),
910 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000911 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000912 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Douglas Gregor199d9912009-06-05 00:53:49 +0000914 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000915 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000916 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
917 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000918 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
920 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000921 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000922 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000923 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000924 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000925 = dyn_cast<ConstantArrayType>(ArrayArg)) {
926 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000927 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
928 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000929 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000930 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000931 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000932 if (const DependentSizedArrayType *DependentArrayArg
933 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000934 if (DependentArrayArg->getSizeExpr())
935 return DeduceNonTypeTemplateArgument(S, NTTP,
936 DependentArrayArg->getSizeExpr(),
937 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Douglas Gregor199d9912009-06-05 00:53:49 +0000939 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000940 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
943 // type(*)(T)
944 // T(*)()
945 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000946 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000947 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000948 dyn_cast<FunctionProtoType>(Arg);
949 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000950 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
952 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000953 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000954
Mike Stump1eb44332009-09-09 15:08:12 +0000955 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000956 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000957 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000959 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000960 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000961
Anders Carlssona27fad52009-06-08 15:19:08 +0000962 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000963 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000964 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000965 FunctionProtoParam->getResultType(),
966 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000967 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000968 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Douglas Gregor603cfb42011-01-05 23:12:31 +0000970 return DeduceTemplateArguments(S, TemplateParams,
971 FunctionProtoParam->arg_type_begin(),
972 FunctionProtoParam->getNumArgs(),
973 FunctionProtoArg->arg_type_begin(),
974 FunctionProtoArg->getNumArgs(),
975 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +0000976 }
Mike Stump1eb44332009-09-09 15:08:12 +0000977
John McCall3cb0ebd2010-03-10 03:28:59 +0000978 case Type::InjectedClassName: {
979 // Treat a template's injected-class-name as if the template
980 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000981 Param = cast<InjectedClassNameType>(Param)
982 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000983 assert(isa<TemplateSpecializationType>(Param) &&
984 "injected class name is not a template specialization type");
985 // fall through
986 }
987
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000988 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000989 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000990 // TT<T>
991 // TT<i>
992 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000993 case Type::TemplateSpecialization: {
994 const TemplateSpecializationType *SpecParam
995 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000997 // Try to deduce template arguments from the template-id.
998 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000999 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001000 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001002 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001003 // C++ [temp.deduct.call]p3b3:
1004 // If P is a class, and P has the form template-id, then A can be a
1005 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001006 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001007 // class pointed to by the deduced A.
1008 //
1009 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001010 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001011 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001012 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1013 // We cannot inspect base classes as part of deduction when the type
1014 // is incomplete, so either instantiate any templates necessary to
1015 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001016 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001017 return Result;
1018
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001019 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001020 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001021 // ToVisit is our stack of records that we still need to visit.
1022 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1023 llvm::SmallVector<const RecordType *, 8> ToVisit;
1024 ToVisit.push_back(RecordT);
1025 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001026 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1027 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001028 while (!ToVisit.empty()) {
1029 // Retrieve the next class in the inheritance hierarchy.
1030 const RecordType *NextT = ToVisit.back();
1031 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001033 // If we have already seen this type, skip it.
1034 if (!Visited.insert(NextT))
1035 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001037 // If this is a base class, try to perform template argument
1038 // deduction from it.
1039 if (NextT != RecordT) {
1040 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001041 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001042 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001044 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001045 // note that we had some success. Otherwise, ignore any deductions
1046 // from this base class.
1047 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001048 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001049 DeducedOrig = Deduced;
1050 }
1051 else
1052 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001053 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001055 // Visit base classes
1056 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1057 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1058 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001059 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001060 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001061 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001062 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001063 }
1064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001066 if (Successful)
1067 return Sema::TDK_Success;
1068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001070 }
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001072 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001073 }
1074
Douglas Gregor637a4092009-06-10 23:47:09 +00001075 // T type::*
1076 // T T::*
1077 // T (type::*)()
1078 // type (T::*)()
1079 // type (type::*)(T)
1080 // type (T::*)(T)
1081 // T (type::*)(T)
1082 // T (T::*)()
1083 // T (T::*)(T)
1084 case Type::MemberPointer: {
1085 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1086 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1087 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001088 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001089
Douglas Gregorf67875d2009-06-12 18:26:56 +00001090 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001091 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001092 MemPtrParam->getPointeeType(),
1093 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001094 Info, Deduced,
1095 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001096 return Result;
1097
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001098 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001099 QualType(MemPtrParam->getClass(), 0),
1100 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001101 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001102 }
1103
Anders Carlsson9a917e42009-06-12 22:56:54 +00001104 // (clang extension)
1105 //
Mike Stump1eb44332009-09-09 15:08:12 +00001106 // type(^)(T)
1107 // T(^)()
1108 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001109 case Type::BlockPointer: {
1110 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1111 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Anders Carlsson859ba502009-06-12 16:23:10 +00001113 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001114 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001116 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001117 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001118 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001119 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001120 }
1121
Douglas Gregor637a4092009-06-10 23:47:09 +00001122 case Type::TypeOfExpr:
1123 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001124 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001125 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001126 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001127
Douglas Gregord560d502009-06-04 00:21:18 +00001128 default:
1129 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001130 }
1131
1132 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001133 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001134}
1135
Douglas Gregorf67875d2009-06-12 18:26:56 +00001136static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001137DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001138 TemplateParameterList *TemplateParams,
1139 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001140 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001141 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001142 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001143 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001144 case TemplateArgument::Null:
1145 assert(false && "Null template argument in parameter list");
1146 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
1148 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001149 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001150 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001151 Arg.getAsType(), Info, Deduced, 0);
1152 Info.FirstArg = Param;
1153 Info.SecondArg = Arg;
1154 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001155
Douglas Gregor788cd062009-11-11 01:00:40 +00001156 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001157 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001158 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001159 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001160 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001161 Info.FirstArg = Param;
1162 Info.SecondArg = Arg;
1163 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001164
1165 case TemplateArgument::TemplateExpansion:
1166 llvm_unreachable("caller should handle pack expansions");
1167 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001168
Douglas Gregor199d9912009-06-05 00:53:49 +00001169 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001170 if (Arg.getKind() == TemplateArgument::Declaration &&
1171 Param.getAsDecl()->getCanonicalDecl() ==
1172 Arg.getAsDecl()->getCanonicalDecl())
1173 return Sema::TDK_Success;
1174
Douglas Gregorf67875d2009-06-12 18:26:56 +00001175 Info.FirstArg = Param;
1176 Info.SecondArg = Arg;
1177 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Douglas Gregor199d9912009-06-05 00:53:49 +00001179 case TemplateArgument::Integral:
1180 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001181 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001182 return Sema::TDK_Success;
1183
1184 Info.FirstArg = Param;
1185 Info.SecondArg = Arg;
1186 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001187 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001188
1189 if (Arg.getKind() == TemplateArgument::Expression) {
1190 Info.FirstArg = Param;
1191 Info.SecondArg = Arg;
1192 return Sema::TDK_NonDeducedMismatch;
1193 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001194
Douglas Gregorf67875d2009-06-12 18:26:56 +00001195 Info.FirstArg = Param;
1196 Info.SecondArg = Arg;
1197 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregor199d9912009-06-05 00:53:49 +00001199 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001200 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001201 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1202 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001203 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001204 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001205 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001206 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001207 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001208 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001209 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001210 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001211 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001212 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001213 Info, Deduced);
1214
Douglas Gregorf67875d2009-06-12 18:26:56 +00001215 Info.FirstArg = Param;
1216 Info.SecondArg = Arg;
1217 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Douglas Gregor199d9912009-06-05 00:53:49 +00001220 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001221 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001222 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001223 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001224 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Douglas Gregorf67875d2009-06-12 18:26:56 +00001227 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001228}
1229
Douglas Gregor20a55e22010-12-22 18:17:10 +00001230/// \brief Determine whether there is a template argument to be used for
1231/// deduction.
1232///
1233/// This routine "expands" argument packs in-place, overriding its input
1234/// parameters so that \c Args[ArgIdx] will be the available template argument.
1235///
1236/// \returns true if there is another template argument (which will be at
1237/// \c Args[ArgIdx]), false otherwise.
1238static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1239 unsigned &ArgIdx,
1240 unsigned &NumArgs) {
1241 if (ArgIdx == NumArgs)
1242 return false;
1243
1244 const TemplateArgument &Arg = Args[ArgIdx];
1245 if (Arg.getKind() != TemplateArgument::Pack)
1246 return true;
1247
1248 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1249 Args = Arg.pack_begin();
1250 NumArgs = Arg.pack_size();
1251 ArgIdx = 0;
1252 return ArgIdx < NumArgs;
1253}
1254
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001255/// \brief Determine whether the given set of template arguments has a pack
1256/// expansion that is not the last template argument.
1257static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1258 unsigned NumArgs) {
1259 unsigned ArgIdx = 0;
1260 while (ArgIdx < NumArgs) {
1261 const TemplateArgument &Arg = Args[ArgIdx];
1262
1263 // Unwrap argument packs.
1264 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1265 Args = Arg.pack_begin();
1266 NumArgs = Arg.pack_size();
1267 ArgIdx = 0;
1268 continue;
1269 }
1270
1271 ++ArgIdx;
1272 if (ArgIdx == NumArgs)
1273 return false;
1274
1275 if (Arg.isPackExpansion())
1276 return true;
1277 }
1278
1279 return false;
1280}
1281
Douglas Gregor20a55e22010-12-22 18:17:10 +00001282static Sema::TemplateDeductionResult
1283DeduceTemplateArguments(Sema &S,
1284 TemplateParameterList *TemplateParams,
1285 const TemplateArgument *Params, unsigned NumParams,
1286 const TemplateArgument *Args, unsigned NumArgs,
1287 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001288 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1289 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001290 // C++0x [temp.deduct.type]p9:
1291 // If the template argument list of P contains a pack expansion that is not
1292 // the last template argument, the entire template argument list is a
1293 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001294 if (hasPackExpansionBeforeEnd(Params, NumParams))
1295 return Sema::TDK_Success;
1296
Douglas Gregore02e2622010-12-22 21:19:48 +00001297 // C++0x [temp.deduct.type]p9:
1298 // If P has a form that contains <T> or <i>, then each argument Pi of the
1299 // respective template argument list P is compared with the corresponding
1300 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001301 unsigned ArgIdx = 0, ParamIdx = 0;
1302 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1303 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001304 // FIXME: Variadic templates.
1305 // What do we do if the argument is a pack expansion?
1306
Douglas Gregor20a55e22010-12-22 18:17:10 +00001307 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001308 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001309
1310 // Check whether we have enough arguments.
1311 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001312 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1313 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001314
Douglas Gregore02e2622010-12-22 21:19:48 +00001315 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001316 if (Sema::TemplateDeductionResult Result
1317 = DeduceTemplateArguments(S, TemplateParams,
1318 Params[ParamIdx], Args[ArgIdx],
1319 Info, Deduced))
1320 return Result;
1321
1322 // Move to the next argument.
1323 ++ArgIdx;
1324 continue;
1325 }
1326
Douglas Gregore02e2622010-12-22 21:19:48 +00001327 // The parameter is a pack expansion.
1328
1329 // C++0x [temp.deduct.type]p9:
1330 // If Pi is a pack expansion, then the pattern of Pi is compared with
1331 // each remaining argument in the template argument list of A. Each
1332 // comparison deduces template arguments for subsequent positions in the
1333 // template parameter packs expanded by Pi.
1334 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1335
1336 // Compute the set of template parameter indices that correspond to
1337 // parameter packs expanded by the pack expansion.
1338 llvm::SmallVector<unsigned, 2> PackIndices;
1339 {
1340 llvm::BitVector SawIndices(TemplateParams->size());
1341 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1342 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1343 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1344 unsigned Depth, Index;
1345 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1346 if (Depth == 0 && !SawIndices[Index]) {
1347 SawIndices[Index] = true;
1348 PackIndices.push_back(Index);
1349 }
1350 }
1351 }
1352 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1353
1354 // FIXME: If there are no remaining arguments, we can bail out early
1355 // and set any deduced parameter packs to an empty argument pack.
1356 // The latter part of this is a (minor) correctness issue.
1357
1358 // Save the deduced template arguments for each parameter pack expanded
1359 // by this pack expansion, then clear out the deduction.
1360 llvm::SmallVector<DeducedTemplateArgument, 2>
1361 SavedPacks(PackIndices.size());
1362 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1363 SavedPacks[I] = Deduced[PackIndices[I]];
1364 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1365 }
1366
1367 // Keep track of the deduced template arguments for each parameter pack
1368 // expanded by this pack expansion (the outer index) and for each
1369 // template argument (the inner SmallVectors).
1370 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1371 NewlyDeducedPacks(PackIndices.size());
1372 bool HasAnyArguments = false;
1373 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1374 HasAnyArguments = true;
1375
1376 // Deduce template arguments from the pattern.
1377 if (Sema::TemplateDeductionResult Result
1378 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1379 Info, Deduced))
1380 return Result;
1381
1382 // Capture the deduced template arguments for each parameter pack expanded
1383 // by this pack expansion, add them to the list of arguments we've deduced
1384 // for that pack, then clear out the deduced argument.
1385 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1386 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1387 if (!DeducedArg.isNull()) {
1388 NewlyDeducedPacks[I].push_back(DeducedArg);
1389 DeducedArg = DeducedTemplateArgument();
1390 }
1391 }
1392
1393 ++ArgIdx;
1394 }
1395
1396 // Build argument packs for each of the parameter packs expanded by this
1397 // pack expansion.
1398 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1399 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1400 // We were not able to deduce anything for this parameter pack,
1401 // so just restore the saved argument pack.
1402 Deduced[PackIndices[I]] = SavedPacks[I];
1403 continue;
1404 }
1405
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001406 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001407
1408 if (NewlyDeducedPacks[I].empty()) {
1409 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001410 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1411 } else {
1412 TemplateArgument *ArgumentPack
1413 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1414 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1415 ArgumentPack);
1416 NewPack
1417 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001418 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001419 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1420 }
1421
1422 DeducedTemplateArgument Result
1423 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1424 if (Result.isNull()) {
1425 Info.Param
1426 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1427 Info.FirstArg = SavedPacks[I];
1428 Info.SecondArg = NewPack;
1429 return Sema::TDK_Inconsistent;
1430 }
1431
1432 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001433 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001434 }
1435
1436 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001437 if (NumberOfArgumentsMustMatch &&
1438 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001439 return Sema::TDK_TooManyArguments;
1440
1441 return Sema::TDK_Success;
1442}
1443
Mike Stump1eb44332009-09-09 15:08:12 +00001444static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001445DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001446 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001447 const TemplateArgumentList &ParamList,
1448 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001449 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001450 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001451 return DeduceTemplateArguments(S, TemplateParams,
1452 ParamList.data(), ParamList.size(),
1453 ArgList.data(), ArgList.size(),
1454 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001455}
1456
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001457/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001458static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001459 const TemplateArgument &X,
1460 const TemplateArgument &Y) {
1461 if (X.getKind() != Y.getKind())
1462 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001464 switch (X.getKind()) {
1465 case TemplateArgument::Null:
1466 assert(false && "Comparing NULL template argument");
1467 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001469 case TemplateArgument::Type:
1470 return Context.getCanonicalType(X.getAsType()) ==
1471 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001473 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001474 return X.getAsDecl()->getCanonicalDecl() ==
1475 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Douglas Gregor788cd062009-11-11 01:00:40 +00001477 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001478 case TemplateArgument::TemplateExpansion:
1479 return Context.getCanonicalTemplateName(
1480 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1481 Context.getCanonicalTemplateName(
1482 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001483
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001484 case TemplateArgument::Integral:
1485 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Douglas Gregor788cd062009-11-11 01:00:40 +00001487 case TemplateArgument::Expression: {
1488 llvm::FoldingSetNodeID XID, YID;
1489 X.getAsExpr()->Profile(XID, Context, true);
1490 Y.getAsExpr()->Profile(YID, Context, true);
1491 return XID == YID;
1492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001494 case TemplateArgument::Pack:
1495 if (X.pack_size() != Y.pack_size())
1496 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001497
1498 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1499 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001500 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001501 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001502 if (!isSameTemplateArg(Context, *XP, *YP))
1503 return false;
1504
1505 return true;
1506 }
1507
1508 return false;
1509}
1510
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001511/// \brief Allocate a TemplateArgumentLoc where all locations have
1512/// been initialized to the given location.
1513///
1514/// \param S The semantic analysis object.
1515///
1516/// \param The template argument we are producing template argument
1517/// location information for.
1518///
1519/// \param NTTPType For a declaration template argument, the type of
1520/// the non-type template parameter that corresponds to this template
1521/// argument.
1522///
1523/// \param Loc The source location to use for the resulting template
1524/// argument.
1525static TemplateArgumentLoc
1526getTrivialTemplateArgumentLoc(Sema &S,
1527 const TemplateArgument &Arg,
1528 QualType NTTPType,
1529 SourceLocation Loc) {
1530 switch (Arg.getKind()) {
1531 case TemplateArgument::Null:
1532 llvm_unreachable("Can't get a NULL template argument here");
1533 break;
1534
1535 case TemplateArgument::Type:
1536 return TemplateArgumentLoc(Arg,
1537 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1538
1539 case TemplateArgument::Declaration: {
1540 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001541 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001542 .takeAs<Expr>();
1543 return TemplateArgumentLoc(TemplateArgument(E), E);
1544 }
1545
1546 case TemplateArgument::Integral: {
1547 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001548 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001549 return TemplateArgumentLoc(TemplateArgument(E), E);
1550 }
1551
1552 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001553 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1554
1555 case TemplateArgument::TemplateExpansion:
1556 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1557
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001558 case TemplateArgument::Expression:
1559 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1560
1561 case TemplateArgument::Pack:
1562 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1563 }
1564
1565 return TemplateArgumentLoc();
1566}
1567
1568
1569/// \brief Convert the given deduced template argument and add it to the set of
1570/// fully-converted template arguments.
1571static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1572 DeducedTemplateArgument Arg,
1573 NamedDecl *Template,
1574 QualType NTTPType,
1575 TemplateDeductionInfo &Info,
1576 bool InFunctionTemplate,
1577 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1578 if (Arg.getKind() == TemplateArgument::Pack) {
1579 // This is a template argument pack, so check each of its arguments against
1580 // the template parameter.
1581 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1582 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001583 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001584 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001585 // When converting the deduced template argument, append it to the
1586 // general output list. We need to do this so that the template argument
1587 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001588 DeducedTemplateArgument InnerArg(*PA);
1589 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1590 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1591 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001592 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001593 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001594
1595 // Move the converted template argument into our argument pack.
1596 PackedArgsBuilder.push_back(Output.back());
1597 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001598 }
1599
1600 // Create the resulting argument pack.
1601 TemplateArgument *PackedArgs = 0;
1602 if (!PackedArgsBuilder.empty()) {
1603 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1604 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1605 }
1606 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1607 return false;
1608 }
1609
1610 // Convert the deduced template argument into a template
1611 // argument that we can check, almost as if the user had written
1612 // the template argument explicitly.
1613 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1614 Info.getLocation());
1615
1616 // Check the template argument, converting it as necessary.
1617 return S.CheckTemplateArgument(Param, ArgLoc,
1618 Template,
1619 Template->getLocation(),
1620 Template->getSourceRange().getEnd(),
1621 Output,
1622 InFunctionTemplate
1623 ? (Arg.wasDeducedFromArrayBound()
1624 ? Sema::CTAK_DeducedFromArrayBound
1625 : Sema::CTAK_Deduced)
1626 : Sema::CTAK_Specified);
1627}
1628
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001629/// Complete template argument deduction for a class template partial
1630/// specialization.
1631static Sema::TemplateDeductionResult
1632FinishTemplateArgumentDeduction(Sema &S,
1633 ClassTemplatePartialSpecializationDecl *Partial,
1634 const TemplateArgumentList &TemplateArgs,
1635 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001636 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001637 // Trap errors.
1638 Sema::SFINAETrap Trap(S);
1639
1640 Sema::ContextRAII SavedContext(S, Partial);
1641
1642 // C++ [temp.deduct.type]p2:
1643 // [...] or if any template argument remains neither deduced nor
1644 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001645 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001646 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1647 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001648 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001649 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001650 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001651 return Sema::TDK_Incomplete;
1652 }
1653
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001654 // We have deduced this argument, so it still needs to be
1655 // checked and converted.
1656
1657 // First, for a non-type template parameter type that is
1658 // initialized by a declaration, we need the type of the
1659 // corresponding non-type template parameter.
1660 QualType NTTPType;
1661 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001662 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001663 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001664 if (NTTPType->isDependentType()) {
1665 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1666 Builder.data(), Builder.size());
1667 NTTPType = S.SubstType(NTTPType,
1668 MultiLevelTemplateArgumentList(TemplateArgs),
1669 NTTP->getLocation(),
1670 NTTP->getDeclName());
1671 if (NTTPType.isNull()) {
1672 Info.Param = makeTemplateParameter(Param);
1673 // FIXME: These template arguments are temporary. Free them!
1674 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1675 Builder.data(),
1676 Builder.size()));
1677 return Sema::TDK_SubstitutionFailure;
1678 }
1679 }
1680 }
1681
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001682 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1683 Partial, NTTPType, Info, false,
1684 Builder)) {
1685 Info.Param = makeTemplateParameter(Param);
1686 // FIXME: These template arguments are temporary. Free them!
1687 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1688 Builder.size()));
1689 return Sema::TDK_SubstitutionFailure;
1690 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001691 }
1692
1693 // Form the template argument list from the deduced template arguments.
1694 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001695 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1696 Builder.size());
1697
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001698 Info.reset(DeducedArgumentList);
1699
1700 // Substitute the deduced template arguments into the template
1701 // arguments of the class template partial specialization, and
1702 // verify that the instantiated template arguments are both valid
1703 // and are equivalent to the template arguments originally provided
1704 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001705 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001706 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1707 const TemplateArgumentLoc *PartialTemplateArgs
1708 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001709
1710 // Note that we don't provide the langle and rangle locations.
1711 TemplateArgumentListInfo InstArgs;
1712
Douglas Gregore02e2622010-12-22 21:19:48 +00001713 if (S.Subst(PartialTemplateArgs,
1714 Partial->getNumTemplateArgsAsWritten(),
1715 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1716 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1717 if (ParamIdx >= Partial->getTemplateParameters()->size())
1718 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1719
1720 Decl *Param
1721 = const_cast<NamedDecl *>(
1722 Partial->getTemplateParameters()->getParam(ParamIdx));
1723 Info.Param = makeTemplateParameter(Param);
1724 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1725 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001726 }
1727
Douglas Gregor910f8002010-11-07 23:05:16 +00001728 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001729 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001730 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001731 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001732
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001733 TemplateParameterList *TemplateParams
1734 = ClassTemplate->getTemplateParameters();
1735 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001736 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001737 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001738 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001739 Info.FirstArg = TemplateArgs[I];
1740 Info.SecondArg = InstArg;
1741 return Sema::TDK_NonDeducedMismatch;
1742 }
1743 }
1744
1745 if (Trap.hasErrorOccurred())
1746 return Sema::TDK_SubstitutionFailure;
1747
1748 return Sema::TDK_Success;
1749}
1750
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001751/// \brief Perform template argument deduction to determine whether
1752/// the given template arguments match the given class template
1753/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001754Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001755Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001756 const TemplateArgumentList &TemplateArgs,
1757 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001758 // C++ [temp.class.spec.match]p2:
1759 // A partial specialization matches a given actual template
1760 // argument list if the template arguments of the partial
1761 // specialization can be deduced from the actual template argument
1762 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001763 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001764 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001765 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001766 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001767 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001768 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001769 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001770 TemplateArgs, Info, Deduced))
1771 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001772
Douglas Gregor637a4092009-06-10 23:47:09 +00001773 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001774 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001775 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001776 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001777
Douglas Gregorbb260412009-06-14 08:02:22 +00001778 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001779 return Sema::TDK_SubstitutionFailure;
1780
1781 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1782 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001783}
Douglas Gregor031a5882009-06-13 00:26:55 +00001784
Douglas Gregor41128772009-06-26 23:27:24 +00001785/// \brief Determine whether the given type T is a simple-template-id type.
1786static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001787 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001788 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001789 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Douglas Gregor41128772009-06-26 23:27:24 +00001791 return false;
1792}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001793
1794/// \brief Substitute the explicitly-provided template arguments into the
1795/// given function template according to C++ [temp.arg.explicit].
1796///
1797/// \param FunctionTemplate the function template into which the explicit
1798/// template arguments will be substituted.
1799///
Mike Stump1eb44332009-09-09 15:08:12 +00001800/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001801/// arguments.
1802///
Mike Stump1eb44332009-09-09 15:08:12 +00001803/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001804/// with the converted and checked explicit template arguments.
1805///
Mike Stump1eb44332009-09-09 15:08:12 +00001806/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001807/// parameters.
1808///
1809/// \param FunctionType if non-NULL, the result type of the function template
1810/// will also be instantiated and the pointed-to value will be updated with
1811/// the instantiated function type.
1812///
1813/// \param Info if substitution fails for any reason, this object will be
1814/// populated with more information about the failure.
1815///
1816/// \returns TDK_Success if substitution was successful, or some failure
1817/// condition.
1818Sema::TemplateDeductionResult
1819Sema::SubstituteExplicitTemplateArguments(
1820 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001821 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001822 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001823 llvm::SmallVectorImpl<QualType> &ParamTypes,
1824 QualType *FunctionType,
1825 TemplateDeductionInfo &Info) {
1826 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1827 TemplateParameterList *TemplateParams
1828 = FunctionTemplate->getTemplateParameters();
1829
John McCalld5532b62009-11-23 01:53:49 +00001830 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001831 // No arguments to substitute; just copy over the parameter types and
1832 // fill in the function type.
1833 for (FunctionDecl::param_iterator P = Function->param_begin(),
1834 PEnd = Function->param_end();
1835 P != PEnd;
1836 ++P)
1837 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Douglas Gregor83314aa2009-07-08 20:55:45 +00001839 if (FunctionType)
1840 *FunctionType = Function->getType();
1841 return TDK_Success;
1842 }
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Douglas Gregor83314aa2009-07-08 20:55:45 +00001844 // Substitution of the explicit template arguments into a function template
1845 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001846 SFINAETrap Trap(*this);
1847
Douglas Gregor83314aa2009-07-08 20:55:45 +00001848 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001849 // Template arguments that are present shall be specified in the
1850 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001851 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001852 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001853 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001854
1855 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001856 // explicitly-specified template arguments against this function template,
1857 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001858 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001859 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001860 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1861 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001862 if (Inst)
1863 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregor83314aa2009-07-08 20:55:45 +00001865 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001866 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001867 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001868 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001869 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001870 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001871 if (Index >= TemplateParams->size())
1872 Index = TemplateParams->size() - 1;
1873 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001874 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Douglas Gregor83314aa2009-07-08 20:55:45 +00001877 // Form the template argument list from the explicitly-specified
1878 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001879 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001880 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001881 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001882
John McCalldf41f182010-10-12 19:40:14 +00001883 // Template argument deduction and the final substitution should be
1884 // done in the context of the templated declaration. Explicit
1885 // argument substitution, on the other hand, needs to happen in the
1886 // calling context.
1887 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1888
Douglas Gregor83314aa2009-07-08 20:55:45 +00001889 // Instantiate the types of each of the function parameters given the
1890 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00001891 if (SubstParmTypes(Function->getLocation(),
1892 Function->param_begin(), Function->getNumParams(),
1893 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1894 ParamTypes))
1895 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001896
1897 // If the caller wants a full function type back, instantiate the return
1898 // type and form that function type.
1899 if (FunctionType) {
1900 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001901 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001902 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001903 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001904
1905 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001906 = SubstType(Proto->getResultType(),
1907 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1908 Function->getTypeSpecStartLoc(),
1909 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001910 if (ResultType.isNull() || Trap.hasErrorOccurred())
1911 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001912
1913 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001914 ParamTypes.data(), ParamTypes.size(),
1915 Proto->isVariadic(),
1916 Proto->getTypeQuals(),
1917 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001918 Function->getDeclName(),
1919 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001920 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1921 return TDK_SubstitutionFailure;
1922 }
Mike Stump1eb44332009-09-09 15:08:12 +00001923
Douglas Gregor83314aa2009-07-08 20:55:45 +00001924 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001925 // Trailing template arguments that can be deduced (14.8.2) may be
1926 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001927 // template arguments can be deduced, they may all be omitted; in this
1928 // case, the empty template argument list <> itself may also be omitted.
1929 //
1930 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001931 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001932 Deduced.reserve(TemplateParams->size());
1933 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001934 Deduced.push_back(ExplicitArgumentList->get(I));
1935
Douglas Gregor83314aa2009-07-08 20:55:45 +00001936 return TDK_Success;
1937}
1938
Mike Stump1eb44332009-09-09 15:08:12 +00001939/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001940/// checking the deduced template arguments for completeness and forming
1941/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001942Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001943Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001944 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1945 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001946 FunctionDecl *&Specialization,
1947 TemplateDeductionInfo &Info) {
1948 TemplateParameterList *TemplateParams
1949 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Douglas Gregor83314aa2009-07-08 20:55:45 +00001951 // Template argument deduction for function templates in a SFINAE context.
1952 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001953 SFINAETrap Trap(*this);
1954
Douglas Gregor83314aa2009-07-08 20:55:45 +00001955 // Enter a new template instantiation context while we instantiate the
1956 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001957 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001958 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001959 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1960 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001961 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001962 return TDK_InstantiationDepth;
1963
John McCall96db3102010-04-29 01:18:58 +00001964 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001965
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001966 // C++ [temp.deduct.type]p2:
1967 // [...] or if any template argument remains neither deduced nor
1968 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001969 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001970 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
1971 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001972
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001973 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001974 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001975 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001976 // argument, because it was explicitly-specified. Just record the
1977 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001978 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001979 continue;
1980 }
1981
1982 // We have deduced this argument, so it still needs to be
1983 // checked and converted.
1984
1985 // First, for a non-type template parameter type that is
1986 // initialized by a declaration, we need the type of the
1987 // corresponding non-type template parameter.
1988 QualType NTTPType;
1989 if (NonTypeTemplateParmDecl *NTTP
1990 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001991 NTTPType = NTTP->getType();
1992 if (NTTPType->isDependentType()) {
1993 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1994 Builder.data(), Builder.size());
1995 NTTPType = SubstType(NTTPType,
1996 MultiLevelTemplateArgumentList(TemplateArgs),
1997 NTTP->getLocation(),
1998 NTTP->getDeclName());
1999 if (NTTPType.isNull()) {
2000 Info.Param = makeTemplateParameter(Param);
2001 // FIXME: These template arguments are temporary. Free them!
2002 Info.reset(TemplateArgumentList::CreateCopy(Context,
2003 Builder.data(),
2004 Builder.size()));
2005 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002006 }
2007 }
2008 }
2009
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002010 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2011 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002012 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002013 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002014 // FIXME: These template arguments are temporary. Free them!
2015 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002016 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002017 return TDK_SubstitutionFailure;
2018 }
2019
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002020 continue;
2021 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002022
2023 // C++0x [temp.arg.explicit]p3:
2024 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2025 // be deduced to an empty sequence of template arguments.
2026 // FIXME: Where did the word "trailing" come from?
2027 if (Param->isTemplateParameterPack()) {
2028 Builder.push_back(TemplateArgument(0, 0));
2029 continue;
2030 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002031
2032 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002033 TemplateArgumentLoc DefArg
2034 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2035 FunctionTemplate->getLocation(),
2036 FunctionTemplate->getSourceRange().getEnd(),
2037 Param,
2038 Builder);
2039
2040 // If there was no default argument, deduction is incomplete.
2041 if (DefArg.getArgument().isNull()) {
2042 Info.Param = makeTemplateParameter(
2043 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2044 return TDK_Incomplete;
2045 }
2046
2047 // Check whether we can actually use the default argument.
2048 if (CheckTemplateArgument(Param, DefArg,
2049 FunctionTemplate,
2050 FunctionTemplate->getLocation(),
2051 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002052 Builder,
2053 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002054 Info.Param = makeTemplateParameter(
2055 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002056 // FIXME: These template arguments are temporary. Free them!
2057 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2058 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002059 return TDK_SubstitutionFailure;
2060 }
2061
2062 // If we get here, we successfully used the default template argument.
2063 }
2064
2065 // Form the template argument list from the deduced template arguments.
2066 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002067 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002068 Info.reset(DeducedArgumentList);
2069
Mike Stump1eb44332009-09-09 15:08:12 +00002070 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002071 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002072 DeclContext *Owner = FunctionTemplate->getDeclContext();
2073 if (FunctionTemplate->getFriendObjectKind())
2074 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002075 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002076 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002077 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002078 if (!Specialization)
2079 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Douglas Gregorf8825742009-09-15 18:26:13 +00002081 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2082 FunctionTemplate->getCanonicalDecl());
2083
Mike Stump1eb44332009-09-09 15:08:12 +00002084 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002085 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002086 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2087 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002088 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Douglas Gregor83314aa2009-07-08 20:55:45 +00002090 // There may have been an error that did not prevent us from constructing a
2091 // declaration. Mark the declaration invalid and return with a substitution
2092 // failure.
2093 if (Trap.hasErrorOccurred()) {
2094 Specialization->setInvalidDecl(true);
2095 return TDK_SubstitutionFailure;
2096 }
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Douglas Gregor9b623632010-10-12 23:32:35 +00002098 // If we suppressed any diagnostics while performing template argument
2099 // deduction, and if we haven't already instantiated this declaration,
2100 // keep track of these diagnostics. They'll be emitted if this specialization
2101 // is actually used.
2102 if (Info.diag_begin() != Info.diag_end()) {
2103 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2104 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2105 if (Pos == SuppressedDiagnostics.end())
2106 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2107 .append(Info.diag_begin(), Info.diag_end());
2108 }
2109
Mike Stump1eb44332009-09-09 15:08:12 +00002110 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002111}
2112
John McCall9c72c602010-08-27 09:08:28 +00002113/// Gets the type of a function for template-argument-deducton
2114/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002115static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002116 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002117 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002118 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002119 if (Method->isInstance()) {
2120 // An instance method that's referenced in a form that doesn't
2121 // look like a member pointer is just invalid.
2122 if (!R.HasFormOfMemberPointer) return QualType();
2123
John McCalleff92132010-02-02 02:21:27 +00002124 return Context.getMemberPointerType(Fn->getType(),
2125 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002126 }
2127
2128 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002129 return Context.getPointerType(Fn->getType());
2130}
2131
2132/// Apply the deduction rules for overload sets.
2133///
2134/// \return the null type if this argument should be treated as an
2135/// undeduced context
2136static QualType
2137ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002138 Expr *Arg, QualType ParamType,
2139 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002140
2141 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002142
John McCall9c72c602010-08-27 09:08:28 +00002143 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002144
Douglas Gregor75f21af2010-08-30 21:04:23 +00002145 // C++0x [temp.deduct.call]p4
2146 unsigned TDF = 0;
2147 if (ParamWasReference)
2148 TDF |= TDF_ParamWithReferenceType;
2149 if (R.IsAddressOfOperand)
2150 TDF |= TDF_IgnoreQualifiers;
2151
John McCalleff92132010-02-02 02:21:27 +00002152 // If there were explicit template arguments, we can only find
2153 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2154 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002155 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002156 // But we can still look for an explicit specialization.
2157 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002158 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002159 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002160 return QualType();
2161 }
2162
2163 // C++0x [temp.deduct.call]p6:
2164 // When P is a function type, pointer to function type, or pointer
2165 // to member function type:
2166
2167 if (!ParamType->isFunctionType() &&
2168 !ParamType->isFunctionPointerType() &&
2169 !ParamType->isMemberFunctionPointerType())
2170 return QualType();
2171
2172 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002173 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2174 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002175 NamedDecl *D = (*I)->getUnderlyingDecl();
2176
2177 // - If the argument is an overload set containing one or more
2178 // function templates, the parameter is treated as a
2179 // non-deduced context.
2180 if (isa<FunctionTemplateDecl>(D))
2181 return QualType();
2182
2183 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002184 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2185 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002186
Douglas Gregor75f21af2010-08-30 21:04:23 +00002187 // Function-to-pointer conversion.
2188 if (!ParamWasReference && ParamType->isPointerType() &&
2189 ArgType->isFunctionType())
2190 ArgType = S.Context.getPointerType(ArgType);
2191
John McCalleff92132010-02-02 02:21:27 +00002192 // - If the argument is an overload set (not containing function
2193 // templates), trial argument deduction is attempted using each
2194 // of the members of the set. If deduction succeeds for only one
2195 // of the overload set members, that member is used as the
2196 // argument value for the deduction. If deduction succeeds for
2197 // more than one member of the overload set the parameter is
2198 // treated as a non-deduced context.
2199
2200 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2201 // Type deduction is done independently for each P/A pair, and
2202 // the deduced template argument values are then combined.
2203 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002204 llvm::SmallVector<DeducedTemplateArgument, 8>
2205 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002206 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002207 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002208 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002209 ParamType, ArgType,
2210 Info, Deduced, TDF);
2211 if (Result) continue;
2212 if (!Match.isNull()) return QualType();
2213 Match = ArgType;
2214 }
2215
2216 return Match;
2217}
2218
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002219/// \brief Perform the adjustments to the parameter and argument types
2220/// described in C++ [temp.deduct.call].
2221///
2222/// \returns true if the caller should not attempt to perform any template
2223/// argument deduction based on this P/A pair.
2224static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2225 TemplateParameterList *TemplateParams,
2226 QualType &ParamType,
2227 QualType &ArgType,
2228 Expr *Arg,
2229 unsigned &TDF) {
2230 // C++0x [temp.deduct.call]p3:
2231 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2232 // are ignored for type deduction.
2233 if (ParamType.getCVRQualifiers())
2234 ParamType = ParamType.getLocalUnqualifiedType();
2235 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2236 if (ParamRefType) {
2237 // [...] If P is a reference type, the type referred to by P is used
2238 // for type deduction.
2239 ParamType = ParamRefType->getPointeeType();
2240 }
2241
2242 // Overload sets usually make this parameter an undeduced
2243 // context, but there are sometimes special circumstances.
2244 if (ArgType == S.Context.OverloadTy) {
2245 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2246 Arg, ParamType,
2247 ParamRefType != 0);
2248 if (ArgType.isNull())
2249 return true;
2250 }
2251
2252 if (ParamRefType) {
2253 // C++0x [temp.deduct.call]p3:
2254 // [...] If P is of the form T&&, where T is a template parameter, and
2255 // the argument is an lvalue, the type A& is used in place of A for
2256 // type deduction.
2257 if (ParamRefType->isRValueReferenceType() &&
2258 ParamRefType->getAs<TemplateTypeParmType>() &&
2259 Arg->isLValue())
2260 ArgType = S.Context.getLValueReferenceType(ArgType);
2261 } else {
2262 // C++ [temp.deduct.call]p2:
2263 // If P is not a reference type:
2264 // - If A is an array type, the pointer type produced by the
2265 // array-to-pointer standard conversion (4.2) is used in place of
2266 // A for type deduction; otherwise,
2267 if (ArgType->isArrayType())
2268 ArgType = S.Context.getArrayDecayedType(ArgType);
2269 // - If A is a function type, the pointer type produced by the
2270 // function-to-pointer standard conversion (4.3) is used in place
2271 // of A for type deduction; otherwise,
2272 else if (ArgType->isFunctionType())
2273 ArgType = S.Context.getPointerType(ArgType);
2274 else {
2275 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2276 // type are ignored for type deduction.
2277 QualType CanonArgType = S.Context.getCanonicalType(ArgType);
2278 if (ArgType.getCVRQualifiers())
2279 ArgType = ArgType.getUnqualifiedType();
2280 }
2281 }
2282
2283 // C++0x [temp.deduct.call]p4:
2284 // In general, the deduction process attempts to find template argument
2285 // values that will make the deduced A identical to A (after the type A
2286 // is transformed as described above). [...]
2287 TDF = TDF_SkipNonDependent;
2288
2289 // - If the original P is a reference type, the deduced A (i.e., the
2290 // type referred to by the reference) can be more cv-qualified than
2291 // the transformed A.
2292 if (ParamRefType)
2293 TDF |= TDF_ParamWithReferenceType;
2294 // - The transformed A can be another pointer or pointer to member
2295 // type that can be converted to the deduced A via a qualification
2296 // conversion (4.4).
2297 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2298 ArgType->isObjCObjectPointerType())
2299 TDF |= TDF_IgnoreQualifiers;
2300 // - If P is a class and P has the form simple-template-id, then the
2301 // transformed A can be a derived class of the deduced A. Likewise,
2302 // if P is a pointer to a class of the form simple-template-id, the
2303 // transformed A can be a pointer to a derived class pointed to by
2304 // the deduced A.
2305 if (isSimpleTemplateIdType(ParamType) ||
2306 (isa<PointerType>(ParamType) &&
2307 isSimpleTemplateIdType(
2308 ParamType->getAs<PointerType>()->getPointeeType())))
2309 TDF |= TDF_DerivedClass;
2310
2311 return false;
2312}
2313
Douglas Gregore53060f2009-06-25 22:08:12 +00002314/// \brief Perform template argument deduction from a function call
2315/// (C++ [temp.deduct.call]).
2316///
2317/// \param FunctionTemplate the function template for which we are performing
2318/// template argument deduction.
2319///
Douglas Gregor48026d22010-01-11 18:40:55 +00002320/// \param ExplicitTemplateArguments the explicit template arguments provided
2321/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002322///
Douglas Gregore53060f2009-06-25 22:08:12 +00002323/// \param Args the function call arguments
2324///
2325/// \param NumArgs the number of arguments in Args
2326///
Douglas Gregor48026d22010-01-11 18:40:55 +00002327/// \param Name the name of the function being called. This is only significant
2328/// when the function template is a conversion function template, in which
2329/// case this routine will also perform template argument deduction based on
2330/// the function to which
2331///
Douglas Gregore53060f2009-06-25 22:08:12 +00002332/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002333/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002334/// template argument deduction.
2335///
2336/// \param Info the argument will be updated to provide additional information
2337/// about template argument deduction.
2338///
2339/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002340Sema::TemplateDeductionResult
2341Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002342 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002343 Expr **Args, unsigned NumArgs,
2344 FunctionDecl *&Specialization,
2345 TemplateDeductionInfo &Info) {
2346 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002347
Douglas Gregore53060f2009-06-25 22:08:12 +00002348 // C++ [temp.deduct.call]p1:
2349 // Template argument deduction is done by comparing each function template
2350 // parameter type (call it P) with the type of the corresponding argument
2351 // of the call (call it A) as described below.
2352 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002353 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002354 return TDK_TooFewArguments;
2355 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002356 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002357 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002358 if (Proto->isTemplateVariadic())
2359 /* Do nothing */;
2360 else if (Proto->isVariadic())
2361 CheckArgs = Function->getNumParams();
2362 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002363 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002364 }
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002366 // The types of the parameters from which we will perform template argument
2367 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002368 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002369 TemplateParameterList *TemplateParams
2370 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002371 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002372 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002373 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002374 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002375 TemplateDeductionResult Result =
2376 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002377 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002378 Deduced,
2379 ParamTypes,
2380 0,
2381 Info);
2382 if (Result)
2383 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002384
2385 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002386 } else {
2387 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002388 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002389 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2390 }
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002392 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002393 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002394 unsigned ArgIdx = 0;
2395 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2396 ParamIdx != NumParams; ++ParamIdx) {
2397 QualType ParamType = ParamTypes[ParamIdx];
2398
2399 const PackExpansionType *ParamExpansion
2400 = dyn_cast<PackExpansionType>(ParamType);
2401 if (!ParamExpansion) {
2402 // Simple case: matching a function parameter to a function argument.
2403 if (ArgIdx >= CheckArgs)
2404 break;
2405
2406 Expr *Arg = Args[ArgIdx++];
2407 QualType ArgType = Arg->getType();
2408 unsigned TDF = 0;
2409 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2410 ParamType, ArgType, Arg,
2411 TDF))
2412 continue;
2413
2414 if (TemplateDeductionResult Result
2415 = ::DeduceTemplateArguments(*this, TemplateParams,
2416 ParamType, ArgType, Info, Deduced,
2417 TDF))
2418 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002419
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002420 // FIXME: we need to check that the deduced A is the same as A,
2421 // modulo the various allowed differences.
2422 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002423 }
2424
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002425 // C++0x [temp.deduct.call]p1:
2426 // For a function parameter pack that occurs at the end of the
2427 // parameter-declaration-list, the type A of each remaining argument of
2428 // the call is compared with the type P of the declarator-id of the
2429 // function parameter pack. Each comparison deduces template arguments
2430 // for subsequent positions in the template parameter packs expanded by
2431 // the function parameter pack.
2432 QualType ParamPattern = ParamExpansion->getPattern();
2433 llvm::SmallVector<unsigned, 2> PackIndices;
2434 {
2435 llvm::BitVector SawIndices(TemplateParams->size());
2436 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2437 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2438 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2439 unsigned Depth, Index;
2440 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2441 if (Depth == 0 && !SawIndices[Index]) {
2442 SawIndices[Index] = true;
2443 PackIndices.push_back(Index);
2444 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002445 }
2446 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002447 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2448
2449 // Save the deduced template arguments for each parameter pack expanded
2450 // by this pack expansion, then clear out the deduction.
2451 llvm::SmallVector<DeducedTemplateArgument, 2>
2452 SavedPacks(PackIndices.size());
2453 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2454 SavedPacks[I] = Deduced[PackIndices[I]];
2455 Deduced[PackIndices[I]] = DeducedTemplateArgument();
2456 }
2457
2458 // Keep track of the deduced template arguments for each parameter pack
2459 // expanded by this pack expansion (the outer index) and for each
2460 // template argument (the inner SmallVectors).
2461 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
2462 NewlyDeducedPacks(PackIndices.size());
2463 bool HasAnyArguments = false;
2464 for (; ArgIdx < NumArgs; ++ArgIdx) {
2465 HasAnyArguments = true;
2466
2467 ParamType = ParamPattern;
2468 Expr *Arg = Args[ArgIdx];
2469 QualType ArgType = Arg->getType();
2470 unsigned TDF = 0;
2471 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2472 ParamType, ArgType, Arg,
2473 TDF)) {
2474 // We can't actually perform any deduction for this argument, so stop
2475 // deduction at this point.
2476 ++ArgIdx;
2477 break;
2478 }
2479
2480 if (TemplateDeductionResult Result
2481 = ::DeduceTemplateArguments(*this, TemplateParams,
2482 ParamType, ArgType, Info, Deduced,
2483 TDF))
2484 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002485
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002486 // Capture the deduced template arguments for each parameter pack expanded
2487 // by this pack expansion, add them to the list of arguments we've deduced
2488 // for that pack, then clear out the deduced argument.
2489 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2490 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2491 if (!DeducedArg.isNull()) {
2492 NewlyDeducedPacks[I].push_back(DeducedArg);
2493 DeducedArg = DeducedTemplateArgument();
2494 }
2495 }
2496 }
2497
2498 // Build argument packs for each of the parameter packs expanded by this
2499 // pack expansion.
2500 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2501 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
2502 // We were not able to deduce anything for this parameter pack,
2503 // so just restore the saved argument pack.
2504 Deduced[PackIndices[I]] = SavedPacks[I];
2505 continue;
2506 }
2507
2508 DeducedTemplateArgument NewPack;
2509
2510 if (NewlyDeducedPacks[I].empty()) {
2511 // If we deduced an empty argument pack, create it now.
2512 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
2513 } else {
2514 TemplateArgument *ArgumentPack
2515 = new (Context) TemplateArgument [NewlyDeducedPacks[I].size()];
2516 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
2517 ArgumentPack);
2518 NewPack
2519 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
2520 NewlyDeducedPacks[I].size()),
2521 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
2522 }
2523
2524 DeducedTemplateArgument Result
2525 = checkDeducedTemplateArguments(Context, SavedPacks[I], NewPack);
2526 if (Result.isNull()) {
2527 Info.Param
2528 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
2529 Info.FirstArg = SavedPacks[I];
2530 Info.SecondArg = NewPack;
2531 return Sema::TDK_Inconsistent;
2532 }
2533
2534 Deduced[PackIndices[I]] = Result;
2535 }
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002537 // After we've matching against a parameter pack, we're done.
2538 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002539 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002540
Mike Stump1eb44332009-09-09 15:08:12 +00002541 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002542 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002543 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002544}
2545
Douglas Gregor83314aa2009-07-08 20:55:45 +00002546/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002547/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2548/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002549///
2550/// \param FunctionTemplate the function template for which we are performing
2551/// template argument deduction.
2552///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002553/// \param ExplicitTemplateArguments the explicitly-specified template
2554/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002555///
2556/// \param ArgFunctionType the function type that will be used as the
2557/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002558/// function template's function type. This type may be NULL, if there is no
2559/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002560///
2561/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002562/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002563/// template argument deduction.
2564///
2565/// \param Info the argument will be updated to provide additional information
2566/// about template argument deduction.
2567///
2568/// \returns the result of template argument deduction.
2569Sema::TemplateDeductionResult
2570Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002571 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002572 QualType ArgFunctionType,
2573 FunctionDecl *&Specialization,
2574 TemplateDeductionInfo &Info) {
2575 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2576 TemplateParameterList *TemplateParams
2577 = FunctionTemplate->getTemplateParameters();
2578 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Douglas Gregor83314aa2009-07-08 20:55:45 +00002580 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002581 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002582 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2583 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002584 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002585 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002586 if (TemplateDeductionResult Result
2587 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002588 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002589 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002590 &FunctionType, Info))
2591 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002592
2593 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002594 }
2595
2596 // Template argument deduction for function templates in a SFINAE context.
2597 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002598 SFINAETrap Trap(*this);
2599
John McCalleff92132010-02-02 02:21:27 +00002600 Deduced.resize(TemplateParams->size());
2601
Douglas Gregor4b52e252009-12-21 23:17:24 +00002602 if (!ArgFunctionType.isNull()) {
2603 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002604 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002605 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002606 FunctionType, ArgFunctionType, Info,
2607 Deduced, 0))
2608 return Result;
2609 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002610
2611 if (TemplateDeductionResult Result
2612 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2613 NumExplicitlySpecified,
2614 Specialization, Info))
2615 return Result;
2616
2617 // If the requested function type does not match the actual type of the
2618 // specialization, template argument deduction fails.
2619 if (!ArgFunctionType.isNull() &&
2620 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2621 return TDK_NonDeducedMismatch;
2622
2623 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002624}
2625
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002626/// \brief Deduce template arguments for a templated conversion
2627/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2628/// conversion function template specialization.
2629Sema::TemplateDeductionResult
2630Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2631 QualType ToType,
2632 CXXConversionDecl *&Specialization,
2633 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002634 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002635 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2636 QualType FromType = Conv->getConversionType();
2637
2638 // Canonicalize the types for deduction.
2639 QualType P = Context.getCanonicalType(FromType);
2640 QualType A = Context.getCanonicalType(ToType);
2641
2642 // C++0x [temp.deduct.conv]p3:
2643 // If P is a reference type, the type referred to by P is used for
2644 // type deduction.
2645 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2646 P = PRef->getPointeeType();
2647
2648 // C++0x [temp.deduct.conv]p3:
2649 // If A is a reference type, the type referred to by A is used
2650 // for type deduction.
2651 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2652 A = ARef->getPointeeType();
2653 // C++ [temp.deduct.conv]p2:
2654 //
Mike Stump1eb44332009-09-09 15:08:12 +00002655 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002656 else {
2657 assert(!A->isReferenceType() && "Reference types were handled above");
2658
2659 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002660 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002661 // of P for type deduction; otherwise,
2662 if (P->isArrayType())
2663 P = Context.getArrayDecayedType(P);
2664 // - If P is a function type, the pointer type produced by the
2665 // function-to-pointer standard conversion (4.3) is used in
2666 // place of P for type deduction; otherwise,
2667 else if (P->isFunctionType())
2668 P = Context.getPointerType(P);
2669 // - If P is a cv-qualified type, the top level cv-qualifiers of
2670 // P’s type are ignored for type deduction.
2671 else
2672 P = P.getUnqualifiedType();
2673
2674 // C++0x [temp.deduct.conv]p3:
2675 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2676 // type are ignored for type deduction.
2677 A = A.getUnqualifiedType();
2678 }
2679
2680 // Template argument deduction for function templates in a SFINAE context.
2681 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002682 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002683
2684 // C++ [temp.deduct.conv]p1:
2685 // Template argument deduction is done by comparing the return
2686 // type of the template conversion function (call it P) with the
2687 // type that is required as the result of the conversion (call it
2688 // A) as described in 14.8.2.4.
2689 TemplateParameterList *TemplateParams
2690 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002691 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002692 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002693
2694 // C++0x [temp.deduct.conv]p4:
2695 // In general, the deduction process attempts to find template
2696 // argument values that will make the deduced A identical to
2697 // A. However, there are two cases that allow a difference:
2698 unsigned TDF = 0;
2699 // - If the original A is a reference type, A can be more
2700 // cv-qualified than the deduced A (i.e., the type referred to
2701 // by the reference)
2702 if (ToType->isReferenceType())
2703 TDF |= TDF_ParamWithReferenceType;
2704 // - The deduced A can be another pointer or pointer to member
2705 // type that can be converted to A via a qualification
2706 // conversion.
2707 //
2708 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2709 // both P and A are pointers or member pointers. In this case, we
2710 // just ignore cv-qualifiers completely).
2711 if ((P->isPointerType() && A->isPointerType()) ||
2712 (P->isMemberPointerType() && P->isMemberPointerType()))
2713 TDF |= TDF_IgnoreQualifiers;
2714 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002715 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002716 P, A, Info, Deduced, TDF))
2717 return Result;
2718
2719 // FIXME: we need to check that the deduced A is the same as A,
2720 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002721
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002722 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002723 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002724 FunctionDecl *Spec = 0;
2725 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002726 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2727 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002728 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2729 return Result;
2730}
2731
Douglas Gregor4b52e252009-12-21 23:17:24 +00002732/// \brief Deduce template arguments for a function template when there is
2733/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2734///
2735/// \param FunctionTemplate the function template for which we are performing
2736/// template argument deduction.
2737///
2738/// \param ExplicitTemplateArguments the explicitly-specified template
2739/// arguments.
2740///
2741/// \param Specialization if template argument deduction was successful,
2742/// this will be set to the function template specialization produced by
2743/// template argument deduction.
2744///
2745/// \param Info the argument will be updated to provide additional information
2746/// about template argument deduction.
2747///
2748/// \returns the result of template argument deduction.
2749Sema::TemplateDeductionResult
2750Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2751 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2752 FunctionDecl *&Specialization,
2753 TemplateDeductionInfo &Info) {
2754 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2755 QualType(), Specialization, Info);
2756}
2757
Douglas Gregor8a514912009-09-14 18:39:43 +00002758/// \brief Stores the result of comparing the qualifiers of two types.
2759enum DeductionQualifierComparison {
2760 NeitherMoreQualified = 0,
2761 ParamMoreQualified,
2762 ArgMoreQualified
2763};
2764
2765/// \brief Deduce the template arguments during partial ordering by comparing
2766/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2767///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002768/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002769///
2770/// \param TemplateParams the template parameters that we are deducing
2771///
2772/// \param ParamIn the parameter type
2773///
2774/// \param ArgIn the argument type
2775///
2776/// \param Info information about the template argument deduction itself
2777///
2778/// \param Deduced the deduced template arguments
2779///
2780/// \returns the result of template argument deduction so far. Note that a
2781/// "success" result means that template argument deduction has not yet failed,
2782/// but it may still fail, later, for other reasons.
2783static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002784DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002785 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002786 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002787 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002788 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2789 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002790 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2791 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002792
2793 // C++0x [temp.deduct.partial]p5:
2794 // Before the partial ordering is done, certain transformations are
2795 // performed on the types used for partial ordering:
2796 // - If P is a reference type, P is replaced by the type referred to.
2797 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002798 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002799 Param = ParamRef->getPointeeType();
2800
2801 // - If A is a reference type, A is replaced by the type referred to.
2802 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002803 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002804 Arg = ArgRef->getPointeeType();
2805
John McCalle27ec8a2009-10-23 23:03:21 +00002806 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002807 // C++0x [temp.deduct.partial]p6:
2808 // If both P and A were reference types (before being replaced with the
2809 // type referred to above), determine which of the two types (if any) is
2810 // more cv-qualified than the other; otherwise the types are considered to
2811 // be equally cv-qualified for partial ordering purposes. The result of this
2812 // determination will be used below.
2813 //
2814 // We save this information for later, using it only when deduction
2815 // succeeds in both directions.
2816 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2817 if (Param.isMoreQualifiedThan(Arg))
2818 QualifierResult = ParamMoreQualified;
2819 else if (Arg.isMoreQualifiedThan(Param))
2820 QualifierResult = ArgMoreQualified;
2821 QualifierComparisons->push_back(QualifierResult);
2822 }
2823
2824 // C++0x [temp.deduct.partial]p7:
2825 // Remove any top-level cv-qualifiers:
2826 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2827 // version of P.
2828 Param = Param.getUnqualifiedType();
2829 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2830 // version of A.
2831 Arg = Arg.getUnqualifiedType();
2832
2833 // C++0x [temp.deduct.partial]p8:
2834 // Using the resulting types P and A the deduction is then done as
2835 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2836 // from the argument template is considered to be at least as specialized
2837 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002838 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002839 Deduced, TDF_None);
2840}
2841
2842static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002843MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2844 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002845 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002846 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002847
2848/// \brief If this is a non-static member function,
2849static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2850 CXXMethodDecl *Method,
2851 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2852 if (Method->isStatic())
2853 return;
2854
2855 // C++ [over.match.funcs]p4:
2856 //
2857 // For non-static member functions, the type of the implicit
2858 // object parameter is
2859 // — "lvalue reference to cv X" for functions declared without a
2860 // ref-qualifier or with the & ref-qualifier
2861 // - "rvalue reference to cv X" for functions declared with the
2862 // && ref-qualifier
2863 //
2864 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2865 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2866 ArgTy = Context.getQualifiedType(ArgTy,
2867 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2868 ArgTy = Context.getLValueReferenceType(ArgTy);
2869 ArgTypes.push_back(ArgTy);
2870}
2871
Douglas Gregor8a514912009-09-14 18:39:43 +00002872/// \brief Determine whether the function template \p FT1 is at least as
2873/// specialized as \p FT2.
2874static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002875 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002876 FunctionTemplateDecl *FT1,
2877 FunctionTemplateDecl *FT2,
2878 TemplatePartialOrderingContext TPOC,
2879 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2880 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2881 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2882 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2883 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2884
2885 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2886 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002887 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002888 Deduced.resize(TemplateParams->size());
2889
2890 // C++0x [temp.deduct.partial]p3:
2891 // The types used to determine the ordering depend on the context in which
2892 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002893 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002894 CXXMethodDecl *Method1 = 0;
2895 CXXMethodDecl *Method2 = 0;
2896 bool IsNonStatic2 = false;
2897 bool IsNonStatic1 = false;
2898 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002899 switch (TPOC) {
2900 case TPOC_Call: {
2901 // - In the context of a function call, the function parameter types are
2902 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002903 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2904 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2905 IsNonStatic1 = Method1 && !Method1->isStatic();
2906 IsNonStatic2 = Method2 && !Method2->isStatic();
2907
2908 // C++0x [temp.func.order]p3:
2909 // [...] If only one of the function templates is a non-static
2910 // member, that function template is considered to have a new
2911 // first parameter inserted in its function parameter list. The
2912 // new parameter is of type "reference to cv A," where cv are
2913 // the cv-qualifiers of the function template (if any) and A is
2914 // the class of which the function template is a member.
2915 //
2916 // C++98/03 doesn't have this provision, so instead we drop the
2917 // first argument of the free function or static member, which
2918 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002919 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002920 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2921 IsNonStatic2 && !IsNonStatic1;
2922 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002923 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2924 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002925 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002926
2927 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002928 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2929 IsNonStatic1 && !IsNonStatic2;
2930 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002931 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2932 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002933 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002934
2935 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002936 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002937 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002938 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002939 Args2[I],
2940 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002941 Info,
2942 Deduced,
2943 QualifierComparisons))
2944 return false;
2945
2946 break;
2947 }
2948
2949 case TPOC_Conversion:
2950 // - In the context of a call to a conversion operator, the return types
2951 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002952 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002953 TemplateParams,
2954 Proto2->getResultType(),
2955 Proto1->getResultType(),
2956 Info,
2957 Deduced,
2958 QualifierComparisons))
2959 return false;
2960 break;
2961
2962 case TPOC_Other:
2963 // - In other contexts (14.6.6.2) the function template’s function type
2964 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002965 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002966 TemplateParams,
2967 FD2->getType(),
2968 FD1->getType(),
2969 Info,
2970 Deduced,
2971 QualifierComparisons))
2972 return false;
2973 break;
2974 }
2975
2976 // C++0x [temp.deduct.partial]p11:
2977 // In most cases, all template parameters must have values in order for
2978 // deduction to succeed, but for partial ordering purposes a template
2979 // parameter may remain without a value provided it is not used in the
2980 // types being used for partial ordering. [ Note: a template parameter used
2981 // in a non-deduced context is considered used. -end note]
2982 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2983 for (; ArgIdx != NumArgs; ++ArgIdx)
2984 if (Deduced[ArgIdx].isNull())
2985 break;
2986
2987 if (ArgIdx == NumArgs) {
2988 // All template arguments were deduced. FT1 is at least as specialized
2989 // as FT2.
2990 return true;
2991 }
2992
Douglas Gregore73bb602009-09-14 21:25:05 +00002993 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002994 llvm::SmallVector<bool, 4> UsedParameters;
2995 UsedParameters.resize(TemplateParams->size());
2996 switch (TPOC) {
2997 case TPOC_Call: {
2998 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002999 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3000 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3001 TemplateParams->getDepth(), UsedParameters);
3002 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003003 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3004 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003005 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003006 break;
3007 }
3008
3009 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003010 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3011 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003012 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003013 break;
3014
3015 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003016 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3017 TemplateParams->getDepth(),
3018 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003019 break;
3020 }
3021
3022 for (; ArgIdx != NumArgs; ++ArgIdx)
3023 // If this argument had no value deduced but was used in one of the types
3024 // used for partial ordering, then deduction fails.
3025 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3026 return false;
3027
3028 return true;
3029}
3030
3031
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003032/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003033/// to the rules of function template partial ordering (C++ [temp.func.order]).
3034///
3035/// \param FT1 the first function template
3036///
3037/// \param FT2 the second function template
3038///
Douglas Gregor8a514912009-09-14 18:39:43 +00003039/// \param TPOC the context in which we are performing partial ordering of
3040/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003041///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003042/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003043/// template is more specialized, returns NULL.
3044FunctionTemplateDecl *
3045Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3046 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003047 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003048 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003049 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00003050 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
3051 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00003052 &QualifierComparisons);
3053
3054 if (Better1 != Better2) // We have a clear winner
3055 return Better1? FT1 : FT2;
3056
3057 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003058 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003059
3060
3061 // C++0x [temp.deduct.partial]p10:
3062 // If for each type being considered a given template is at least as
3063 // specialized for all types and more specialized for some set of types and
3064 // the other template is not more specialized for any types or is not at
3065 // least as specialized for any types, then the given template is more
3066 // specialized than the other template. Otherwise, neither template is more
3067 // specialized than the other.
3068 Better1 = false;
3069 Better2 = false;
3070 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3071 // C++0x [temp.deduct.partial]p9:
3072 // If, for a given type, deduction succeeds in both directions (i.e., the
3073 // types are identical after the transformations above) and if the type
3074 // from the argument template is more cv-qualified than the type from the
3075 // parameter template (as described above) that type is considered to be
3076 // more specialized than the other. If neither type is more cv-qualified
3077 // than the other then neither type is more specialized than the other.
3078 switch (QualifierComparisons[I]) {
3079 case NeitherMoreQualified:
3080 break;
3081
3082 case ParamMoreQualified:
3083 Better1 = true;
3084 if (Better2)
3085 return 0;
3086 break;
3087
3088 case ArgMoreQualified:
3089 Better2 = true;
3090 if (Better1)
3091 return 0;
3092 break;
3093 }
3094 }
3095
3096 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003097 if (Better1)
3098 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003099 else if (Better2)
3100 return FT2;
3101 else
3102 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003103}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003104
Douglas Gregord5a423b2009-09-25 18:43:00 +00003105/// \brief Determine if the two templates are equivalent.
3106static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3107 if (T1 == T2)
3108 return true;
3109
3110 if (!T1 || !T2)
3111 return false;
3112
3113 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3114}
3115
3116/// \brief Retrieve the most specialized of the given function template
3117/// specializations.
3118///
John McCallc373d482010-01-27 01:50:18 +00003119/// \param SpecBegin the start iterator of the function template
3120/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003121///
John McCallc373d482010-01-27 01:50:18 +00003122/// \param SpecEnd the end iterator of the function template
3123/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003124///
3125/// \param TPOC the partial ordering context to use to compare the function
3126/// template specializations.
3127///
3128/// \param Loc the location where the ambiguity or no-specializations
3129/// diagnostic should occur.
3130///
3131/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3132/// no matching candidates.
3133///
3134/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3135/// occurs.
3136///
3137/// \param CandidateDiag partial diagnostic used for each function template
3138/// specialization that is a candidate in the ambiguous ordering. One parameter
3139/// in this diagnostic should be unbound, which will correspond to the string
3140/// describing the template arguments for the function template specialization.
3141///
3142/// \param Index if non-NULL and the result of this function is non-nULL,
3143/// receives the index corresponding to the resulting function template
3144/// specialization.
3145///
3146/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003147/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003148///
3149/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3150/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003151UnresolvedSetIterator
3152Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3153 UnresolvedSetIterator SpecEnd,
3154 TemplatePartialOrderingContext TPOC,
3155 SourceLocation Loc,
3156 const PartialDiagnostic &NoneDiag,
3157 const PartialDiagnostic &AmbigDiag,
3158 const PartialDiagnostic &CandidateDiag) {
3159 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003160 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003161 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003162 }
3163
John McCallc373d482010-01-27 01:50:18 +00003164 if (SpecBegin + 1 == SpecEnd)
3165 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003166
3167 // Find the function template that is better than all of the templates it
3168 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003169 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003170 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003171 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003172 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003173 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3174 FunctionTemplateDecl *Challenger
3175 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003176 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003177 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003178 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003179 Challenger)) {
3180 Best = I;
3181 BestTemplate = Challenger;
3182 }
3183 }
3184
3185 // Make sure that the "best" function template is more specialized than all
3186 // of the others.
3187 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003188 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3189 FunctionTemplateDecl *Challenger
3190 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003191 if (I != Best &&
3192 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003193 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003194 BestTemplate)) {
3195 Ambiguous = true;
3196 break;
3197 }
3198 }
3199
3200 if (!Ambiguous) {
3201 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003202 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003203 }
3204
3205 // Diagnose the ambiguity.
3206 Diag(Loc, AmbigDiag);
3207
3208 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003209 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3210 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003211 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003212 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3213 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003214
John McCallc373d482010-01-27 01:50:18 +00003215 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003216}
3217
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003218/// \brief Returns the more specialized class template partial specialization
3219/// according to the rules of partial ordering of class template partial
3220/// specializations (C++ [temp.class.order]).
3221///
3222/// \param PS1 the first class template partial specialization
3223///
3224/// \param PS2 the second class template partial specialization
3225///
3226/// \returns the more specialized class template partial specialization. If
3227/// neither partial specialization is more specialized, returns NULL.
3228ClassTemplatePartialSpecializationDecl *
3229Sema::getMoreSpecializedPartialSpecialization(
3230 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003231 ClassTemplatePartialSpecializationDecl *PS2,
3232 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003233 // C++ [temp.class.order]p1:
3234 // For two class template partial specializations, the first is at least as
3235 // specialized as the second if, given the following rewrite to two
3236 // function templates, the first function template is at least as
3237 // specialized as the second according to the ordering rules for function
3238 // templates (14.6.6.2):
3239 // - the first function template has the same template parameters as the
3240 // first partial specialization and has a single function parameter
3241 // whose type is a class template specialization with the template
3242 // arguments of the first partial specialization, and
3243 // - the second function template has the same template parameters as the
3244 // second partial specialization and has a single function parameter
3245 // whose type is a class template specialization with the template
3246 // arguments of the second partial specialization.
3247 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003248 // Rather than synthesize function templates, we merely perform the
3249 // equivalent partial ordering by performing deduction directly on
3250 // the template arguments of the class template partial
3251 // specializations. This computation is slightly simpler than the
3252 // general problem of function template partial ordering, because
3253 // class template partial specializations are more constrained. We
3254 // know that every template parameter is deducible from the class
3255 // template partial specialization's template arguments, for
3256 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003257 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003258 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003259
3260 QualType PT1 = PS1->getInjectedSpecializationType();
3261 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003262
3263 // Determine whether PS1 is at least as specialized as PS2
3264 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003265 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003266 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003267 PT2,
3268 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003269 Info,
3270 Deduced,
3271 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003272 if (Better1) {
3273 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3274 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003275 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3276 PS1->getTemplateArgs(),
3277 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003278 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003279
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003280 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003281 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003282 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003283 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003284 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003285 PT1,
3286 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003287 Info,
3288 Deduced,
3289 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003290 if (Better2) {
3291 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3292 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003293 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3294 PS2->getTemplateArgs(),
3295 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003296 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003297
3298 if (Better1 == Better2)
3299 return 0;
3300
3301 return Better1? PS1 : PS2;
3302}
3303
Mike Stump1eb44332009-09-09 15:08:12 +00003304static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003305MarkUsedTemplateParameters(Sema &SemaRef,
3306 const TemplateArgument &TemplateArg,
3307 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003308 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003309 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003310
Douglas Gregore73bb602009-09-14 21:25:05 +00003311/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003312/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003313static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003314MarkUsedTemplateParameters(Sema &SemaRef,
3315 const Expr *E,
3316 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003317 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003318 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003319 // We can deduce from a pack expansion.
3320 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3321 E = Expansion->getPattern();
3322
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003323 // Skip through any implicit casts we added while type-checking.
3324 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3325 E = ICE->getSubExpr();
3326
Douglas Gregore73bb602009-09-14 21:25:05 +00003327 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3328 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003329 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003330 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003331 return;
3332
Mike Stump1eb44332009-09-09 15:08:12 +00003333 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003334 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3335 if (!NTTP)
3336 return;
3337
Douglas Gregored9c0f92009-10-29 00:04:11 +00003338 if (NTTP->getDepth() == Depth)
3339 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003340}
3341
Douglas Gregore73bb602009-09-14 21:25:05 +00003342/// \brief Mark the template parameters that are used by the given
3343/// nested name specifier.
3344static void
3345MarkUsedTemplateParameters(Sema &SemaRef,
3346 NestedNameSpecifier *NNS,
3347 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003348 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003349 llvm::SmallVectorImpl<bool> &Used) {
3350 if (!NNS)
3351 return;
3352
Douglas Gregored9c0f92009-10-29 00:04:11 +00003353 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3354 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003355 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003356 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003357}
3358
3359/// \brief Mark the template parameters that are used by the given
3360/// template name.
3361static void
3362MarkUsedTemplateParameters(Sema &SemaRef,
3363 TemplateName Name,
3364 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003365 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003366 llvm::SmallVectorImpl<bool> &Used) {
3367 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3368 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003369 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3370 if (TTP->getDepth() == Depth)
3371 Used[TTP->getIndex()] = true;
3372 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003373 return;
3374 }
3375
Douglas Gregor788cd062009-11-11 01:00:40 +00003376 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3377 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3378 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003379 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003380 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3381 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003382}
3383
3384/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003385/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003386static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003387MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3388 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003389 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003390 llvm::SmallVectorImpl<bool> &Used) {
3391 if (T.isNull())
3392 return;
3393
Douglas Gregor031a5882009-06-13 00:26:55 +00003394 // Non-dependent types have nothing deducible
3395 if (!T->isDependentType())
3396 return;
3397
3398 T = SemaRef.Context.getCanonicalType(T);
3399 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003400 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003401 MarkUsedTemplateParameters(SemaRef,
3402 cast<PointerType>(T)->getPointeeType(),
3403 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003404 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003405 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003406 break;
3407
3408 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003409 MarkUsedTemplateParameters(SemaRef,
3410 cast<BlockPointerType>(T)->getPointeeType(),
3411 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003412 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003413 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003414 break;
3415
3416 case Type::LValueReference:
3417 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003418 MarkUsedTemplateParameters(SemaRef,
3419 cast<ReferenceType>(T)->getPointeeType(),
3420 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003421 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003422 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003423 break;
3424
3425 case Type::MemberPointer: {
3426 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003427 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003428 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003429 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003430 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003431 break;
3432 }
3433
3434 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003435 MarkUsedTemplateParameters(SemaRef,
3436 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003437 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003438 // Fall through to check the element type
3439
3440 case Type::ConstantArray:
3441 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003442 MarkUsedTemplateParameters(SemaRef,
3443 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003444 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003445 break;
3446
3447 case Type::Vector:
3448 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003449 MarkUsedTemplateParameters(SemaRef,
3450 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003451 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003452 break;
3453
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003454 case Type::DependentSizedExtVector: {
3455 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003456 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003457 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003458 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003459 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003460 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003461 break;
3462 }
3463
Douglas Gregor031a5882009-06-13 00:26:55 +00003464 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003465 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003466 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003467 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003468 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003469 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003470 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003471 break;
3472 }
3473
Douglas Gregored9c0f92009-10-29 00:04:11 +00003474 case Type::TemplateTypeParm: {
3475 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3476 if (TTP->getDepth() == Depth)
3477 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003478 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003479 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003480
John McCall31f17ec2010-04-27 00:57:59 +00003481 case Type::InjectedClassName:
3482 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3483 // fall through
3484
Douglas Gregor031a5882009-06-13 00:26:55 +00003485 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003486 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003487 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003488 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003489 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003490
3491 // C++0x [temp.deduct.type]p9:
3492 // If the template argument list of P contains a pack expansion that is not
3493 // the last template argument, the entire template argument list is a
3494 // non-deduced context.
3495 if (OnlyDeduced &&
3496 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3497 break;
3498
Douglas Gregore73bb602009-09-14 21:25:05 +00003499 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003500 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3501 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003502 break;
3503 }
3504
Douglas Gregore73bb602009-09-14 21:25:05 +00003505 case Type::Complex:
3506 if (!OnlyDeduced)
3507 MarkUsedTemplateParameters(SemaRef,
3508 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003509 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003510 break;
3511
Douglas Gregor4714c122010-03-31 17:34:00 +00003512 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003513 if (!OnlyDeduced)
3514 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003515 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003516 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003517 break;
3518
John McCall33500952010-06-11 00:33:02 +00003519 case Type::DependentTemplateSpecialization: {
3520 const DependentTemplateSpecializationType *Spec
3521 = cast<DependentTemplateSpecializationType>(T);
3522 if (!OnlyDeduced)
3523 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3524 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003525
3526 // C++0x [temp.deduct.type]p9:
3527 // If the template argument list of P contains a pack expansion that is not
3528 // the last template argument, the entire template argument list is a
3529 // non-deduced context.
3530 if (OnlyDeduced &&
3531 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3532 break;
3533
John McCall33500952010-06-11 00:33:02 +00003534 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3535 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3536 Used);
3537 break;
3538 }
3539
John McCallad5e7382010-03-01 23:49:17 +00003540 case Type::TypeOf:
3541 if (!OnlyDeduced)
3542 MarkUsedTemplateParameters(SemaRef,
3543 cast<TypeOfType>(T)->getUnderlyingType(),
3544 OnlyDeduced, Depth, Used);
3545 break;
3546
3547 case Type::TypeOfExpr:
3548 if (!OnlyDeduced)
3549 MarkUsedTemplateParameters(SemaRef,
3550 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3551 OnlyDeduced, Depth, Used);
3552 break;
3553
3554 case Type::Decltype:
3555 if (!OnlyDeduced)
3556 MarkUsedTemplateParameters(SemaRef,
3557 cast<DecltypeType>(T)->getUnderlyingExpr(),
3558 OnlyDeduced, Depth, Used);
3559 break;
3560
Douglas Gregor7536dd52010-12-20 02:24:11 +00003561 case Type::PackExpansion:
3562 MarkUsedTemplateParameters(SemaRef,
3563 cast<PackExpansionType>(T)->getPattern(),
3564 OnlyDeduced, Depth, Used);
3565 break;
3566
Douglas Gregore73bb602009-09-14 21:25:05 +00003567 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003568 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003569 case Type::VariableArray:
3570 case Type::FunctionNoProto:
3571 case Type::Record:
3572 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003573 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003574 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003575 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003576 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003577#define TYPE(Class, Base)
3578#define ABSTRACT_TYPE(Class, Base)
3579#define DEPENDENT_TYPE(Class, Base)
3580#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3581#include "clang/AST/TypeNodes.def"
3582 break;
3583 }
3584}
3585
Douglas Gregore73bb602009-09-14 21:25:05 +00003586/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003587/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003588static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003589MarkUsedTemplateParameters(Sema &SemaRef,
3590 const TemplateArgument &TemplateArg,
3591 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003592 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003593 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003594 switch (TemplateArg.getKind()) {
3595 case TemplateArgument::Null:
3596 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003597 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003598 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003599
Douglas Gregor031a5882009-06-13 00:26:55 +00003600 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003601 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003602 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003603 break;
3604
Douglas Gregor788cd062009-11-11 01:00:40 +00003605 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003606 case TemplateArgument::TemplateExpansion:
3607 MarkUsedTemplateParameters(SemaRef,
3608 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003609 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003610 break;
3611
3612 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003613 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003614 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003615 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003616
Anders Carlssond01b1da2009-06-15 17:04:53 +00003617 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003618 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3619 PEnd = TemplateArg.pack_end();
3620 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003621 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003622 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003623 }
3624}
3625
3626/// \brief Mark the template parameters can be deduced by the given
3627/// template argument list.
3628///
3629/// \param TemplateArgs the template argument list from which template
3630/// parameters will be deduced.
3631///
3632/// \param Deduced a bit vector whose elements will be set to \c true
3633/// to indicate when the corresponding template parameter will be
3634/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003635void
Douglas Gregore73bb602009-09-14 21:25:05 +00003636Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003637 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003638 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003639 // C++0x [temp.deduct.type]p9:
3640 // If the template argument list of P contains a pack expansion that is not
3641 // the last template argument, the entire template argument list is a
3642 // non-deduced context.
3643 if (OnlyDeduced &&
3644 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3645 return;
3646
Douglas Gregor031a5882009-06-13 00:26:55 +00003647 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003648 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3649 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003650}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003651
3652/// \brief Marks all of the template parameters that will be deduced by a
3653/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003654void
3655Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3656 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003657 TemplateParameterList *TemplateParams
3658 = FunctionTemplate->getTemplateParameters();
3659 Deduced.clear();
3660 Deduced.resize(TemplateParams->size());
3661
3662 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3663 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3664 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003665 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003666}