blob: a0cbeca952054e7a555f7bbc3f9e82d8bf07f178 [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 Gregord3731192011-01-10 07:32:04 +0000481/// \brief Retrieve the depth and index of a template parameter.
Douglas Gregor603cfb42011-01-05 23:12:31 +0000482static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000483getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor603cfb42011-01-05 23:12:31 +0000484 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
485 return std::make_pair(TTP->getDepth(), TTP->getIndex());
486
487 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
488 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
489
490 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
491 return std::make_pair(TTP->getDepth(), TTP->getIndex());
492}
493
Douglas Gregord3731192011-01-10 07:32:04 +0000494/// \brief Retrieve the depth and index of an unexpanded parameter pack.
495static std::pair<unsigned, unsigned>
496getDepthAndIndex(UnexpandedParameterPack UPP) {
497 if (const TemplateTypeParmType *TTP
498 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
499 return std::make_pair(TTP->getDepth(), TTP->getIndex());
500
501 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
502}
503
Douglas Gregor603cfb42011-01-05 23:12:31 +0000504/// \brief Helper function to build a TemplateParameter when we don't
505/// know its type statically.
506static TemplateParameter makeTemplateParameter(Decl *D) {
507 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
508 return TemplateParameter(TTP);
509 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
510 return TemplateParameter(NTTP);
511
512 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
513}
514
Douglas Gregor54293852011-01-10 17:35:05 +0000515/// \brief Prepare to perform template argument deduction for all of the
516/// arguments in a set of argument packs.
517static void PrepareArgumentPackDeduction(Sema &S,
518 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
519 const llvm::SmallVectorImpl<unsigned> &PackIndices,
520 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
521 llvm::SmallVectorImpl<
522 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
523 // Save the deduced template arguments for each parameter pack expanded
524 // by this pack expansion, then clear out the deduction.
525 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
526 // Save the previously-deduced argument pack, then clear it out so that we
527 // can deduce a new argument pack.
528 SavedPacks[I] = Deduced[PackIndices[I]];
529 Deduced[PackIndices[I]] = TemplateArgument();
530
531 // If the template arugment pack was explicitly specified, add that to
532 // the set of deduced arguments.
533 const TemplateArgument *ExplicitArgs;
534 unsigned NumExplicitArgs;
535 if (NamedDecl *PartiallySubstitutedPack
536 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
537 &ExplicitArgs,
538 &NumExplicitArgs)) {
539 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
540 NewlyDeducedPacks[I].append(ExplicitArgs,
541 ExplicitArgs + NumExplicitArgs);
542 }
543 }
544}
545
Douglas Gregor603cfb42011-01-05 23:12:31 +0000546/// \brief Deduce the template arguments by comparing the list of parameter
547/// types to the list of argument types, as in the parameter-type-lists of
548/// function types (C++ [temp.deduct.type]p10).
549///
550/// \param S The semantic analysis object within which we are deducing
551///
552/// \param TemplateParams The template parameters that we are deducing
553///
554/// \param Params The list of parameter types
555///
556/// \param NumParams The number of types in \c Params
557///
558/// \param Args The list of argument types
559///
560/// \param NumArgs The number of types in \c Args
561///
562/// \param Info information about the template argument deduction itself
563///
564/// \param Deduced the deduced template arguments
565///
566/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
567/// how template argument deduction is performed.
568///
569/// \returns the result of template argument deduction so far. Note that a
570/// "success" result means that template argument deduction has not yet failed,
571/// but it may still fail, later, for other reasons.
572static Sema::TemplateDeductionResult
573DeduceTemplateArguments(Sema &S,
574 TemplateParameterList *TemplateParams,
575 const QualType *Params, unsigned NumParams,
576 const QualType *Args, unsigned NumArgs,
577 TemplateDeductionInfo &Info,
578 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
579 unsigned TDF) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000580 // Fast-path check to see if we have too many/too few arguments.
581 if (NumParams != NumArgs &&
582 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
583 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
584 return NumArgs < NumParams ? Sema::TDK_TooFewArguments
585 : Sema::TDK_TooManyArguments;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000586
587 // C++0x [temp.deduct.type]p10:
588 // Similarly, if P has a form that contains (T), then each parameter type
589 // Pi of the respective parameter-type- list of P is compared with the
590 // corresponding parameter type Ai of the corresponding parameter-type-list
591 // of A. [...]
592 unsigned ArgIdx = 0, ParamIdx = 0;
593 for (; ParamIdx != NumParams; ++ParamIdx) {
594 // Check argument types.
595 const PackExpansionType *Expansion
596 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
597 if (!Expansion) {
598 // Simple case: compare the parameter and argument types at this point.
599
600 // Make sure we have an argument.
601 if (ArgIdx >= NumArgs)
602 return Sema::TDK_TooFewArguments;
603
604 if (Sema::TemplateDeductionResult Result
605 = DeduceTemplateArguments(S, TemplateParams,
606 Params[ParamIdx],
607 Args[ArgIdx],
608 Info, Deduced, TDF))
609 return Result;
610
611 ++ArgIdx;
612 continue;
613 }
614
615 // C++0x [temp.deduct.type]p10:
616 // If the parameter-declaration corresponding to Pi is a function
617 // parameter pack, then the type of its declarator- id is compared with
618 // each remaining parameter type in the parameter-type-list of A. Each
619 // comparison deduces template arguments for subsequent positions in the
620 // template parameter packs expanded by the function parameter pack.
621
622 // Compute the set of template parameter indices that correspond to
623 // parameter packs expanded by the pack expansion.
624 llvm::SmallVector<unsigned, 2> PackIndices;
625 QualType Pattern = Expansion->getPattern();
626 {
627 llvm::BitVector SawIndices(TemplateParams->size());
628 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
629 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
630 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
631 unsigned Depth, Index;
632 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
633 if (Depth == 0 && !SawIndices[Index]) {
634 SawIndices[Index] = true;
635 PackIndices.push_back(Index);
636 }
637 }
638 }
639 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
640
Douglas Gregord3731192011-01-10 07:32:04 +0000641 // Keep track of the deduced template arguments for each parameter pack
642 // expanded by this pack expansion (the outer index) and for each
643 // template argument (the inner SmallVectors).
644 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
645 NewlyDeducedPacks(PackIndices.size());
Douglas Gregor603cfb42011-01-05 23:12:31 +0000646 llvm::SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000647 SavedPacks(PackIndices.size());
648 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
649 NewlyDeducedPacks);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000650
Douglas Gregor603cfb42011-01-05 23:12:31 +0000651 bool HasAnyArguments = false;
652 for (; ArgIdx < NumArgs; ++ArgIdx) {
653 HasAnyArguments = true;
654
655 // Deduce template arguments from the pattern.
656 if (Sema::TemplateDeductionResult Result
657 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
658 Info, Deduced))
659 return Result;
660
661 // Capture the deduced template arguments for each parameter pack expanded
662 // by this pack expansion, add them to the list of arguments we've deduced
663 // for that pack, then clear out the deduced argument.
664 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
665 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
666 if (!DeducedArg.isNull()) {
667 NewlyDeducedPacks[I].push_back(DeducedArg);
668 DeducedArg = DeducedTemplateArgument();
669 }
670 }
671 }
672
673 // Build argument packs for each of the parameter packs expanded by this
674 // pack expansion.
675 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
676 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
677 // We were not able to deduce anything for this parameter pack,
678 // so just restore the saved argument pack.
679 Deduced[PackIndices[I]] = SavedPacks[I];
680 continue;
681 }
682
683 DeducedTemplateArgument NewPack;
684
685 if (NewlyDeducedPacks[I].empty()) {
686 // If we deduced an empty argument pack, create it now.
687 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
688 } else {
689 TemplateArgument *ArgumentPack
690 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
691 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
692 ArgumentPack);
693 NewPack
694 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
695 NewlyDeducedPacks[I].size()),
696 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
697 }
698
699 DeducedTemplateArgument Result
700 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
701 if (Result.isNull()) {
702 Info.Param
703 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
704 Info.FirstArg = SavedPacks[I];
705 Info.SecondArg = NewPack;
706 return Sema::TDK_Inconsistent;
707 }
708
709 Deduced[PackIndices[I]] = Result;
710 }
711 }
712
713 // Make sure we don't have any extra arguments.
714 if (ArgIdx < NumArgs)
715 return Sema::TDK_TooManyArguments;
716
717 return Sema::TDK_Success;
718}
719
Douglas Gregor500d3312009-06-26 18:27:22 +0000720/// \brief Deduce the template arguments by comparing the parameter type and
721/// the argument type (C++ [temp.deduct.type]).
722///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000723/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000724///
725/// \param TemplateParams the template parameters that we are deducing
726///
727/// \param ParamIn the parameter type
728///
729/// \param ArgIn the argument type
730///
731/// \param Info information about the template argument deduction itself
732///
733/// \param Deduced the deduced template arguments
734///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000735/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000736/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000737///
738/// \returns the result of template argument deduction so far. Note that a
739/// "success" result means that template argument deduction has not yet failed,
740/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000741static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000742DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000743 TemplateParameterList *TemplateParams,
744 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000745 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000746 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000747 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000748 // We only want to look at the canonical types, since typedefs and
749 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000750 QualType Param = S.Context.getCanonicalType(ParamIn);
751 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000752
Douglas Gregor500d3312009-06-26 18:27:22 +0000753 // C++0x [temp.deduct.call]p4 bullet 1:
754 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000755 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000756 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000757 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000758 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000759 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000760 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
761 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000762 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000763 }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000765 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000766 if (!Param->isDependentType()) {
767 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
768
769 return Sema::TDK_NonDeducedMismatch;
770 }
771
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000772 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000773 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000774
Douglas Gregor199d9912009-06-05 00:53:49 +0000775 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000776 // A template type argument T, a template template argument TT or a
777 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000778 // the following forms:
779 //
780 // T
781 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000782 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000783 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000784 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000785 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000787 // If the argument type is an array type, move the qualifiers up to the
788 // top level, so they can be matched with the qualifiers on the parameter.
789 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000790 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000791 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000792 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000793 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000794 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000795 RecanonicalizeArg = true;
796 }
797 }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000799 // The argument type can not be less qualified than the parameter
800 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000801 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000802 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000803 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000804 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000805 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000806 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000807
808 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000809 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000810 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000811
812 // local manipulation is okay because it's canonical
813 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000814 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000815 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000817 DeducedTemplateArgument NewDeduced(DeducedType);
818 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
819 Deduced[Index],
820 NewDeduced);
821 if (Result.isNull()) {
822 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
823 Info.FirstArg = Deduced[Index];
824 Info.SecondArg = NewDeduced;
825 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000826 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000827
828 Deduced[Index] = Result;
829 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000830 }
831
Douglas Gregorf67875d2009-06-12 18:26:56 +0000832 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000833 Info.FirstArg = TemplateArgument(ParamIn);
834 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000835
Douglas Gregor508f1c82009-06-26 23:10:12 +0000836 // Check the cv-qualifiers on the parameter and argument types.
837 if (!(TDF & TDF_IgnoreQualifiers)) {
838 if (TDF & TDF_ParamWithReferenceType) {
839 if (Param.isMoreQualifiedThan(Arg))
840 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000841 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000842 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000843 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000844 }
845 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000846
Douglas Gregord560d502009-06-04 00:21:18 +0000847 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000848 // No deduction possible for these types
849 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000850 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Douglas Gregor199d9912009-06-05 00:53:49 +0000852 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000853 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000854 QualType PointeeType;
855 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
856 PointeeType = PointerArg->getPointeeType();
857 } else if (const ObjCObjectPointerType *PointerArg
858 = Arg->getAs<ObjCObjectPointerType>()) {
859 PointeeType = PointerArg->getPointeeType();
860 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000861 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Douglas Gregor41128772009-06-26 23:27:24 +0000864 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000865 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000866 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000867 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000868 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000869 }
Mike Stump1eb44332009-09-09 15:08:12 +0000870
Douglas Gregor199d9912009-06-05 00:53:49 +0000871 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000872 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000873 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000874 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000875 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000877 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000878 cast<LValueReferenceType>(Param)->getPointeeType(),
879 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000880 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000881 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000882
Douglas Gregor199d9912009-06-05 00:53:49 +0000883 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000884 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000885 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000886 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000887 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000889 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000890 cast<RValueReferenceType>(Param)->getPointeeType(),
891 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000892 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000893 }
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Douglas Gregor199d9912009-06-05 00:53:49 +0000895 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000896 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000897 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000898 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000899 if (!IncompleteArrayArg)
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;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000903 return DeduceTemplateArguments(S, TemplateParams,
904 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000905 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000906 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000907 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000908
909 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000910 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000911 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000912 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000913 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000914 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000915
916 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000917 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000918 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000919 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000920
John McCalle4f26e52010-08-19 00:20:19 +0000921 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000922 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000923 ConstantArrayParm->getElementType(),
924 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000925 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000926 }
927
Douglas Gregor199d9912009-06-05 00:53:49 +0000928 // type [i]
929 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000930 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000931 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000932 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000933
John McCalle4f26e52010-08-19 00:20:19 +0000934 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
935
Douglas Gregor199d9912009-06-05 00:53:49 +0000936 // Check the element type of the arrays
937 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000938 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000939 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000940 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000941 DependentArrayParm->getElementType(),
942 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000943 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000944 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Douglas Gregor199d9912009-06-05 00:53:49 +0000946 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000947 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000948 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
949 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000950 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
952 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000953 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000954 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000955 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000956 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000957 = dyn_cast<ConstantArrayType>(ArrayArg)) {
958 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000959 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
960 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000961 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000962 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000963 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000964 if (const DependentSizedArrayType *DependentArrayArg
965 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000966 if (DependentArrayArg->getSizeExpr())
967 return DeduceNonTypeTemplateArgument(S, NTTP,
968 DependentArrayArg->getSizeExpr(),
969 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Douglas Gregor199d9912009-06-05 00:53:49 +0000971 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000972 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000973 }
Mike Stump1eb44332009-09-09 15:08:12 +0000974
975 // type(*)(T)
976 // T(*)()
977 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000978 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000979 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000980 dyn_cast<FunctionProtoType>(Arg);
981 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000982 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000983
984 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000985 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000986
Mike Stump1eb44332009-09-09 15:08:12 +0000987 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000988 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000989 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000991 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000992 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000993
Anders Carlssona27fad52009-06-08 15:19:08 +0000994 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000995 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000996 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000997 FunctionProtoParam->getResultType(),
998 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000999 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001000 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Douglas Gregor603cfb42011-01-05 23:12:31 +00001002 return DeduceTemplateArguments(S, TemplateParams,
1003 FunctionProtoParam->arg_type_begin(),
1004 FunctionProtoParam->getNumArgs(),
1005 FunctionProtoArg->arg_type_begin(),
1006 FunctionProtoArg->getNumArgs(),
1007 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +00001008 }
Mike Stump1eb44332009-09-09 15:08:12 +00001009
John McCall3cb0ebd2010-03-10 03:28:59 +00001010 case Type::InjectedClassName: {
1011 // Treat a template's injected-class-name as if the template
1012 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001013 Param = cast<InjectedClassNameType>(Param)
1014 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001015 assert(isa<TemplateSpecializationType>(Param) &&
1016 "injected class name is not a template specialization type");
1017 // fall through
1018 }
1019
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001020 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001021 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001022 // TT<T>
1023 // TT<i>
1024 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001025 case Type::TemplateSpecialization: {
1026 const TemplateSpecializationType *SpecParam
1027 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001029 // Try to deduce template arguments from the template-id.
1030 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001031 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001032 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001034 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001035 // C++ [temp.deduct.call]p3b3:
1036 // If P is a class, and P has the form template-id, then A can be a
1037 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001038 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001039 // class pointed to by the deduced A.
1040 //
1041 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001042 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001043 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001044 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1045 // We cannot inspect base classes as part of deduction when the type
1046 // is incomplete, so either instantiate any templates necessary to
1047 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001048 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001049 return Result;
1050
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001051 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001052 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001053 // ToVisit is our stack of records that we still need to visit.
1054 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1055 llvm::SmallVector<const RecordType *, 8> ToVisit;
1056 ToVisit.push_back(RecordT);
1057 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001058 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1059 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001060 while (!ToVisit.empty()) {
1061 // Retrieve the next class in the inheritance hierarchy.
1062 const RecordType *NextT = ToVisit.back();
1063 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001065 // If we have already seen this type, skip it.
1066 if (!Visited.insert(NextT))
1067 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001069 // If this is a base class, try to perform template argument
1070 // deduction from it.
1071 if (NextT != RecordT) {
1072 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001073 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001074 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001076 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001077 // note that we had some success. Otherwise, ignore any deductions
1078 // from this base class.
1079 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001080 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001081 DeducedOrig = Deduced;
1082 }
1083 else
1084 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001085 }
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001087 // Visit base classes
1088 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1089 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1090 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001091 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001092 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001093 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001094 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001095 }
1096 }
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001098 if (Successful)
1099 return Sema::TDK_Success;
1100 }
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001102 }
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001104 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001105 }
1106
Douglas Gregor637a4092009-06-10 23:47:09 +00001107 // T type::*
1108 // T T::*
1109 // T (type::*)()
1110 // type (T::*)()
1111 // type (type::*)(T)
1112 // type (T::*)(T)
1113 // T (type::*)(T)
1114 // T (T::*)()
1115 // T (T::*)(T)
1116 case Type::MemberPointer: {
1117 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1118 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1119 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001120 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001121
Douglas Gregorf67875d2009-06-12 18:26:56 +00001122 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001123 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001124 MemPtrParam->getPointeeType(),
1125 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001126 Info, Deduced,
1127 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001128 return Result;
1129
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001130 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001131 QualType(MemPtrParam->getClass(), 0),
1132 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001133 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001134 }
1135
Anders Carlsson9a917e42009-06-12 22:56:54 +00001136 // (clang extension)
1137 //
Mike Stump1eb44332009-09-09 15:08:12 +00001138 // type(^)(T)
1139 // T(^)()
1140 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001141 case Type::BlockPointer: {
1142 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1143 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Anders Carlsson859ba502009-06-12 16:23:10 +00001145 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001146 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001148 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001149 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001150 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001151 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001152 }
1153
Douglas Gregor637a4092009-06-10 23:47:09 +00001154 case Type::TypeOfExpr:
1155 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001156 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001157 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001158 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001159
Douglas Gregord560d502009-06-04 00:21:18 +00001160 default:
1161 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001162 }
1163
1164 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001165 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001166}
1167
Douglas Gregorf67875d2009-06-12 18:26:56 +00001168static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001169DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001170 TemplateParameterList *TemplateParams,
1171 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001172 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001173 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001174 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001175 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001176 case TemplateArgument::Null:
1177 assert(false && "Null template argument in parameter list");
1178 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001179
1180 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001181 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001182 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001183 Arg.getAsType(), Info, Deduced, 0);
1184 Info.FirstArg = Param;
1185 Info.SecondArg = Arg;
1186 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001187
Douglas Gregor788cd062009-11-11 01:00:40 +00001188 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001189 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001190 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001191 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001192 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001193 Info.FirstArg = Param;
1194 Info.SecondArg = Arg;
1195 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001196
1197 case TemplateArgument::TemplateExpansion:
1198 llvm_unreachable("caller should handle pack expansions");
1199 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001200
Douglas Gregor199d9912009-06-05 00:53:49 +00001201 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001202 if (Arg.getKind() == TemplateArgument::Declaration &&
1203 Param.getAsDecl()->getCanonicalDecl() ==
1204 Arg.getAsDecl()->getCanonicalDecl())
1205 return Sema::TDK_Success;
1206
Douglas Gregorf67875d2009-06-12 18:26:56 +00001207 Info.FirstArg = Param;
1208 Info.SecondArg = Arg;
1209 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Douglas Gregor199d9912009-06-05 00:53:49 +00001211 case TemplateArgument::Integral:
1212 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001213 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001214 return Sema::TDK_Success;
1215
1216 Info.FirstArg = Param;
1217 Info.SecondArg = Arg;
1218 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001219 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001220
1221 if (Arg.getKind() == TemplateArgument::Expression) {
1222 Info.FirstArg = Param;
1223 Info.SecondArg = Arg;
1224 return Sema::TDK_NonDeducedMismatch;
1225 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001226
Douglas Gregorf67875d2009-06-12 18:26:56 +00001227 Info.FirstArg = Param;
1228 Info.SecondArg = Arg;
1229 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Douglas Gregor199d9912009-06-05 00:53:49 +00001231 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001232 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001233 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1234 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001235 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001236 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001237 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001238 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001239 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001240 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001241 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001242 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001243 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001244 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001245 Info, Deduced);
1246
Douglas Gregorf67875d2009-06-12 18:26:56 +00001247 Info.FirstArg = Param;
1248 Info.SecondArg = Arg;
1249 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001250 }
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Douglas Gregor199d9912009-06-05 00:53:49 +00001252 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001253 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001254 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001255 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001256 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001257 }
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Douglas Gregorf67875d2009-06-12 18:26:56 +00001259 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001260}
1261
Douglas Gregor20a55e22010-12-22 18:17:10 +00001262/// \brief Determine whether there is a template argument to be used for
1263/// deduction.
1264///
1265/// This routine "expands" argument packs in-place, overriding its input
1266/// parameters so that \c Args[ArgIdx] will be the available template argument.
1267///
1268/// \returns true if there is another template argument (which will be at
1269/// \c Args[ArgIdx]), false otherwise.
1270static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1271 unsigned &ArgIdx,
1272 unsigned &NumArgs) {
1273 if (ArgIdx == NumArgs)
1274 return false;
1275
1276 const TemplateArgument &Arg = Args[ArgIdx];
1277 if (Arg.getKind() != TemplateArgument::Pack)
1278 return true;
1279
1280 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1281 Args = Arg.pack_begin();
1282 NumArgs = Arg.pack_size();
1283 ArgIdx = 0;
1284 return ArgIdx < NumArgs;
1285}
1286
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001287/// \brief Determine whether the given set of template arguments has a pack
1288/// expansion that is not the last template argument.
1289static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1290 unsigned NumArgs) {
1291 unsigned ArgIdx = 0;
1292 while (ArgIdx < NumArgs) {
1293 const TemplateArgument &Arg = Args[ArgIdx];
1294
1295 // Unwrap argument packs.
1296 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1297 Args = Arg.pack_begin();
1298 NumArgs = Arg.pack_size();
1299 ArgIdx = 0;
1300 continue;
1301 }
1302
1303 ++ArgIdx;
1304 if (ArgIdx == NumArgs)
1305 return false;
1306
1307 if (Arg.isPackExpansion())
1308 return true;
1309 }
1310
1311 return false;
1312}
1313
Douglas Gregor20a55e22010-12-22 18:17:10 +00001314static Sema::TemplateDeductionResult
1315DeduceTemplateArguments(Sema &S,
1316 TemplateParameterList *TemplateParams,
1317 const TemplateArgument *Params, unsigned NumParams,
1318 const TemplateArgument *Args, unsigned NumArgs,
1319 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001320 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1321 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001322 // C++0x [temp.deduct.type]p9:
1323 // If the template argument list of P contains a pack expansion that is not
1324 // the last template argument, the entire template argument list is a
1325 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001326 if (hasPackExpansionBeforeEnd(Params, NumParams))
1327 return Sema::TDK_Success;
1328
Douglas Gregore02e2622010-12-22 21:19:48 +00001329 // C++0x [temp.deduct.type]p9:
1330 // If P has a form that contains <T> or <i>, then each argument Pi of the
1331 // respective template argument list P is compared with the corresponding
1332 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001333 unsigned ArgIdx = 0, ParamIdx = 0;
1334 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1335 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001336 // FIXME: Variadic templates.
1337 // What do we do if the argument is a pack expansion?
1338
Douglas Gregor20a55e22010-12-22 18:17:10 +00001339 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001340 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001341
1342 // Check whether we have enough arguments.
1343 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001344 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1345 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001346
Douglas Gregore02e2622010-12-22 21:19:48 +00001347 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001348 if (Sema::TemplateDeductionResult Result
1349 = DeduceTemplateArguments(S, TemplateParams,
1350 Params[ParamIdx], Args[ArgIdx],
1351 Info, Deduced))
1352 return Result;
1353
1354 // Move to the next argument.
1355 ++ArgIdx;
1356 continue;
1357 }
1358
Douglas Gregore02e2622010-12-22 21:19:48 +00001359 // The parameter is a pack expansion.
1360
1361 // C++0x [temp.deduct.type]p9:
1362 // If Pi is a pack expansion, then the pattern of Pi is compared with
1363 // each remaining argument in the template argument list of A. Each
1364 // comparison deduces template arguments for subsequent positions in the
1365 // template parameter packs expanded by Pi.
1366 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1367
1368 // Compute the set of template parameter indices that correspond to
1369 // parameter packs expanded by the pack expansion.
1370 llvm::SmallVector<unsigned, 2> PackIndices;
1371 {
1372 llvm::BitVector SawIndices(TemplateParams->size());
1373 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1374 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1375 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1376 unsigned Depth, Index;
1377 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1378 if (Depth == 0 && !SawIndices[Index]) {
1379 SawIndices[Index] = true;
1380 PackIndices.push_back(Index);
1381 }
1382 }
1383 }
1384 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1385
1386 // FIXME: If there are no remaining arguments, we can bail out early
1387 // and set any deduced parameter packs to an empty argument pack.
1388 // The latter part of this is a (minor) correctness issue.
1389
1390 // Save the deduced template arguments for each parameter pack expanded
1391 // by this pack expansion, then clear out the deduction.
1392 llvm::SmallVector<DeducedTemplateArgument, 2>
1393 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00001394 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1395 NewlyDeducedPacks(PackIndices.size());
1396 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1397 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001398
1399 // Keep track of the deduced template arguments for each parameter pack
1400 // expanded by this pack expansion (the outer index) and for each
1401 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001402 bool HasAnyArguments = false;
1403 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1404 HasAnyArguments = true;
1405
1406 // Deduce template arguments from the pattern.
1407 if (Sema::TemplateDeductionResult Result
1408 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1409 Info, Deduced))
1410 return Result;
1411
1412 // Capture the deduced template arguments for each parameter pack expanded
1413 // by this pack expansion, add them to the list of arguments we've deduced
1414 // for that pack, then clear out the deduced argument.
1415 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1416 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1417 if (!DeducedArg.isNull()) {
1418 NewlyDeducedPacks[I].push_back(DeducedArg);
1419 DeducedArg = DeducedTemplateArgument();
1420 }
1421 }
1422
1423 ++ArgIdx;
1424 }
1425
1426 // Build argument packs for each of the parameter packs expanded by this
1427 // pack expansion.
1428 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1429 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1430 // We were not able to deduce anything for this parameter pack,
1431 // so just restore the saved argument pack.
1432 Deduced[PackIndices[I]] = SavedPacks[I];
1433 continue;
1434 }
1435
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001436 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001437
1438 if (NewlyDeducedPacks[I].empty()) {
1439 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001440 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1441 } else {
1442 TemplateArgument *ArgumentPack
1443 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1444 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1445 ArgumentPack);
1446 NewPack
1447 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001448 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001449 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1450 }
1451
1452 DeducedTemplateArgument Result
1453 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1454 if (Result.isNull()) {
1455 Info.Param
1456 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1457 Info.FirstArg = SavedPacks[I];
1458 Info.SecondArg = NewPack;
1459 return Sema::TDK_Inconsistent;
1460 }
1461
1462 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001463 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001464 }
1465
1466 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001467 if (NumberOfArgumentsMustMatch &&
1468 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001469 return Sema::TDK_TooManyArguments;
1470
1471 return Sema::TDK_Success;
1472}
1473
Mike Stump1eb44332009-09-09 15:08:12 +00001474static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001475DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001476 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001477 const TemplateArgumentList &ParamList,
1478 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001479 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001480 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001481 return DeduceTemplateArguments(S, TemplateParams,
1482 ParamList.data(), ParamList.size(),
1483 ArgList.data(), ArgList.size(),
1484 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001485}
1486
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001487/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001488static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001489 const TemplateArgument &X,
1490 const TemplateArgument &Y) {
1491 if (X.getKind() != Y.getKind())
1492 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001494 switch (X.getKind()) {
1495 case TemplateArgument::Null:
1496 assert(false && "Comparing NULL template argument");
1497 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001499 case TemplateArgument::Type:
1500 return Context.getCanonicalType(X.getAsType()) ==
1501 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001503 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001504 return X.getAsDecl()->getCanonicalDecl() ==
1505 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Douglas Gregor788cd062009-11-11 01:00:40 +00001507 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001508 case TemplateArgument::TemplateExpansion:
1509 return Context.getCanonicalTemplateName(
1510 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1511 Context.getCanonicalTemplateName(
1512 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001513
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001514 case TemplateArgument::Integral:
1515 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Douglas Gregor788cd062009-11-11 01:00:40 +00001517 case TemplateArgument::Expression: {
1518 llvm::FoldingSetNodeID XID, YID;
1519 X.getAsExpr()->Profile(XID, Context, true);
1520 Y.getAsExpr()->Profile(YID, Context, true);
1521 return XID == YID;
1522 }
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001524 case TemplateArgument::Pack:
1525 if (X.pack_size() != Y.pack_size())
1526 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001527
1528 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1529 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001530 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001531 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001532 if (!isSameTemplateArg(Context, *XP, *YP))
1533 return false;
1534
1535 return true;
1536 }
1537
1538 return false;
1539}
1540
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001541/// \brief Allocate a TemplateArgumentLoc where all locations have
1542/// been initialized to the given location.
1543///
1544/// \param S The semantic analysis object.
1545///
1546/// \param The template argument we are producing template argument
1547/// location information for.
1548///
1549/// \param NTTPType For a declaration template argument, the type of
1550/// the non-type template parameter that corresponds to this template
1551/// argument.
1552///
1553/// \param Loc The source location to use for the resulting template
1554/// argument.
1555static TemplateArgumentLoc
1556getTrivialTemplateArgumentLoc(Sema &S,
1557 const TemplateArgument &Arg,
1558 QualType NTTPType,
1559 SourceLocation Loc) {
1560 switch (Arg.getKind()) {
1561 case TemplateArgument::Null:
1562 llvm_unreachable("Can't get a NULL template argument here");
1563 break;
1564
1565 case TemplateArgument::Type:
1566 return TemplateArgumentLoc(Arg,
1567 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1568
1569 case TemplateArgument::Declaration: {
1570 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001571 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001572 .takeAs<Expr>();
1573 return TemplateArgumentLoc(TemplateArgument(E), E);
1574 }
1575
1576 case TemplateArgument::Integral: {
1577 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001578 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001579 return TemplateArgumentLoc(TemplateArgument(E), E);
1580 }
1581
1582 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001583 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1584
1585 case TemplateArgument::TemplateExpansion:
1586 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1587
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001588 case TemplateArgument::Expression:
1589 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1590
1591 case TemplateArgument::Pack:
1592 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1593 }
1594
1595 return TemplateArgumentLoc();
1596}
1597
1598
1599/// \brief Convert the given deduced template argument and add it to the set of
1600/// fully-converted template arguments.
1601static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1602 DeducedTemplateArgument Arg,
1603 NamedDecl *Template,
1604 QualType NTTPType,
1605 TemplateDeductionInfo &Info,
1606 bool InFunctionTemplate,
1607 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1608 if (Arg.getKind() == TemplateArgument::Pack) {
1609 // This is a template argument pack, so check each of its arguments against
1610 // the template parameter.
1611 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1612 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001613 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001614 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001615 // When converting the deduced template argument, append it to the
1616 // general output list. We need to do this so that the template argument
1617 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001618 DeducedTemplateArgument InnerArg(*PA);
1619 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1620 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1621 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001622 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001623 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001624
1625 // Move the converted template argument into our argument pack.
1626 PackedArgsBuilder.push_back(Output.back());
1627 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001628 }
1629
1630 // Create the resulting argument pack.
1631 TemplateArgument *PackedArgs = 0;
1632 if (!PackedArgsBuilder.empty()) {
1633 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1634 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1635 }
1636 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1637 return false;
1638 }
1639
1640 // Convert the deduced template argument into a template
1641 // argument that we can check, almost as if the user had written
1642 // the template argument explicitly.
1643 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1644 Info.getLocation());
1645
1646 // Check the template argument, converting it as necessary.
1647 return S.CheckTemplateArgument(Param, ArgLoc,
1648 Template,
1649 Template->getLocation(),
1650 Template->getSourceRange().getEnd(),
1651 Output,
1652 InFunctionTemplate
1653 ? (Arg.wasDeducedFromArrayBound()
1654 ? Sema::CTAK_DeducedFromArrayBound
1655 : Sema::CTAK_Deduced)
1656 : Sema::CTAK_Specified);
1657}
1658
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001659/// Complete template argument deduction for a class template partial
1660/// specialization.
1661static Sema::TemplateDeductionResult
1662FinishTemplateArgumentDeduction(Sema &S,
1663 ClassTemplatePartialSpecializationDecl *Partial,
1664 const TemplateArgumentList &TemplateArgs,
1665 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001666 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001667 // Trap errors.
1668 Sema::SFINAETrap Trap(S);
1669
1670 Sema::ContextRAII SavedContext(S, Partial);
1671
1672 // C++ [temp.deduct.type]p2:
1673 // [...] or if any template argument remains neither deduced nor
1674 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001675 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001676 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1677 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001678 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001679 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001680 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001681 return Sema::TDK_Incomplete;
1682 }
1683
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001684 // We have deduced this argument, so it still needs to be
1685 // checked and converted.
1686
1687 // First, for a non-type template parameter type that is
1688 // initialized by a declaration, we need the type of the
1689 // corresponding non-type template parameter.
1690 QualType NTTPType;
1691 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001692 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001693 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001694 if (NTTPType->isDependentType()) {
1695 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1696 Builder.data(), Builder.size());
1697 NTTPType = S.SubstType(NTTPType,
1698 MultiLevelTemplateArgumentList(TemplateArgs),
1699 NTTP->getLocation(),
1700 NTTP->getDeclName());
1701 if (NTTPType.isNull()) {
1702 Info.Param = makeTemplateParameter(Param);
1703 // FIXME: These template arguments are temporary. Free them!
1704 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1705 Builder.data(),
1706 Builder.size()));
1707 return Sema::TDK_SubstitutionFailure;
1708 }
1709 }
1710 }
1711
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001712 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1713 Partial, NTTPType, Info, false,
1714 Builder)) {
1715 Info.Param = makeTemplateParameter(Param);
1716 // FIXME: These template arguments are temporary. Free them!
1717 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1718 Builder.size()));
1719 return Sema::TDK_SubstitutionFailure;
1720 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001721 }
1722
1723 // Form the template argument list from the deduced template arguments.
1724 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001725 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1726 Builder.size());
1727
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001728 Info.reset(DeducedArgumentList);
1729
1730 // Substitute the deduced template arguments into the template
1731 // arguments of the class template partial specialization, and
1732 // verify that the instantiated template arguments are both valid
1733 // and are equivalent to the template arguments originally provided
1734 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001735 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001736 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1737 const TemplateArgumentLoc *PartialTemplateArgs
1738 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001739
1740 // Note that we don't provide the langle and rangle locations.
1741 TemplateArgumentListInfo InstArgs;
1742
Douglas Gregore02e2622010-12-22 21:19:48 +00001743 if (S.Subst(PartialTemplateArgs,
1744 Partial->getNumTemplateArgsAsWritten(),
1745 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1746 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1747 if (ParamIdx >= Partial->getTemplateParameters()->size())
1748 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1749
1750 Decl *Param
1751 = const_cast<NamedDecl *>(
1752 Partial->getTemplateParameters()->getParam(ParamIdx));
1753 Info.Param = makeTemplateParameter(Param);
1754 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1755 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001756 }
1757
Douglas Gregor910f8002010-11-07 23:05:16 +00001758 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001759 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001760 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001761 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001762
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001763 TemplateParameterList *TemplateParams
1764 = ClassTemplate->getTemplateParameters();
1765 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001766 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001767 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001768 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001769 Info.FirstArg = TemplateArgs[I];
1770 Info.SecondArg = InstArg;
1771 return Sema::TDK_NonDeducedMismatch;
1772 }
1773 }
1774
1775 if (Trap.hasErrorOccurred())
1776 return Sema::TDK_SubstitutionFailure;
1777
1778 return Sema::TDK_Success;
1779}
1780
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001781/// \brief Perform template argument deduction to determine whether
1782/// the given template arguments match the given class template
1783/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001784Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001785Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001786 const TemplateArgumentList &TemplateArgs,
1787 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001788 // C++ [temp.class.spec.match]p2:
1789 // A partial specialization matches a given actual template
1790 // argument list if the template arguments of the partial
1791 // specialization can be deduced from the actual template argument
1792 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001793 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001794 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001795 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001796 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001797 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001798 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001799 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001800 TemplateArgs, Info, Deduced))
1801 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001802
Douglas Gregor637a4092009-06-10 23:47:09 +00001803 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001804 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001805 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001806 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001807
Douglas Gregorbb260412009-06-14 08:02:22 +00001808 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001809 return Sema::TDK_SubstitutionFailure;
1810
1811 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1812 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001813}
Douglas Gregor031a5882009-06-13 00:26:55 +00001814
Douglas Gregor41128772009-06-26 23:27:24 +00001815/// \brief Determine whether the given type T is a simple-template-id type.
1816static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001817 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001818 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001819 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Douglas Gregor41128772009-06-26 23:27:24 +00001821 return false;
1822}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001823
1824/// \brief Substitute the explicitly-provided template arguments into the
1825/// given function template according to C++ [temp.arg.explicit].
1826///
1827/// \param FunctionTemplate the function template into which the explicit
1828/// template arguments will be substituted.
1829///
Mike Stump1eb44332009-09-09 15:08:12 +00001830/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001831/// arguments.
1832///
Mike Stump1eb44332009-09-09 15:08:12 +00001833/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001834/// with the converted and checked explicit template arguments.
1835///
Mike Stump1eb44332009-09-09 15:08:12 +00001836/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001837/// parameters.
1838///
1839/// \param FunctionType if non-NULL, the result type of the function template
1840/// will also be instantiated and the pointed-to value will be updated with
1841/// the instantiated function type.
1842///
1843/// \param Info if substitution fails for any reason, this object will be
1844/// populated with more information about the failure.
1845///
1846/// \returns TDK_Success if substitution was successful, or some failure
1847/// condition.
1848Sema::TemplateDeductionResult
1849Sema::SubstituteExplicitTemplateArguments(
1850 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001851 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001852 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001853 llvm::SmallVectorImpl<QualType> &ParamTypes,
1854 QualType *FunctionType,
1855 TemplateDeductionInfo &Info) {
1856 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1857 TemplateParameterList *TemplateParams
1858 = FunctionTemplate->getTemplateParameters();
1859
John McCalld5532b62009-11-23 01:53:49 +00001860 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001861 // No arguments to substitute; just copy over the parameter types and
1862 // fill in the function type.
1863 for (FunctionDecl::param_iterator P = Function->param_begin(),
1864 PEnd = Function->param_end();
1865 P != PEnd;
1866 ++P)
1867 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Douglas Gregor83314aa2009-07-08 20:55:45 +00001869 if (FunctionType)
1870 *FunctionType = Function->getType();
1871 return TDK_Success;
1872 }
Mike Stump1eb44332009-09-09 15:08:12 +00001873
Douglas Gregor83314aa2009-07-08 20:55:45 +00001874 // Substitution of the explicit template arguments into a function template
1875 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001876 SFINAETrap Trap(*this);
1877
Douglas Gregor83314aa2009-07-08 20:55:45 +00001878 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001879 // Template arguments that are present shall be specified in the
1880 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001881 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001882 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001883 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
1885 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001886 // explicitly-specified template arguments against this function template,
1887 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001888 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001889 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001890 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1891 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001892 if (Inst)
1893 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Douglas Gregor83314aa2009-07-08 20:55:45 +00001895 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001896 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001897 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001898 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001899 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001900 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001901 if (Index >= TemplateParams->size())
1902 Index = TemplateParams->size() - 1;
1903 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001904 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001905 }
Mike Stump1eb44332009-09-09 15:08:12 +00001906
Douglas Gregor83314aa2009-07-08 20:55:45 +00001907 // Form the template argument list from the explicitly-specified
1908 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001909 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001910 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001911 Info.reset(ExplicitArgumentList);
Douglas Gregord3731192011-01-10 07:32:04 +00001912
John McCalldf41f182010-10-12 19:40:14 +00001913 // Template argument deduction and the final substitution should be
1914 // done in the context of the templated declaration. Explicit
1915 // argument substitution, on the other hand, needs to happen in the
1916 // calling context.
1917 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1918
Douglas Gregord3731192011-01-10 07:32:04 +00001919 // If we deduced template arguments for a template parameter pack,
1920 // note that the template argument pack is partially substituted and record
1921 // the explicit template arguments. They'll be used as part of deduction
1922 // for this template parameter pack.
1923 bool HasPartiallySubstitutedPack = false;
1924 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
1925 const TemplateArgument &Arg = Builder[I];
1926 if (Arg.getKind() == TemplateArgument::Pack) {
1927 HasPartiallySubstitutedPack = true;
1928 CurrentInstantiationScope->SetPartiallySubstitutedPack(
1929 TemplateParams->getParam(I),
1930 Arg.pack_begin(),
1931 Arg.pack_size());
1932 break;
1933 }
1934 }
1935
Douglas Gregor83314aa2009-07-08 20:55:45 +00001936 // Instantiate the types of each of the function parameters given the
1937 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00001938 if (SubstParmTypes(Function->getLocation(),
1939 Function->param_begin(), Function->getNumParams(),
1940 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1941 ParamTypes))
1942 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001943
1944 // If the caller wants a full function type back, instantiate the return
1945 // type and form that function type.
1946 if (FunctionType) {
1947 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001948 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001949 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001950 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001951
1952 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001953 = SubstType(Proto->getResultType(),
1954 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1955 Function->getTypeSpecStartLoc(),
1956 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001957 if (ResultType.isNull() || Trap.hasErrorOccurred())
1958 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001959
1960 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001961 ParamTypes.data(), ParamTypes.size(),
1962 Proto->isVariadic(),
1963 Proto->getTypeQuals(),
1964 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001965 Function->getDeclName(),
1966 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001967 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1968 return TDK_SubstitutionFailure;
1969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Douglas Gregor83314aa2009-07-08 20:55:45 +00001971 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001972 // Trailing template arguments that can be deduced (14.8.2) may be
1973 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001974 // template arguments can be deduced, they may all be omitted; in this
1975 // case, the empty template argument list <> itself may also be omitted.
1976 //
Douglas Gregord3731192011-01-10 07:32:04 +00001977 // Take all of the explicitly-specified arguments and put them into
1978 // the set of deduced template arguments. Explicitly-specified
1979 // parameter packs, however, will be set to NULL since the deduction
1980 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001981 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00001982 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
1983 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
1984 if (Arg.getKind() == TemplateArgument::Pack)
1985 Deduced.push_back(DeducedTemplateArgument());
1986 else
1987 Deduced.push_back(Arg);
1988 }
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Douglas Gregor83314aa2009-07-08 20:55:45 +00001990 return TDK_Success;
1991}
1992
Mike Stump1eb44332009-09-09 15:08:12 +00001993/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001994/// checking the deduced template arguments for completeness and forming
1995/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001996Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001997Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001998 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1999 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002000 FunctionDecl *&Specialization,
2001 TemplateDeductionInfo &Info) {
2002 TemplateParameterList *TemplateParams
2003 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregor83314aa2009-07-08 20:55:45 +00002005 // Template argument deduction for function templates in a SFINAE context.
2006 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002007 SFINAETrap Trap(*this);
2008
Douglas Gregor83314aa2009-07-08 20:55:45 +00002009 // Enter a new template instantiation context while we instantiate the
2010 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002011 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002012 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002013 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2014 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002015 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002016 return TDK_InstantiationDepth;
2017
John McCall96db3102010-04-29 01:18:58 +00002018 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002019
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002020 // C++ [temp.deduct.type]p2:
2021 // [...] or if any template argument remains neither deduced nor
2022 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00002023 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002024 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2025 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002026
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002027 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002028 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002029 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002030 // argument, because it was explicitly-specified. Just record the
2031 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002032 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002033 continue;
2034 }
2035
2036 // We have deduced this argument, so it still needs to be
2037 // checked and converted.
2038
2039 // First, for a non-type template parameter type that is
2040 // initialized by a declaration, we need the type of the
2041 // corresponding non-type template parameter.
2042 QualType NTTPType;
2043 if (NonTypeTemplateParmDecl *NTTP
2044 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002045 NTTPType = NTTP->getType();
2046 if (NTTPType->isDependentType()) {
2047 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2048 Builder.data(), Builder.size());
2049 NTTPType = SubstType(NTTPType,
2050 MultiLevelTemplateArgumentList(TemplateArgs),
2051 NTTP->getLocation(),
2052 NTTP->getDeclName());
2053 if (NTTPType.isNull()) {
2054 Info.Param = makeTemplateParameter(Param);
2055 // FIXME: These template arguments are temporary. Free them!
2056 Info.reset(TemplateArgumentList::CreateCopy(Context,
2057 Builder.data(),
2058 Builder.size()));
2059 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002060 }
2061 }
2062 }
2063
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002064 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2065 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002066 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002067 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002068 // FIXME: These template arguments are temporary. Free them!
2069 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002070 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002071 return TDK_SubstitutionFailure;
2072 }
2073
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002074 continue;
2075 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002076
2077 // C++0x [temp.arg.explicit]p3:
2078 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2079 // be deduced to an empty sequence of template arguments.
2080 // FIXME: Where did the word "trailing" come from?
2081 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002082 // We may have had explicitly-specified template arguments for this
2083 // template parameter pack. If so, our empty deduction extends the
2084 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2085 const TemplateArgument *ExplicitArgs;
2086 unsigned NumExplicitArgs;
2087 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2088 &NumExplicitArgs)
2089 == Param)
2090 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2091 else
2092 Builder.push_back(TemplateArgument(0, 0));
2093
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002094 continue;
2095 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002096
2097 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002098 TemplateArgumentLoc DefArg
2099 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2100 FunctionTemplate->getLocation(),
2101 FunctionTemplate->getSourceRange().getEnd(),
2102 Param,
2103 Builder);
2104
2105 // If there was no default argument, deduction is incomplete.
2106 if (DefArg.getArgument().isNull()) {
2107 Info.Param = makeTemplateParameter(
2108 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2109 return TDK_Incomplete;
2110 }
2111
2112 // Check whether we can actually use the default argument.
2113 if (CheckTemplateArgument(Param, DefArg,
2114 FunctionTemplate,
2115 FunctionTemplate->getLocation(),
2116 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002117 Builder,
2118 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002119 Info.Param = makeTemplateParameter(
2120 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002121 // FIXME: These template arguments are temporary. Free them!
2122 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2123 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002124 return TDK_SubstitutionFailure;
2125 }
2126
2127 // If we get here, we successfully used the default template argument.
2128 }
2129
2130 // Form the template argument list from the deduced template arguments.
2131 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002132 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002133 Info.reset(DeducedArgumentList);
2134
Mike Stump1eb44332009-09-09 15:08:12 +00002135 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002136 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002137 DeclContext *Owner = FunctionTemplate->getDeclContext();
2138 if (FunctionTemplate->getFriendObjectKind())
2139 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002140 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002141 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002142 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002143 if (!Specialization)
2144 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Douglas Gregorf8825742009-09-15 18:26:13 +00002146 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2147 FunctionTemplate->getCanonicalDecl());
2148
Mike Stump1eb44332009-09-09 15:08:12 +00002149 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002150 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002151 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2152 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002153 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Douglas Gregor83314aa2009-07-08 20:55:45 +00002155 // There may have been an error that did not prevent us from constructing a
2156 // declaration. Mark the declaration invalid and return with a substitution
2157 // failure.
2158 if (Trap.hasErrorOccurred()) {
2159 Specialization->setInvalidDecl(true);
2160 return TDK_SubstitutionFailure;
2161 }
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Douglas Gregor9b623632010-10-12 23:32:35 +00002163 // If we suppressed any diagnostics while performing template argument
2164 // deduction, and if we haven't already instantiated this declaration,
2165 // keep track of these diagnostics. They'll be emitted if this specialization
2166 // is actually used.
2167 if (Info.diag_begin() != Info.diag_end()) {
2168 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2169 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2170 if (Pos == SuppressedDiagnostics.end())
2171 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2172 .append(Info.diag_begin(), Info.diag_end());
2173 }
2174
Mike Stump1eb44332009-09-09 15:08:12 +00002175 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002176}
2177
John McCall9c72c602010-08-27 09:08:28 +00002178/// Gets the type of a function for template-argument-deducton
2179/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002180static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002181 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002182 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002183 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002184 if (Method->isInstance()) {
2185 // An instance method that's referenced in a form that doesn't
2186 // look like a member pointer is just invalid.
2187 if (!R.HasFormOfMemberPointer) return QualType();
2188
John McCalleff92132010-02-02 02:21:27 +00002189 return Context.getMemberPointerType(Fn->getType(),
2190 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002191 }
2192
2193 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002194 return Context.getPointerType(Fn->getType());
2195}
2196
2197/// Apply the deduction rules for overload sets.
2198///
2199/// \return the null type if this argument should be treated as an
2200/// undeduced context
2201static QualType
2202ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002203 Expr *Arg, QualType ParamType,
2204 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002205
2206 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002207
John McCall9c72c602010-08-27 09:08:28 +00002208 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002209
Douglas Gregor75f21af2010-08-30 21:04:23 +00002210 // C++0x [temp.deduct.call]p4
2211 unsigned TDF = 0;
2212 if (ParamWasReference)
2213 TDF |= TDF_ParamWithReferenceType;
2214 if (R.IsAddressOfOperand)
2215 TDF |= TDF_IgnoreQualifiers;
2216
John McCalleff92132010-02-02 02:21:27 +00002217 // If there were explicit template arguments, we can only find
2218 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2219 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002220 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002221 // But we can still look for an explicit specialization.
2222 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002223 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002224 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002225 return QualType();
2226 }
2227
2228 // C++0x [temp.deduct.call]p6:
2229 // When P is a function type, pointer to function type, or pointer
2230 // to member function type:
2231
2232 if (!ParamType->isFunctionType() &&
2233 !ParamType->isFunctionPointerType() &&
2234 !ParamType->isMemberFunctionPointerType())
2235 return QualType();
2236
2237 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002238 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2239 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002240 NamedDecl *D = (*I)->getUnderlyingDecl();
2241
2242 // - If the argument is an overload set containing one or more
2243 // function templates, the parameter is treated as a
2244 // non-deduced context.
2245 if (isa<FunctionTemplateDecl>(D))
2246 return QualType();
2247
2248 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002249 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2250 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002251
Douglas Gregor75f21af2010-08-30 21:04:23 +00002252 // Function-to-pointer conversion.
2253 if (!ParamWasReference && ParamType->isPointerType() &&
2254 ArgType->isFunctionType())
2255 ArgType = S.Context.getPointerType(ArgType);
2256
John McCalleff92132010-02-02 02:21:27 +00002257 // - If the argument is an overload set (not containing function
2258 // templates), trial argument deduction is attempted using each
2259 // of the members of the set. If deduction succeeds for only one
2260 // of the overload set members, that member is used as the
2261 // argument value for the deduction. If deduction succeeds for
2262 // more than one member of the overload set the parameter is
2263 // treated as a non-deduced context.
2264
2265 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2266 // Type deduction is done independently for each P/A pair, and
2267 // the deduced template argument values are then combined.
2268 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002269 llvm::SmallVector<DeducedTemplateArgument, 8>
2270 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002271 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002272 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002273 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002274 ParamType, ArgType,
2275 Info, Deduced, TDF);
2276 if (Result) continue;
2277 if (!Match.isNull()) return QualType();
2278 Match = ArgType;
2279 }
2280
2281 return Match;
2282}
2283
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002284/// \brief Perform the adjustments to the parameter and argument types
2285/// described in C++ [temp.deduct.call].
2286///
2287/// \returns true if the caller should not attempt to perform any template
2288/// argument deduction based on this P/A pair.
2289static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2290 TemplateParameterList *TemplateParams,
2291 QualType &ParamType,
2292 QualType &ArgType,
2293 Expr *Arg,
2294 unsigned &TDF) {
2295 // C++0x [temp.deduct.call]p3:
2296 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2297 // are ignored for type deduction.
2298 if (ParamType.getCVRQualifiers())
2299 ParamType = ParamType.getLocalUnqualifiedType();
2300 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2301 if (ParamRefType) {
2302 // [...] If P is a reference type, the type referred to by P is used
2303 // for type deduction.
2304 ParamType = ParamRefType->getPointeeType();
2305 }
2306
2307 // Overload sets usually make this parameter an undeduced
2308 // context, but there are sometimes special circumstances.
2309 if (ArgType == S.Context.OverloadTy) {
2310 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2311 Arg, ParamType,
2312 ParamRefType != 0);
2313 if (ArgType.isNull())
2314 return true;
2315 }
2316
2317 if (ParamRefType) {
2318 // C++0x [temp.deduct.call]p3:
2319 // [...] If P is of the form T&&, where T is a template parameter, and
2320 // the argument is an lvalue, the type A& is used in place of A for
2321 // type deduction.
2322 if (ParamRefType->isRValueReferenceType() &&
2323 ParamRefType->getAs<TemplateTypeParmType>() &&
2324 Arg->isLValue())
2325 ArgType = S.Context.getLValueReferenceType(ArgType);
2326 } else {
2327 // C++ [temp.deduct.call]p2:
2328 // If P is not a reference type:
2329 // - If A is an array type, the pointer type produced by the
2330 // array-to-pointer standard conversion (4.2) is used in place of
2331 // A for type deduction; otherwise,
2332 if (ArgType->isArrayType())
2333 ArgType = S.Context.getArrayDecayedType(ArgType);
2334 // - If A is a function type, the pointer type produced by the
2335 // function-to-pointer standard conversion (4.3) is used in place
2336 // of A for type deduction; otherwise,
2337 else if (ArgType->isFunctionType())
2338 ArgType = S.Context.getPointerType(ArgType);
2339 else {
2340 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2341 // type are ignored for type deduction.
2342 QualType CanonArgType = S.Context.getCanonicalType(ArgType);
2343 if (ArgType.getCVRQualifiers())
2344 ArgType = ArgType.getUnqualifiedType();
2345 }
2346 }
2347
2348 // C++0x [temp.deduct.call]p4:
2349 // In general, the deduction process attempts to find template argument
2350 // values that will make the deduced A identical to A (after the type A
2351 // is transformed as described above). [...]
2352 TDF = TDF_SkipNonDependent;
2353
2354 // - If the original P is a reference type, the deduced A (i.e., the
2355 // type referred to by the reference) can be more cv-qualified than
2356 // the transformed A.
2357 if (ParamRefType)
2358 TDF |= TDF_ParamWithReferenceType;
2359 // - The transformed A can be another pointer or pointer to member
2360 // type that can be converted to the deduced A via a qualification
2361 // conversion (4.4).
2362 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2363 ArgType->isObjCObjectPointerType())
2364 TDF |= TDF_IgnoreQualifiers;
2365 // - If P is a class and P has the form simple-template-id, then the
2366 // transformed A can be a derived class of the deduced A. Likewise,
2367 // if P is a pointer to a class of the form simple-template-id, the
2368 // transformed A can be a pointer to a derived class pointed to by
2369 // the deduced A.
2370 if (isSimpleTemplateIdType(ParamType) ||
2371 (isa<PointerType>(ParamType) &&
2372 isSimpleTemplateIdType(
2373 ParamType->getAs<PointerType>()->getPointeeType())))
2374 TDF |= TDF_DerivedClass;
2375
2376 return false;
2377}
2378
Douglas Gregore53060f2009-06-25 22:08:12 +00002379/// \brief Perform template argument deduction from a function call
2380/// (C++ [temp.deduct.call]).
2381///
2382/// \param FunctionTemplate the function template for which we are performing
2383/// template argument deduction.
2384///
Douglas Gregor48026d22010-01-11 18:40:55 +00002385/// \param ExplicitTemplateArguments the explicit template arguments provided
2386/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002387///
Douglas Gregore53060f2009-06-25 22:08:12 +00002388/// \param Args the function call arguments
2389///
2390/// \param NumArgs the number of arguments in Args
2391///
Douglas Gregor48026d22010-01-11 18:40:55 +00002392/// \param Name the name of the function being called. This is only significant
2393/// when the function template is a conversion function template, in which
2394/// case this routine will also perform template argument deduction based on
2395/// the function to which
2396///
Douglas Gregore53060f2009-06-25 22:08:12 +00002397/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002398/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002399/// template argument deduction.
2400///
2401/// \param Info the argument will be updated to provide additional information
2402/// about template argument deduction.
2403///
2404/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002405Sema::TemplateDeductionResult
2406Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002407 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002408 Expr **Args, unsigned NumArgs,
2409 FunctionDecl *&Specialization,
2410 TemplateDeductionInfo &Info) {
2411 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002412
Douglas Gregore53060f2009-06-25 22:08:12 +00002413 // C++ [temp.deduct.call]p1:
2414 // Template argument deduction is done by comparing each function template
2415 // parameter type (call it P) with the type of the corresponding argument
2416 // of the call (call it A) as described below.
2417 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002418 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002419 return TDK_TooFewArguments;
2420 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002421 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002422 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002423 if (Proto->isTemplateVariadic())
2424 /* Do nothing */;
2425 else if (Proto->isVariadic())
2426 CheckArgs = Function->getNumParams();
2427 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002428 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002429 }
Mike Stump1eb44332009-09-09 15:08:12 +00002430
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002431 // The types of the parameters from which we will perform template argument
2432 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002433 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002434 TemplateParameterList *TemplateParams
2435 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002436 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002437 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002438 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002439 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002440 TemplateDeductionResult Result =
2441 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002442 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002443 Deduced,
2444 ParamTypes,
2445 0,
2446 Info);
2447 if (Result)
2448 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002449
2450 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002451 } else {
2452 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002453 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002454 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2455 }
Mike Stump1eb44332009-09-09 15:08:12 +00002456
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002457 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002458 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002459 unsigned ArgIdx = 0;
2460 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2461 ParamIdx != NumParams; ++ParamIdx) {
2462 QualType ParamType = ParamTypes[ParamIdx];
2463
2464 const PackExpansionType *ParamExpansion
2465 = dyn_cast<PackExpansionType>(ParamType);
2466 if (!ParamExpansion) {
2467 // Simple case: matching a function parameter to a function argument.
2468 if (ArgIdx >= CheckArgs)
2469 break;
2470
2471 Expr *Arg = Args[ArgIdx++];
2472 QualType ArgType = Arg->getType();
2473 unsigned TDF = 0;
2474 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2475 ParamType, ArgType, Arg,
2476 TDF))
2477 continue;
2478
2479 if (TemplateDeductionResult Result
2480 = ::DeduceTemplateArguments(*this, TemplateParams,
2481 ParamType, ArgType, Info, Deduced,
2482 TDF))
2483 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002484
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002485 // FIXME: we need to check that the deduced A is the same as A,
2486 // modulo the various allowed differences.
2487 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002488 }
2489
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002490 // C++0x [temp.deduct.call]p1:
2491 // For a function parameter pack that occurs at the end of the
2492 // parameter-declaration-list, the type A of each remaining argument of
2493 // the call is compared with the type P of the declarator-id of the
2494 // function parameter pack. Each comparison deduces template arguments
2495 // for subsequent positions in the template parameter packs expanded by
2496 // the function parameter pack.
2497 QualType ParamPattern = ParamExpansion->getPattern();
2498 llvm::SmallVector<unsigned, 2> PackIndices;
2499 {
2500 llvm::BitVector SawIndices(TemplateParams->size());
2501 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2502 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2503 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2504 unsigned Depth, Index;
2505 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2506 if (Depth == 0 && !SawIndices[Index]) {
2507 SawIndices[Index] = true;
2508 PackIndices.push_back(Index);
2509 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002510 }
2511 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002512 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2513
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002514 // Keep track of the deduced template arguments for each parameter pack
2515 // expanded by this pack expansion (the outer index) and for each
2516 // template argument (the inner SmallVectors).
2517 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00002518 NewlyDeducedPacks(PackIndices.size());
Douglas Gregord3731192011-01-10 07:32:04 +00002519 llvm::SmallVector<DeducedTemplateArgument, 2>
2520 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00002521 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
2522 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002523 bool HasAnyArguments = false;
2524 for (; ArgIdx < NumArgs; ++ArgIdx) {
2525 HasAnyArguments = true;
2526
2527 ParamType = ParamPattern;
2528 Expr *Arg = Args[ArgIdx];
2529 QualType ArgType = Arg->getType();
2530 unsigned TDF = 0;
2531 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2532 ParamType, ArgType, Arg,
2533 TDF)) {
2534 // We can't actually perform any deduction for this argument, so stop
2535 // deduction at this point.
2536 ++ArgIdx;
2537 break;
2538 }
2539
2540 if (TemplateDeductionResult Result
2541 = ::DeduceTemplateArguments(*this, TemplateParams,
2542 ParamType, ArgType, Info, Deduced,
2543 TDF))
2544 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002546 // Capture the deduced template arguments for each parameter pack expanded
2547 // by this pack expansion, add them to the list of arguments we've deduced
2548 // for that pack, then clear out the deduced argument.
2549 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2550 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2551 if (!DeducedArg.isNull()) {
2552 NewlyDeducedPacks[I].push_back(DeducedArg);
2553 DeducedArg = DeducedTemplateArgument();
2554 }
2555 }
2556 }
2557
2558 // Build argument packs for each of the parameter packs expanded by this
2559 // pack expansion.
2560 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2561 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
2562 // We were not able to deduce anything for this parameter pack,
2563 // so just restore the saved argument pack.
2564 Deduced[PackIndices[I]] = SavedPacks[I];
2565 continue;
2566 }
2567
2568 DeducedTemplateArgument NewPack;
2569
2570 if (NewlyDeducedPacks[I].empty()) {
2571 // If we deduced an empty argument pack, create it now.
2572 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
2573 } else {
2574 TemplateArgument *ArgumentPack
2575 = new (Context) TemplateArgument [NewlyDeducedPacks[I].size()];
2576 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
2577 ArgumentPack);
2578 NewPack
2579 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
2580 NewlyDeducedPacks[I].size()),
2581 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
2582 }
2583
2584 DeducedTemplateArgument Result
2585 = checkDeducedTemplateArguments(Context, SavedPacks[I], NewPack);
2586 if (Result.isNull()) {
2587 Info.Param
2588 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
2589 Info.FirstArg = SavedPacks[I];
2590 Info.SecondArg = NewPack;
2591 return Sema::TDK_Inconsistent;
2592 }
2593
2594 Deduced[PackIndices[I]] = Result;
2595 }
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002597 // After we've matching against a parameter pack, we're done.
2598 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002599 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002600
Mike Stump1eb44332009-09-09 15:08:12 +00002601 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002602 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002603 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002604}
2605
Douglas Gregor83314aa2009-07-08 20:55:45 +00002606/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002607/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2608/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002609///
2610/// \param FunctionTemplate the function template for which we are performing
2611/// template argument deduction.
2612///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002613/// \param ExplicitTemplateArguments the explicitly-specified template
2614/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002615///
2616/// \param ArgFunctionType the function type that will be used as the
2617/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002618/// function template's function type. This type may be NULL, if there is no
2619/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002620///
2621/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002622/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002623/// template argument deduction.
2624///
2625/// \param Info the argument will be updated to provide additional information
2626/// about template argument deduction.
2627///
2628/// \returns the result of template argument deduction.
2629Sema::TemplateDeductionResult
2630Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002631 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002632 QualType ArgFunctionType,
2633 FunctionDecl *&Specialization,
2634 TemplateDeductionInfo &Info) {
2635 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2636 TemplateParameterList *TemplateParams
2637 = FunctionTemplate->getTemplateParameters();
2638 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Douglas Gregor83314aa2009-07-08 20:55:45 +00002640 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002641 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002642 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2643 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002644 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002645 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002646 if (TemplateDeductionResult Result
2647 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002648 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002649 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002650 &FunctionType, Info))
2651 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002652
2653 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002654 }
2655
2656 // Template argument deduction for function templates in a SFINAE context.
2657 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002658 SFINAETrap Trap(*this);
2659
John McCalleff92132010-02-02 02:21:27 +00002660 Deduced.resize(TemplateParams->size());
2661
Douglas Gregor4b52e252009-12-21 23:17:24 +00002662 if (!ArgFunctionType.isNull()) {
2663 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002664 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002665 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002666 FunctionType, ArgFunctionType, Info,
2667 Deduced, 0))
2668 return Result;
2669 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002670
2671 if (TemplateDeductionResult Result
2672 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2673 NumExplicitlySpecified,
2674 Specialization, Info))
2675 return Result;
2676
2677 // If the requested function type does not match the actual type of the
2678 // specialization, template argument deduction fails.
2679 if (!ArgFunctionType.isNull() &&
2680 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2681 return TDK_NonDeducedMismatch;
2682
2683 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002684}
2685
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002686/// \brief Deduce template arguments for a templated conversion
2687/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2688/// conversion function template specialization.
2689Sema::TemplateDeductionResult
2690Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2691 QualType ToType,
2692 CXXConversionDecl *&Specialization,
2693 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002694 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002695 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2696 QualType FromType = Conv->getConversionType();
2697
2698 // Canonicalize the types for deduction.
2699 QualType P = Context.getCanonicalType(FromType);
2700 QualType A = Context.getCanonicalType(ToType);
2701
2702 // C++0x [temp.deduct.conv]p3:
2703 // If P is a reference type, the type referred to by P is used for
2704 // type deduction.
2705 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2706 P = PRef->getPointeeType();
2707
2708 // C++0x [temp.deduct.conv]p3:
2709 // If A is a reference type, the type referred to by A is used
2710 // for type deduction.
2711 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2712 A = ARef->getPointeeType();
2713 // C++ [temp.deduct.conv]p2:
2714 //
Mike Stump1eb44332009-09-09 15:08:12 +00002715 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002716 else {
2717 assert(!A->isReferenceType() && "Reference types were handled above");
2718
2719 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002720 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002721 // of P for type deduction; otherwise,
2722 if (P->isArrayType())
2723 P = Context.getArrayDecayedType(P);
2724 // - If P is a function type, the pointer type produced by the
2725 // function-to-pointer standard conversion (4.3) is used in
2726 // place of P for type deduction; otherwise,
2727 else if (P->isFunctionType())
2728 P = Context.getPointerType(P);
2729 // - If P is a cv-qualified type, the top level cv-qualifiers of
2730 // P’s type are ignored for type deduction.
2731 else
2732 P = P.getUnqualifiedType();
2733
2734 // C++0x [temp.deduct.conv]p3:
2735 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2736 // type are ignored for type deduction.
2737 A = A.getUnqualifiedType();
2738 }
2739
2740 // Template argument deduction for function templates in a SFINAE context.
2741 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002742 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002743
2744 // C++ [temp.deduct.conv]p1:
2745 // Template argument deduction is done by comparing the return
2746 // type of the template conversion function (call it P) with the
2747 // type that is required as the result of the conversion (call it
2748 // A) as described in 14.8.2.4.
2749 TemplateParameterList *TemplateParams
2750 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002751 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002752 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002753
2754 // C++0x [temp.deduct.conv]p4:
2755 // In general, the deduction process attempts to find template
2756 // argument values that will make the deduced A identical to
2757 // A. However, there are two cases that allow a difference:
2758 unsigned TDF = 0;
2759 // - If the original A is a reference type, A can be more
2760 // cv-qualified than the deduced A (i.e., the type referred to
2761 // by the reference)
2762 if (ToType->isReferenceType())
2763 TDF |= TDF_ParamWithReferenceType;
2764 // - The deduced A can be another pointer or pointer to member
2765 // type that can be converted to A via a qualification
2766 // conversion.
2767 //
2768 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2769 // both P and A are pointers or member pointers. In this case, we
2770 // just ignore cv-qualifiers completely).
2771 if ((P->isPointerType() && A->isPointerType()) ||
2772 (P->isMemberPointerType() && P->isMemberPointerType()))
2773 TDF |= TDF_IgnoreQualifiers;
2774 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002775 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002776 P, A, Info, Deduced, TDF))
2777 return Result;
2778
2779 // FIXME: we need to check that the deduced A is the same as A,
2780 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002781
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002782 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002783 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002784 FunctionDecl *Spec = 0;
2785 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002786 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2787 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002788 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2789 return Result;
2790}
2791
Douglas Gregor4b52e252009-12-21 23:17:24 +00002792/// \brief Deduce template arguments for a function template when there is
2793/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2794///
2795/// \param FunctionTemplate the function template for which we are performing
2796/// template argument deduction.
2797///
2798/// \param ExplicitTemplateArguments the explicitly-specified template
2799/// arguments.
2800///
2801/// \param Specialization if template argument deduction was successful,
2802/// this will be set to the function template specialization produced by
2803/// template argument deduction.
2804///
2805/// \param Info the argument will be updated to provide additional information
2806/// about template argument deduction.
2807///
2808/// \returns the result of template argument deduction.
2809Sema::TemplateDeductionResult
2810Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2811 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2812 FunctionDecl *&Specialization,
2813 TemplateDeductionInfo &Info) {
2814 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2815 QualType(), Specialization, Info);
2816}
2817
Douglas Gregor8a514912009-09-14 18:39:43 +00002818/// \brief Stores the result of comparing the qualifiers of two types.
2819enum DeductionQualifierComparison {
2820 NeitherMoreQualified = 0,
2821 ParamMoreQualified,
2822 ArgMoreQualified
2823};
2824
2825/// \brief Deduce the template arguments during partial ordering by comparing
2826/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2827///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002828/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002829///
2830/// \param TemplateParams the template parameters that we are deducing
2831///
2832/// \param ParamIn the parameter type
2833///
2834/// \param ArgIn the argument type
2835///
2836/// \param Info information about the template argument deduction itself
2837///
2838/// \param Deduced the deduced template arguments
2839///
2840/// \returns the result of template argument deduction so far. Note that a
2841/// "success" result means that template argument deduction has not yet failed,
2842/// but it may still fail, later, for other reasons.
2843static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002844DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002845 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002846 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002847 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002848 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2849 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002850 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2851 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002852
2853 // C++0x [temp.deduct.partial]p5:
2854 // Before the partial ordering is done, certain transformations are
2855 // performed on the types used for partial ordering:
2856 // - If P is a reference type, P is replaced by the type referred to.
2857 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002858 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002859 Param = ParamRef->getPointeeType();
2860
2861 // - If A is a reference type, A is replaced by the type referred to.
2862 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002863 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002864 Arg = ArgRef->getPointeeType();
2865
John McCalle27ec8a2009-10-23 23:03:21 +00002866 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002867 // C++0x [temp.deduct.partial]p6:
2868 // If both P and A were reference types (before being replaced with the
2869 // type referred to above), determine which of the two types (if any) is
2870 // more cv-qualified than the other; otherwise the types are considered to
2871 // be equally cv-qualified for partial ordering purposes. The result of this
2872 // determination will be used below.
2873 //
2874 // We save this information for later, using it only when deduction
2875 // succeeds in both directions.
2876 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2877 if (Param.isMoreQualifiedThan(Arg))
2878 QualifierResult = ParamMoreQualified;
2879 else if (Arg.isMoreQualifiedThan(Param))
2880 QualifierResult = ArgMoreQualified;
2881 QualifierComparisons->push_back(QualifierResult);
2882 }
2883
2884 // C++0x [temp.deduct.partial]p7:
2885 // Remove any top-level cv-qualifiers:
2886 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2887 // version of P.
2888 Param = Param.getUnqualifiedType();
2889 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2890 // version of A.
2891 Arg = Arg.getUnqualifiedType();
2892
2893 // C++0x [temp.deduct.partial]p8:
2894 // Using the resulting types P and A the deduction is then done as
2895 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2896 // from the argument template is considered to be at least as specialized
2897 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002898 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002899 Deduced, TDF_None);
2900}
2901
2902static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002903MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2904 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002905 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002906 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002907
2908/// \brief If this is a non-static member function,
2909static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2910 CXXMethodDecl *Method,
2911 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2912 if (Method->isStatic())
2913 return;
2914
2915 // C++ [over.match.funcs]p4:
2916 //
2917 // For non-static member functions, the type of the implicit
2918 // object parameter is
2919 // — "lvalue reference to cv X" for functions declared without a
2920 // ref-qualifier or with the & ref-qualifier
2921 // - "rvalue reference to cv X" for functions declared with the
2922 // && ref-qualifier
2923 //
2924 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2925 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2926 ArgTy = Context.getQualifiedType(ArgTy,
2927 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2928 ArgTy = Context.getLValueReferenceType(ArgTy);
2929 ArgTypes.push_back(ArgTy);
2930}
2931
Douglas Gregor8a514912009-09-14 18:39:43 +00002932/// \brief Determine whether the function template \p FT1 is at least as
2933/// specialized as \p FT2.
2934static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002935 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002936 FunctionTemplateDecl *FT1,
2937 FunctionTemplateDecl *FT2,
2938 TemplatePartialOrderingContext TPOC,
2939 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2940 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2941 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2942 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2943 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2944
2945 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2946 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002947 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002948 Deduced.resize(TemplateParams->size());
2949
2950 // C++0x [temp.deduct.partial]p3:
2951 // The types used to determine the ordering depend on the context in which
2952 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002953 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002954 CXXMethodDecl *Method1 = 0;
2955 CXXMethodDecl *Method2 = 0;
2956 bool IsNonStatic2 = false;
2957 bool IsNonStatic1 = false;
2958 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002959 switch (TPOC) {
2960 case TPOC_Call: {
2961 // - In the context of a function call, the function parameter types are
2962 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002963 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2964 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2965 IsNonStatic1 = Method1 && !Method1->isStatic();
2966 IsNonStatic2 = Method2 && !Method2->isStatic();
2967
2968 // C++0x [temp.func.order]p3:
2969 // [...] If only one of the function templates is a non-static
2970 // member, that function template is considered to have a new
2971 // first parameter inserted in its function parameter list. The
2972 // new parameter is of type "reference to cv A," where cv are
2973 // the cv-qualifiers of the function template (if any) and A is
2974 // the class of which the function template is a member.
2975 //
2976 // C++98/03 doesn't have this provision, so instead we drop the
2977 // first argument of the free function or static member, which
2978 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002979 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002980 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2981 IsNonStatic2 && !IsNonStatic1;
2982 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002983 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2984 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002985 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002986
2987 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002988 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2989 IsNonStatic1 && !IsNonStatic2;
2990 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002991 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2992 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002993 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002994
2995 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002996 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002997 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002998 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002999 Args2[I],
3000 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00003001 Info,
3002 Deduced,
3003 QualifierComparisons))
3004 return false;
3005
3006 break;
3007 }
3008
3009 case TPOC_Conversion:
3010 // - In the context of a call to a conversion operator, the return types
3011 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003012 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00003013 TemplateParams,
3014 Proto2->getResultType(),
3015 Proto1->getResultType(),
3016 Info,
3017 Deduced,
3018 QualifierComparisons))
3019 return false;
3020 break;
3021
3022 case TPOC_Other:
3023 // - In other contexts (14.6.6.2) the function template’s function type
3024 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003025 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00003026 TemplateParams,
3027 FD2->getType(),
3028 FD1->getType(),
3029 Info,
3030 Deduced,
3031 QualifierComparisons))
3032 return false;
3033 break;
3034 }
3035
3036 // C++0x [temp.deduct.partial]p11:
3037 // In most cases, all template parameters must have values in order for
3038 // deduction to succeed, but for partial ordering purposes a template
3039 // parameter may remain without a value provided it is not used in the
3040 // types being used for partial ordering. [ Note: a template parameter used
3041 // in a non-deduced context is considered used. -end note]
3042 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3043 for (; ArgIdx != NumArgs; ++ArgIdx)
3044 if (Deduced[ArgIdx].isNull())
3045 break;
3046
3047 if (ArgIdx == NumArgs) {
3048 // All template arguments were deduced. FT1 is at least as specialized
3049 // as FT2.
3050 return true;
3051 }
3052
Douglas Gregore73bb602009-09-14 21:25:05 +00003053 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003054 llvm::SmallVector<bool, 4> UsedParameters;
3055 UsedParameters.resize(TemplateParams->size());
3056 switch (TPOC) {
3057 case TPOC_Call: {
3058 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003059 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3060 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3061 TemplateParams->getDepth(), UsedParameters);
3062 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003063 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3064 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003065 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003066 break;
3067 }
3068
3069 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003070 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3071 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003072 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003073 break;
3074
3075 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003076 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3077 TemplateParams->getDepth(),
3078 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003079 break;
3080 }
3081
3082 for (; ArgIdx != NumArgs; ++ArgIdx)
3083 // If this argument had no value deduced but was used in one of the types
3084 // used for partial ordering, then deduction fails.
3085 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3086 return false;
3087
3088 return true;
3089}
3090
3091
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003092/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003093/// to the rules of function template partial ordering (C++ [temp.func.order]).
3094///
3095/// \param FT1 the first function template
3096///
3097/// \param FT2 the second function template
3098///
Douglas Gregor8a514912009-09-14 18:39:43 +00003099/// \param TPOC the context in which we are performing partial ordering of
3100/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003101///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003102/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003103/// template is more specialized, returns NULL.
3104FunctionTemplateDecl *
3105Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3106 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003107 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003108 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003109 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00003110 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
3111 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00003112 &QualifierComparisons);
3113
3114 if (Better1 != Better2) // We have a clear winner
3115 return Better1? FT1 : FT2;
3116
3117 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003118 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003119
3120
3121 // C++0x [temp.deduct.partial]p10:
3122 // If for each type being considered a given template is at least as
3123 // specialized for all types and more specialized for some set of types and
3124 // the other template is not more specialized for any types or is not at
3125 // least as specialized for any types, then the given template is more
3126 // specialized than the other template. Otherwise, neither template is more
3127 // specialized than the other.
3128 Better1 = false;
3129 Better2 = false;
3130 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3131 // C++0x [temp.deduct.partial]p9:
3132 // If, for a given type, deduction succeeds in both directions (i.e., the
3133 // types are identical after the transformations above) and if the type
3134 // from the argument template is more cv-qualified than the type from the
3135 // parameter template (as described above) that type is considered to be
3136 // more specialized than the other. If neither type is more cv-qualified
3137 // than the other then neither type is more specialized than the other.
3138 switch (QualifierComparisons[I]) {
3139 case NeitherMoreQualified:
3140 break;
3141
3142 case ParamMoreQualified:
3143 Better1 = true;
3144 if (Better2)
3145 return 0;
3146 break;
3147
3148 case ArgMoreQualified:
3149 Better2 = true;
3150 if (Better1)
3151 return 0;
3152 break;
3153 }
3154 }
3155
3156 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003157 if (Better1)
3158 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003159 else if (Better2)
3160 return FT2;
3161 else
3162 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003163}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003164
Douglas Gregord5a423b2009-09-25 18:43:00 +00003165/// \brief Determine if the two templates are equivalent.
3166static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3167 if (T1 == T2)
3168 return true;
3169
3170 if (!T1 || !T2)
3171 return false;
3172
3173 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3174}
3175
3176/// \brief Retrieve the most specialized of the given function template
3177/// specializations.
3178///
John McCallc373d482010-01-27 01:50:18 +00003179/// \param SpecBegin the start iterator of the function template
3180/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003181///
John McCallc373d482010-01-27 01:50:18 +00003182/// \param SpecEnd the end iterator of the function template
3183/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003184///
3185/// \param TPOC the partial ordering context to use to compare the function
3186/// template specializations.
3187///
3188/// \param Loc the location where the ambiguity or no-specializations
3189/// diagnostic should occur.
3190///
3191/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3192/// no matching candidates.
3193///
3194/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3195/// occurs.
3196///
3197/// \param CandidateDiag partial diagnostic used for each function template
3198/// specialization that is a candidate in the ambiguous ordering. One parameter
3199/// in this diagnostic should be unbound, which will correspond to the string
3200/// describing the template arguments for the function template specialization.
3201///
3202/// \param Index if non-NULL and the result of this function is non-nULL,
3203/// receives the index corresponding to the resulting function template
3204/// specialization.
3205///
3206/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003207/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003208///
3209/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3210/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003211UnresolvedSetIterator
3212Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3213 UnresolvedSetIterator SpecEnd,
3214 TemplatePartialOrderingContext TPOC,
3215 SourceLocation Loc,
3216 const PartialDiagnostic &NoneDiag,
3217 const PartialDiagnostic &AmbigDiag,
3218 const PartialDiagnostic &CandidateDiag) {
3219 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003220 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003221 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003222 }
3223
John McCallc373d482010-01-27 01:50:18 +00003224 if (SpecBegin + 1 == SpecEnd)
3225 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003226
3227 // Find the function template that is better than all of the templates it
3228 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003229 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003230 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003231 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003232 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003233 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3234 FunctionTemplateDecl *Challenger
3235 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003236 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003237 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003238 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003239 Challenger)) {
3240 Best = I;
3241 BestTemplate = Challenger;
3242 }
3243 }
3244
3245 // Make sure that the "best" function template is more specialized than all
3246 // of the others.
3247 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003248 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3249 FunctionTemplateDecl *Challenger
3250 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003251 if (I != Best &&
3252 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003253 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003254 BestTemplate)) {
3255 Ambiguous = true;
3256 break;
3257 }
3258 }
3259
3260 if (!Ambiguous) {
3261 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003262 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003263 }
3264
3265 // Diagnose the ambiguity.
3266 Diag(Loc, AmbigDiag);
3267
3268 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003269 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3270 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003271 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003272 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3273 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003274
John McCallc373d482010-01-27 01:50:18 +00003275 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003276}
3277
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003278/// \brief Returns the more specialized class template partial specialization
3279/// according to the rules of partial ordering of class template partial
3280/// specializations (C++ [temp.class.order]).
3281///
3282/// \param PS1 the first class template partial specialization
3283///
3284/// \param PS2 the second class template partial specialization
3285///
3286/// \returns the more specialized class template partial specialization. If
3287/// neither partial specialization is more specialized, returns NULL.
3288ClassTemplatePartialSpecializationDecl *
3289Sema::getMoreSpecializedPartialSpecialization(
3290 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003291 ClassTemplatePartialSpecializationDecl *PS2,
3292 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003293 // C++ [temp.class.order]p1:
3294 // For two class template partial specializations, the first is at least as
3295 // specialized as the second if, given the following rewrite to two
3296 // function templates, the first function template is at least as
3297 // specialized as the second according to the ordering rules for function
3298 // templates (14.6.6.2):
3299 // - the first function template has the same template parameters as the
3300 // first partial specialization and has a single function parameter
3301 // whose type is a class template specialization with the template
3302 // arguments of the first partial specialization, and
3303 // - the second function template has the same template parameters as the
3304 // second partial specialization and has a single function parameter
3305 // whose type is a class template specialization with the template
3306 // arguments of the second partial specialization.
3307 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003308 // Rather than synthesize function templates, we merely perform the
3309 // equivalent partial ordering by performing deduction directly on
3310 // the template arguments of the class template partial
3311 // specializations. This computation is slightly simpler than the
3312 // general problem of function template partial ordering, because
3313 // class template partial specializations are more constrained. We
3314 // know that every template parameter is deducible from the class
3315 // template partial specialization's template arguments, for
3316 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003317 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003318 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003319
3320 QualType PT1 = PS1->getInjectedSpecializationType();
3321 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003322
3323 // Determine whether PS1 is at least as specialized as PS2
3324 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003325 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003326 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003327 PT2,
3328 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003329 Info,
3330 Deduced,
3331 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003332 if (Better1) {
3333 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3334 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003335 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3336 PS1->getTemplateArgs(),
3337 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003338 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003339
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003340 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003341 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003342 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003343 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003344 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003345 PT1,
3346 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003347 Info,
3348 Deduced,
3349 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003350 if (Better2) {
3351 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3352 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003353 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3354 PS2->getTemplateArgs(),
3355 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003356 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003357
3358 if (Better1 == Better2)
3359 return 0;
3360
3361 return Better1? PS1 : PS2;
3362}
3363
Mike Stump1eb44332009-09-09 15:08:12 +00003364static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003365MarkUsedTemplateParameters(Sema &SemaRef,
3366 const TemplateArgument &TemplateArg,
3367 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003368 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003369 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003370
Douglas Gregore73bb602009-09-14 21:25:05 +00003371/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003372/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003373static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003374MarkUsedTemplateParameters(Sema &SemaRef,
3375 const Expr *E,
3376 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003377 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003378 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003379 // We can deduce from a pack expansion.
3380 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3381 E = Expansion->getPattern();
3382
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003383 // Skip through any implicit casts we added while type-checking.
3384 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3385 E = ICE->getSubExpr();
3386
Douglas Gregore73bb602009-09-14 21:25:05 +00003387 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3388 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003389 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003390 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003391 return;
3392
Mike Stump1eb44332009-09-09 15:08:12 +00003393 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003394 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3395 if (!NTTP)
3396 return;
3397
Douglas Gregored9c0f92009-10-29 00:04:11 +00003398 if (NTTP->getDepth() == Depth)
3399 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003400}
3401
Douglas Gregore73bb602009-09-14 21:25:05 +00003402/// \brief Mark the template parameters that are used by the given
3403/// nested name specifier.
3404static void
3405MarkUsedTemplateParameters(Sema &SemaRef,
3406 NestedNameSpecifier *NNS,
3407 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003408 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003409 llvm::SmallVectorImpl<bool> &Used) {
3410 if (!NNS)
3411 return;
3412
Douglas Gregored9c0f92009-10-29 00:04:11 +00003413 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3414 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003415 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003416 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003417}
3418
3419/// \brief Mark the template parameters that are used by the given
3420/// template name.
3421static void
3422MarkUsedTemplateParameters(Sema &SemaRef,
3423 TemplateName Name,
3424 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003425 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003426 llvm::SmallVectorImpl<bool> &Used) {
3427 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3428 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003429 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3430 if (TTP->getDepth() == Depth)
3431 Used[TTP->getIndex()] = true;
3432 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003433 return;
3434 }
3435
Douglas Gregor788cd062009-11-11 01:00:40 +00003436 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3437 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3438 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003439 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003440 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3441 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003442}
3443
3444/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003445/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003446static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003447MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3448 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003449 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003450 llvm::SmallVectorImpl<bool> &Used) {
3451 if (T.isNull())
3452 return;
3453
Douglas Gregor031a5882009-06-13 00:26:55 +00003454 // Non-dependent types have nothing deducible
3455 if (!T->isDependentType())
3456 return;
3457
3458 T = SemaRef.Context.getCanonicalType(T);
3459 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003460 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003461 MarkUsedTemplateParameters(SemaRef,
3462 cast<PointerType>(T)->getPointeeType(),
3463 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003464 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003465 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003466 break;
3467
3468 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003469 MarkUsedTemplateParameters(SemaRef,
3470 cast<BlockPointerType>(T)->getPointeeType(),
3471 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003472 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003473 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003474 break;
3475
3476 case Type::LValueReference:
3477 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003478 MarkUsedTemplateParameters(SemaRef,
3479 cast<ReferenceType>(T)->getPointeeType(),
3480 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003481 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003482 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003483 break;
3484
3485 case Type::MemberPointer: {
3486 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003487 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003488 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003489 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003490 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003491 break;
3492 }
3493
3494 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003495 MarkUsedTemplateParameters(SemaRef,
3496 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003497 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003498 // Fall through to check the element type
3499
3500 case Type::ConstantArray:
3501 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003502 MarkUsedTemplateParameters(SemaRef,
3503 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003504 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003505 break;
3506
3507 case Type::Vector:
3508 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003509 MarkUsedTemplateParameters(SemaRef,
3510 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003511 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003512 break;
3513
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003514 case Type::DependentSizedExtVector: {
3515 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003516 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003517 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003518 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003519 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003520 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003521 break;
3522 }
3523
Douglas Gregor031a5882009-06-13 00:26:55 +00003524 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003525 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003526 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003527 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003528 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003529 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003530 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003531 break;
3532 }
3533
Douglas Gregored9c0f92009-10-29 00:04:11 +00003534 case Type::TemplateTypeParm: {
3535 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3536 if (TTP->getDepth() == Depth)
3537 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003538 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003539 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003540
John McCall31f17ec2010-04-27 00:57:59 +00003541 case Type::InjectedClassName:
3542 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3543 // fall through
3544
Douglas Gregor031a5882009-06-13 00:26:55 +00003545 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003546 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003547 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003548 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003549 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003550
3551 // C++0x [temp.deduct.type]p9:
3552 // If the template argument list of P contains a pack expansion that is not
3553 // the last template argument, the entire template argument list is a
3554 // non-deduced context.
3555 if (OnlyDeduced &&
3556 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3557 break;
3558
Douglas Gregore73bb602009-09-14 21:25:05 +00003559 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003560 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3561 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003562 break;
3563 }
3564
Douglas Gregore73bb602009-09-14 21:25:05 +00003565 case Type::Complex:
3566 if (!OnlyDeduced)
3567 MarkUsedTemplateParameters(SemaRef,
3568 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003569 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003570 break;
3571
Douglas Gregor4714c122010-03-31 17:34:00 +00003572 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003573 if (!OnlyDeduced)
3574 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003575 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003576 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003577 break;
3578
John McCall33500952010-06-11 00:33:02 +00003579 case Type::DependentTemplateSpecialization: {
3580 const DependentTemplateSpecializationType *Spec
3581 = cast<DependentTemplateSpecializationType>(T);
3582 if (!OnlyDeduced)
3583 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3584 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003585
3586 // C++0x [temp.deduct.type]p9:
3587 // If the template argument list of P contains a pack expansion that is not
3588 // the last template argument, the entire template argument list is a
3589 // non-deduced context.
3590 if (OnlyDeduced &&
3591 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3592 break;
3593
John McCall33500952010-06-11 00:33:02 +00003594 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3595 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3596 Used);
3597 break;
3598 }
3599
John McCallad5e7382010-03-01 23:49:17 +00003600 case Type::TypeOf:
3601 if (!OnlyDeduced)
3602 MarkUsedTemplateParameters(SemaRef,
3603 cast<TypeOfType>(T)->getUnderlyingType(),
3604 OnlyDeduced, Depth, Used);
3605 break;
3606
3607 case Type::TypeOfExpr:
3608 if (!OnlyDeduced)
3609 MarkUsedTemplateParameters(SemaRef,
3610 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3611 OnlyDeduced, Depth, Used);
3612 break;
3613
3614 case Type::Decltype:
3615 if (!OnlyDeduced)
3616 MarkUsedTemplateParameters(SemaRef,
3617 cast<DecltypeType>(T)->getUnderlyingExpr(),
3618 OnlyDeduced, Depth, Used);
3619 break;
3620
Douglas Gregor7536dd52010-12-20 02:24:11 +00003621 case Type::PackExpansion:
3622 MarkUsedTemplateParameters(SemaRef,
3623 cast<PackExpansionType>(T)->getPattern(),
3624 OnlyDeduced, Depth, Used);
3625 break;
3626
Douglas Gregore73bb602009-09-14 21:25:05 +00003627 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003628 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003629 case Type::VariableArray:
3630 case Type::FunctionNoProto:
3631 case Type::Record:
3632 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003633 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003634 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003635 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003636 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003637#define TYPE(Class, Base)
3638#define ABSTRACT_TYPE(Class, Base)
3639#define DEPENDENT_TYPE(Class, Base)
3640#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3641#include "clang/AST/TypeNodes.def"
3642 break;
3643 }
3644}
3645
Douglas Gregore73bb602009-09-14 21:25:05 +00003646/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003647/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003648static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003649MarkUsedTemplateParameters(Sema &SemaRef,
3650 const TemplateArgument &TemplateArg,
3651 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003652 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003653 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003654 switch (TemplateArg.getKind()) {
3655 case TemplateArgument::Null:
3656 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003657 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003658 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Douglas Gregor031a5882009-06-13 00:26:55 +00003660 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003661 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003662 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003663 break;
3664
Douglas Gregor788cd062009-11-11 01:00:40 +00003665 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003666 case TemplateArgument::TemplateExpansion:
3667 MarkUsedTemplateParameters(SemaRef,
3668 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003669 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003670 break;
3671
3672 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003673 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003674 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003675 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003676
Anders Carlssond01b1da2009-06-15 17:04:53 +00003677 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003678 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3679 PEnd = TemplateArg.pack_end();
3680 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003681 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003682 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003683 }
3684}
3685
3686/// \brief Mark the template parameters can be deduced by the given
3687/// template argument list.
3688///
3689/// \param TemplateArgs the template argument list from which template
3690/// parameters will be deduced.
3691///
3692/// \param Deduced a bit vector whose elements will be set to \c true
3693/// to indicate when the corresponding template parameter will be
3694/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003695void
Douglas Gregore73bb602009-09-14 21:25:05 +00003696Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003697 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003698 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003699 // C++0x [temp.deduct.type]p9:
3700 // If the template argument list of P contains a pack expansion that is not
3701 // the last template argument, the entire template argument list is a
3702 // non-deduced context.
3703 if (OnlyDeduced &&
3704 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3705 return;
3706
Douglas Gregor031a5882009-06-13 00:26:55 +00003707 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003708 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3709 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003710}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003711
3712/// \brief Marks all of the template parameters that will be deduced by a
3713/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003714void
3715Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3716 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003717 TemplateParameterList *TemplateParams
3718 = FunctionTemplate->getTemplateParameters();
3719 Deduced.clear();
3720 Deduced.resize(TemplateParams->size());
3721
3722 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3723 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3724 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003725 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003726}