blob: ff084c34c2857f30b95d4972b65652f06ea0fccb [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
515/// \brief Deduce the template arguments by comparing the list of parameter
516/// types to the list of argument types, as in the parameter-type-lists of
517/// function types (C++ [temp.deduct.type]p10).
518///
519/// \param S The semantic analysis object within which we are deducing
520///
521/// \param TemplateParams The template parameters that we are deducing
522///
523/// \param Params The list of parameter types
524///
525/// \param NumParams The number of types in \c Params
526///
527/// \param Args The list of argument types
528///
529/// \param NumArgs The number of types in \c Args
530///
531/// \param Info information about the template argument deduction itself
532///
533/// \param Deduced the deduced template arguments
534///
535/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
536/// how template argument deduction is performed.
537///
538/// \returns the result of template argument deduction so far. Note that a
539/// "success" result means that template argument deduction has not yet failed,
540/// but it may still fail, later, for other reasons.
541static Sema::TemplateDeductionResult
542DeduceTemplateArguments(Sema &S,
543 TemplateParameterList *TemplateParams,
544 const QualType *Params, unsigned NumParams,
545 const QualType *Args, unsigned NumArgs,
546 TemplateDeductionInfo &Info,
547 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
548 unsigned TDF) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000549 // Fast-path check to see if we have too many/too few arguments.
550 if (NumParams != NumArgs &&
551 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
552 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
553 return NumArgs < NumParams ? Sema::TDK_TooFewArguments
554 : Sema::TDK_TooManyArguments;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000555
556 // C++0x [temp.deduct.type]p10:
557 // Similarly, if P has a form that contains (T), then each parameter type
558 // Pi of the respective parameter-type- list of P is compared with the
559 // corresponding parameter type Ai of the corresponding parameter-type-list
560 // of A. [...]
561 unsigned ArgIdx = 0, ParamIdx = 0;
562 for (; ParamIdx != NumParams; ++ParamIdx) {
563 // Check argument types.
564 const PackExpansionType *Expansion
565 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
566 if (!Expansion) {
567 // Simple case: compare the parameter and argument types at this point.
568
569 // Make sure we have an argument.
570 if (ArgIdx >= NumArgs)
571 return Sema::TDK_TooFewArguments;
572
573 if (Sema::TemplateDeductionResult Result
574 = DeduceTemplateArguments(S, TemplateParams,
575 Params[ParamIdx],
576 Args[ArgIdx],
577 Info, Deduced, TDF))
578 return Result;
579
580 ++ArgIdx;
581 continue;
582 }
583
584 // C++0x [temp.deduct.type]p10:
585 // If the parameter-declaration corresponding to Pi is a function
586 // parameter pack, then the type of its declarator- id is compared with
587 // each remaining parameter type in the parameter-type-list of A. Each
588 // comparison deduces template arguments for subsequent positions in the
589 // template parameter packs expanded by the function parameter pack.
590
591 // Compute the set of template parameter indices that correspond to
592 // parameter packs expanded by the pack expansion.
593 llvm::SmallVector<unsigned, 2> PackIndices;
594 QualType Pattern = Expansion->getPattern();
595 {
596 llvm::BitVector SawIndices(TemplateParams->size());
597 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
598 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
599 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
600 unsigned Depth, Index;
601 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
602 if (Depth == 0 && !SawIndices[Index]) {
603 SawIndices[Index] = true;
604 PackIndices.push_back(Index);
605 }
606 }
607 }
608 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
609
Douglas Gregord3731192011-01-10 07:32:04 +0000610 // Keep track of the deduced template arguments for each parameter pack
611 // expanded by this pack expansion (the outer index) and for each
612 // template argument (the inner SmallVectors).
613 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
614 NewlyDeducedPacks(PackIndices.size());
615
Douglas Gregor603cfb42011-01-05 23:12:31 +0000616 // Save the deduced template arguments for each parameter pack expanded
617 // by this pack expansion, then clear out the deduction.
618 llvm::SmallVector<DeducedTemplateArgument, 2>
619 SavedPacks(PackIndices.size());
620 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
621 SavedPacks[I] = Deduced[PackIndices[I]];
622 Deduced[PackIndices[I]] = DeducedTemplateArgument();
Douglas Gregord3731192011-01-10 07:32:04 +0000623
624 // If the template arugment pack was explicitly specified, add that to
625 // the set of deduced arguments.
626 const TemplateArgument *ExplicitArgs;
627 unsigned NumExplicitArgs;
628 if (NamedDecl *PartiallySubstitutedPack
629 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
630 &ExplicitArgs,
631 &NumExplicitArgs)) {
632 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
633 NewlyDeducedPacks[I].append(ExplicitArgs,
634 ExplicitArgs + NumExplicitArgs);
635 }
Douglas Gregor603cfb42011-01-05 23:12:31 +0000636 }
637
Douglas Gregor603cfb42011-01-05 23:12:31 +0000638 bool HasAnyArguments = false;
639 for (; ArgIdx < NumArgs; ++ArgIdx) {
640 HasAnyArguments = true;
641
642 // Deduce template arguments from the pattern.
643 if (Sema::TemplateDeductionResult Result
644 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
645 Info, Deduced))
646 return Result;
647
648 // Capture the deduced template arguments for each parameter pack expanded
649 // by this pack expansion, add them to the list of arguments we've deduced
650 // for that pack, then clear out the deduced argument.
651 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
652 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
653 if (!DeducedArg.isNull()) {
654 NewlyDeducedPacks[I].push_back(DeducedArg);
655 DeducedArg = DeducedTemplateArgument();
656 }
657 }
658 }
659
660 // Build argument packs for each of the parameter packs expanded by this
661 // pack expansion.
662 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
663 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
664 // We were not able to deduce anything for this parameter pack,
665 // so just restore the saved argument pack.
666 Deduced[PackIndices[I]] = SavedPacks[I];
667 continue;
668 }
669
670 DeducedTemplateArgument NewPack;
671
672 if (NewlyDeducedPacks[I].empty()) {
673 // If we deduced an empty argument pack, create it now.
674 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
675 } else {
676 TemplateArgument *ArgumentPack
677 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
678 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
679 ArgumentPack);
680 NewPack
681 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
682 NewlyDeducedPacks[I].size()),
683 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
684 }
685
686 DeducedTemplateArgument Result
687 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
688 if (Result.isNull()) {
689 Info.Param
690 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
691 Info.FirstArg = SavedPacks[I];
692 Info.SecondArg = NewPack;
693 return Sema::TDK_Inconsistent;
694 }
695
696 Deduced[PackIndices[I]] = Result;
697 }
698 }
699
700 // Make sure we don't have any extra arguments.
701 if (ArgIdx < NumArgs)
702 return Sema::TDK_TooManyArguments;
703
704 return Sema::TDK_Success;
705}
706
Douglas Gregor500d3312009-06-26 18:27:22 +0000707/// \brief Deduce the template arguments by comparing the parameter type and
708/// the argument type (C++ [temp.deduct.type]).
709///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000710/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000711///
712/// \param TemplateParams the template parameters that we are deducing
713///
714/// \param ParamIn the parameter type
715///
716/// \param ArgIn the argument type
717///
718/// \param Info information about the template argument deduction itself
719///
720/// \param Deduced the deduced template arguments
721///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000722/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000723/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000724///
725/// \returns the result of template argument deduction so far. Note that a
726/// "success" result means that template argument deduction has not yet failed,
727/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000728static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000729DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000730 TemplateParameterList *TemplateParams,
731 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000732 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000733 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000734 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000735 // We only want to look at the canonical types, since typedefs and
736 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000737 QualType Param = S.Context.getCanonicalType(ParamIn);
738 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000739
Douglas Gregor500d3312009-06-26 18:27:22 +0000740 // C++0x [temp.deduct.call]p4 bullet 1:
741 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000742 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000743 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000744 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000745 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000746 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000747 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
748 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000749 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000750 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000752 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000753 if (!Param->isDependentType()) {
754 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
755
756 return Sema::TDK_NonDeducedMismatch;
757 }
758
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000759 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000760 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000761
Douglas Gregor199d9912009-06-05 00:53:49 +0000762 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000763 // A template type argument T, a template template argument TT or a
764 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000765 // the following forms:
766 //
767 // T
768 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000769 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000770 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000771 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000772 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000774 // If the argument type is an array type, move the qualifiers up to the
775 // top level, so they can be matched with the qualifiers on the parameter.
776 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000777 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000778 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000779 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000780 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000781 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000782 RecanonicalizeArg = true;
783 }
784 }
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000786 // The argument type can not be less qualified than the parameter
787 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000788 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000789 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000790 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000791 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000792 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000793 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000794
795 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000796 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000797 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000798
799 // local manipulation is okay because it's canonical
800 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000801 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000802 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000804 DeducedTemplateArgument NewDeduced(DeducedType);
805 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
806 Deduced[Index],
807 NewDeduced);
808 if (Result.isNull()) {
809 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
810 Info.FirstArg = Deduced[Index];
811 Info.SecondArg = NewDeduced;
812 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000813 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000814
815 Deduced[Index] = Result;
816 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000817 }
818
Douglas Gregorf67875d2009-06-12 18:26:56 +0000819 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000820 Info.FirstArg = TemplateArgument(ParamIn);
821 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000822
Douglas Gregor508f1c82009-06-26 23:10:12 +0000823 // Check the cv-qualifiers on the parameter and argument types.
824 if (!(TDF & TDF_IgnoreQualifiers)) {
825 if (TDF & TDF_ParamWithReferenceType) {
826 if (Param.isMoreQualifiedThan(Arg))
827 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000828 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000829 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000830 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000831 }
832 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000833
Douglas Gregord560d502009-06-04 00:21:18 +0000834 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000835 // No deduction possible for these types
836 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000837 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Douglas Gregor199d9912009-06-05 00:53:49 +0000839 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000840 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000841 QualType PointeeType;
842 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
843 PointeeType = PointerArg->getPointeeType();
844 } else if (const ObjCObjectPointerType *PointerArg
845 = Arg->getAs<ObjCObjectPointerType>()) {
846 PointeeType = PointerArg->getPointeeType();
847 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000848 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000849 }
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Douglas Gregor41128772009-06-26 23:27:24 +0000851 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000852 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000853 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000854 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000855 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000856 }
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Douglas Gregor199d9912009-06-05 00:53:49 +0000858 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000859 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000860 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000861 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000862 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000864 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000865 cast<LValueReferenceType>(Param)->getPointeeType(),
866 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000867 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000868 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000869
Douglas Gregor199d9912009-06-05 00:53:49 +0000870 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000871 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000872 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000873 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000874 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000876 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000877 cast<RValueReferenceType>(Param)->getPointeeType(),
878 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000879 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000880 }
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Douglas Gregor199d9912009-06-05 00:53:49 +0000882 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000883 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000884 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000885 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000886 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000887 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
John McCalle4f26e52010-08-19 00:20:19 +0000889 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000890 return DeduceTemplateArguments(S, TemplateParams,
891 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000892 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000893 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000894 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000895
896 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000897 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000898 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000899 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000900 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000901 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000902
903 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000904 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000905 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000906 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000907
John McCalle4f26e52010-08-19 00:20:19 +0000908 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000909 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000910 ConstantArrayParm->getElementType(),
911 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000912 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000913 }
914
Douglas Gregor199d9912009-06-05 00:53:49 +0000915 // type [i]
916 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000917 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000918 if (!ArrayArg)
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;
922
Douglas Gregor199d9912009-06-05 00:53:49 +0000923 // Check the element type of the arrays
924 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000925 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000926 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000927 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000928 DependentArrayParm->getElementType(),
929 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000930 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000931 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000932
Douglas Gregor199d9912009-06-05 00:53:49 +0000933 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000934 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000935 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
936 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000937 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000938
939 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000940 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000941 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000942 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000943 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000944 = dyn_cast<ConstantArrayType>(ArrayArg)) {
945 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000946 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
947 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000948 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000949 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000950 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000951 if (const DependentSizedArrayType *DependentArrayArg
952 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000953 if (DependentArrayArg->getSizeExpr())
954 return DeduceNonTypeTemplateArgument(S, NTTP,
955 DependentArrayArg->getSizeExpr(),
956 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregor199d9912009-06-05 00:53:49 +0000958 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000959 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961
962 // type(*)(T)
963 // T(*)()
964 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000965 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000966 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000967 dyn_cast<FunctionProtoType>(Arg);
968 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000969 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000970
971 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000972 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000973
Mike Stump1eb44332009-09-09 15:08:12 +0000974 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000975 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000976 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000978 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000979 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000980
Anders Carlssona27fad52009-06-08 15:19:08 +0000981 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000982 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000983 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000984 FunctionProtoParam->getResultType(),
985 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000986 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000987 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Douglas Gregor603cfb42011-01-05 23:12:31 +0000989 return DeduceTemplateArguments(S, TemplateParams,
990 FunctionProtoParam->arg_type_begin(),
991 FunctionProtoParam->getNumArgs(),
992 FunctionProtoArg->arg_type_begin(),
993 FunctionProtoArg->getNumArgs(),
994 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +0000995 }
Mike Stump1eb44332009-09-09 15:08:12 +0000996
John McCall3cb0ebd2010-03-10 03:28:59 +0000997 case Type::InjectedClassName: {
998 // Treat a template's injected-class-name as if the template
999 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001000 Param = cast<InjectedClassNameType>(Param)
1001 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001002 assert(isa<TemplateSpecializationType>(Param) &&
1003 "injected class name is not a template specialization type");
1004 // fall through
1005 }
1006
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001007 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001008 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001009 // TT<T>
1010 // TT<i>
1011 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001012 case Type::TemplateSpecialization: {
1013 const TemplateSpecializationType *SpecParam
1014 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001016 // Try to deduce template arguments from the template-id.
1017 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001018 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001019 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001021 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001022 // C++ [temp.deduct.call]p3b3:
1023 // If P is a class, and P has the form template-id, then A can be a
1024 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001025 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001026 // class pointed to by the deduced A.
1027 //
1028 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001029 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001030 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001031 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1032 // We cannot inspect base classes as part of deduction when the type
1033 // is incomplete, so either instantiate any templates necessary to
1034 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001035 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001036 return Result;
1037
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001038 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001039 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001040 // ToVisit is our stack of records that we still need to visit.
1041 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1042 llvm::SmallVector<const RecordType *, 8> ToVisit;
1043 ToVisit.push_back(RecordT);
1044 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001045 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1046 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001047 while (!ToVisit.empty()) {
1048 // Retrieve the next class in the inheritance hierarchy.
1049 const RecordType *NextT = ToVisit.back();
1050 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001052 // If we have already seen this type, skip it.
1053 if (!Visited.insert(NextT))
1054 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001056 // If this is a base class, try to perform template argument
1057 // deduction from it.
1058 if (NextT != RecordT) {
1059 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001060 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001061 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001063 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001064 // note that we had some success. Otherwise, ignore any deductions
1065 // from this base class.
1066 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001067 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001068 DeducedOrig = Deduced;
1069 }
1070 else
1071 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001072 }
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001074 // Visit base classes
1075 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1076 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1077 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001078 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001079 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001080 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001081 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001082 }
1083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001085 if (Successful)
1086 return Sema::TDK_Success;
1087 }
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001089 }
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001091 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001092 }
1093
Douglas Gregor637a4092009-06-10 23:47:09 +00001094 // T type::*
1095 // T T::*
1096 // T (type::*)()
1097 // type (T::*)()
1098 // type (type::*)(T)
1099 // type (T::*)(T)
1100 // T (type::*)(T)
1101 // T (T::*)()
1102 // T (T::*)(T)
1103 case Type::MemberPointer: {
1104 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1105 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1106 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001107 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001108
Douglas Gregorf67875d2009-06-12 18:26:56 +00001109 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001110 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001111 MemPtrParam->getPointeeType(),
1112 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001113 Info, Deduced,
1114 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001115 return Result;
1116
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001117 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001118 QualType(MemPtrParam->getClass(), 0),
1119 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001120 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001121 }
1122
Anders Carlsson9a917e42009-06-12 22:56:54 +00001123 // (clang extension)
1124 //
Mike Stump1eb44332009-09-09 15:08:12 +00001125 // type(^)(T)
1126 // T(^)()
1127 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001128 case Type::BlockPointer: {
1129 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1130 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Anders Carlsson859ba502009-06-12 16:23:10 +00001132 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001133 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001135 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001136 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001137 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001138 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001139 }
1140
Douglas Gregor637a4092009-06-10 23:47:09 +00001141 case Type::TypeOfExpr:
1142 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001143 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001144 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001145 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001146
Douglas Gregord560d502009-06-04 00:21:18 +00001147 default:
1148 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001149 }
1150
1151 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001152 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001153}
1154
Douglas Gregorf67875d2009-06-12 18:26:56 +00001155static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001156DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001157 TemplateParameterList *TemplateParams,
1158 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001159 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001160 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001161 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001162 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001163 case TemplateArgument::Null:
1164 assert(false && "Null template argument in parameter list");
1165 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001166
1167 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001168 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001169 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001170 Arg.getAsType(), Info, Deduced, 0);
1171 Info.FirstArg = Param;
1172 Info.SecondArg = Arg;
1173 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001174
Douglas Gregor788cd062009-11-11 01:00:40 +00001175 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001176 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001177 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001178 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001179 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001180 Info.FirstArg = Param;
1181 Info.SecondArg = Arg;
1182 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001183
1184 case TemplateArgument::TemplateExpansion:
1185 llvm_unreachable("caller should handle pack expansions");
1186 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001187
Douglas Gregor199d9912009-06-05 00:53:49 +00001188 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001189 if (Arg.getKind() == TemplateArgument::Declaration &&
1190 Param.getAsDecl()->getCanonicalDecl() ==
1191 Arg.getAsDecl()->getCanonicalDecl())
1192 return Sema::TDK_Success;
1193
Douglas Gregorf67875d2009-06-12 18:26:56 +00001194 Info.FirstArg = Param;
1195 Info.SecondArg = Arg;
1196 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Douglas Gregor199d9912009-06-05 00:53:49 +00001198 case TemplateArgument::Integral:
1199 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001200 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001201 return Sema::TDK_Success;
1202
1203 Info.FirstArg = Param;
1204 Info.SecondArg = Arg;
1205 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001206 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001207
1208 if (Arg.getKind() == TemplateArgument::Expression) {
1209 Info.FirstArg = Param;
1210 Info.SecondArg = Arg;
1211 return Sema::TDK_NonDeducedMismatch;
1212 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001213
Douglas Gregorf67875d2009-06-12 18:26:56 +00001214 Info.FirstArg = Param;
1215 Info.SecondArg = Arg;
1216 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Douglas Gregor199d9912009-06-05 00:53:49 +00001218 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001219 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001220 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1221 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001222 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001223 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001224 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001225 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001226 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001227 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001228 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001229 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001230 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001231 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001232 Info, Deduced);
1233
Douglas Gregorf67875d2009-06-12 18:26:56 +00001234 Info.FirstArg = Param;
1235 Info.SecondArg = Arg;
1236 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001237 }
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Douglas Gregor199d9912009-06-05 00:53:49 +00001239 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001240 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001241 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001242 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001243 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001244 }
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Douglas Gregorf67875d2009-06-12 18:26:56 +00001246 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001247}
1248
Douglas Gregor20a55e22010-12-22 18:17:10 +00001249/// \brief Determine whether there is a template argument to be used for
1250/// deduction.
1251///
1252/// This routine "expands" argument packs in-place, overriding its input
1253/// parameters so that \c Args[ArgIdx] will be the available template argument.
1254///
1255/// \returns true if there is another template argument (which will be at
1256/// \c Args[ArgIdx]), false otherwise.
1257static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1258 unsigned &ArgIdx,
1259 unsigned &NumArgs) {
1260 if (ArgIdx == NumArgs)
1261 return false;
1262
1263 const TemplateArgument &Arg = Args[ArgIdx];
1264 if (Arg.getKind() != TemplateArgument::Pack)
1265 return true;
1266
1267 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1268 Args = Arg.pack_begin();
1269 NumArgs = Arg.pack_size();
1270 ArgIdx = 0;
1271 return ArgIdx < NumArgs;
1272}
1273
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001274/// \brief Determine whether the given set of template arguments has a pack
1275/// expansion that is not the last template argument.
1276static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1277 unsigned NumArgs) {
1278 unsigned ArgIdx = 0;
1279 while (ArgIdx < NumArgs) {
1280 const TemplateArgument &Arg = Args[ArgIdx];
1281
1282 // Unwrap argument packs.
1283 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1284 Args = Arg.pack_begin();
1285 NumArgs = Arg.pack_size();
1286 ArgIdx = 0;
1287 continue;
1288 }
1289
1290 ++ArgIdx;
1291 if (ArgIdx == NumArgs)
1292 return false;
1293
1294 if (Arg.isPackExpansion())
1295 return true;
1296 }
1297
1298 return false;
1299}
1300
Douglas Gregor20a55e22010-12-22 18:17:10 +00001301static Sema::TemplateDeductionResult
1302DeduceTemplateArguments(Sema &S,
1303 TemplateParameterList *TemplateParams,
1304 const TemplateArgument *Params, unsigned NumParams,
1305 const TemplateArgument *Args, unsigned NumArgs,
1306 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001307 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1308 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001309 // C++0x [temp.deduct.type]p9:
1310 // If the template argument list of P contains a pack expansion that is not
1311 // the last template argument, the entire template argument list is a
1312 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001313 if (hasPackExpansionBeforeEnd(Params, NumParams))
1314 return Sema::TDK_Success;
1315
Douglas Gregore02e2622010-12-22 21:19:48 +00001316 // C++0x [temp.deduct.type]p9:
1317 // If P has a form that contains <T> or <i>, then each argument Pi of the
1318 // respective template argument list P is compared with the corresponding
1319 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001320 unsigned ArgIdx = 0, ParamIdx = 0;
1321 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1322 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001323 // FIXME: Variadic templates.
1324 // What do we do if the argument is a pack expansion?
1325
Douglas Gregor20a55e22010-12-22 18:17:10 +00001326 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001327 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001328
1329 // Check whether we have enough arguments.
1330 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001331 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1332 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001333
Douglas Gregore02e2622010-12-22 21:19:48 +00001334 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001335 if (Sema::TemplateDeductionResult Result
1336 = DeduceTemplateArguments(S, TemplateParams,
1337 Params[ParamIdx], Args[ArgIdx],
1338 Info, Deduced))
1339 return Result;
1340
1341 // Move to the next argument.
1342 ++ArgIdx;
1343 continue;
1344 }
1345
Douglas Gregore02e2622010-12-22 21:19:48 +00001346 // The parameter is a pack expansion.
1347
1348 // C++0x [temp.deduct.type]p9:
1349 // If Pi is a pack expansion, then the pattern of Pi is compared with
1350 // each remaining argument in the template argument list of A. Each
1351 // comparison deduces template arguments for subsequent positions in the
1352 // template parameter packs expanded by Pi.
1353 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1354
1355 // Compute the set of template parameter indices that correspond to
1356 // parameter packs expanded by the pack expansion.
1357 llvm::SmallVector<unsigned, 2> PackIndices;
1358 {
1359 llvm::BitVector SawIndices(TemplateParams->size());
1360 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1361 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1362 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1363 unsigned Depth, Index;
1364 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1365 if (Depth == 0 && !SawIndices[Index]) {
1366 SawIndices[Index] = true;
1367 PackIndices.push_back(Index);
1368 }
1369 }
1370 }
1371 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1372
1373 // FIXME: If there are no remaining arguments, we can bail out early
1374 // and set any deduced parameter packs to an empty argument pack.
1375 // The latter part of this is a (minor) correctness issue.
1376
1377 // Save the deduced template arguments for each parameter pack expanded
1378 // by this pack expansion, then clear out the deduction.
1379 llvm::SmallVector<DeducedTemplateArgument, 2>
1380 SavedPacks(PackIndices.size());
1381 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1382 SavedPacks[I] = Deduced[PackIndices[I]];
1383 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1384 }
1385
1386 // Keep track of the deduced template arguments for each parameter pack
1387 // expanded by this pack expansion (the outer index) and for each
1388 // template argument (the inner SmallVectors).
1389 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1390 NewlyDeducedPacks(PackIndices.size());
1391 bool HasAnyArguments = false;
1392 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1393 HasAnyArguments = true;
1394
1395 // Deduce template arguments from the pattern.
1396 if (Sema::TemplateDeductionResult Result
1397 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1398 Info, Deduced))
1399 return Result;
1400
1401 // Capture the deduced template arguments for each parameter pack expanded
1402 // by this pack expansion, add them to the list of arguments we've deduced
1403 // for that pack, then clear out the deduced argument.
1404 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1405 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1406 if (!DeducedArg.isNull()) {
1407 NewlyDeducedPacks[I].push_back(DeducedArg);
1408 DeducedArg = DeducedTemplateArgument();
1409 }
1410 }
1411
1412 ++ArgIdx;
1413 }
1414
1415 // Build argument packs for each of the parameter packs expanded by this
1416 // pack expansion.
1417 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1418 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1419 // We were not able to deduce anything for this parameter pack,
1420 // so just restore the saved argument pack.
1421 Deduced[PackIndices[I]] = SavedPacks[I];
1422 continue;
1423 }
1424
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001425 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001426
1427 if (NewlyDeducedPacks[I].empty()) {
1428 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001429 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1430 } else {
1431 TemplateArgument *ArgumentPack
1432 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1433 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1434 ArgumentPack);
1435 NewPack
1436 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001437 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001438 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1439 }
1440
1441 DeducedTemplateArgument Result
1442 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1443 if (Result.isNull()) {
1444 Info.Param
1445 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1446 Info.FirstArg = SavedPacks[I];
1447 Info.SecondArg = NewPack;
1448 return Sema::TDK_Inconsistent;
1449 }
1450
1451 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001452 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001453 }
1454
1455 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001456 if (NumberOfArgumentsMustMatch &&
1457 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001458 return Sema::TDK_TooManyArguments;
1459
1460 return Sema::TDK_Success;
1461}
1462
Mike Stump1eb44332009-09-09 15:08:12 +00001463static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001464DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001465 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001466 const TemplateArgumentList &ParamList,
1467 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001468 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001469 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001470 return DeduceTemplateArguments(S, TemplateParams,
1471 ParamList.data(), ParamList.size(),
1472 ArgList.data(), ArgList.size(),
1473 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001474}
1475
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001476/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001477static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001478 const TemplateArgument &X,
1479 const TemplateArgument &Y) {
1480 if (X.getKind() != Y.getKind())
1481 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001483 switch (X.getKind()) {
1484 case TemplateArgument::Null:
1485 assert(false && "Comparing NULL template argument");
1486 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001488 case TemplateArgument::Type:
1489 return Context.getCanonicalType(X.getAsType()) ==
1490 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001492 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001493 return X.getAsDecl()->getCanonicalDecl() ==
1494 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Douglas Gregor788cd062009-11-11 01:00:40 +00001496 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001497 case TemplateArgument::TemplateExpansion:
1498 return Context.getCanonicalTemplateName(
1499 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1500 Context.getCanonicalTemplateName(
1501 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001502
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001503 case TemplateArgument::Integral:
1504 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Douglas Gregor788cd062009-11-11 01:00:40 +00001506 case TemplateArgument::Expression: {
1507 llvm::FoldingSetNodeID XID, YID;
1508 X.getAsExpr()->Profile(XID, Context, true);
1509 Y.getAsExpr()->Profile(YID, Context, true);
1510 return XID == YID;
1511 }
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001513 case TemplateArgument::Pack:
1514 if (X.pack_size() != Y.pack_size())
1515 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001516
1517 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1518 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001519 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001520 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001521 if (!isSameTemplateArg(Context, *XP, *YP))
1522 return false;
1523
1524 return true;
1525 }
1526
1527 return false;
1528}
1529
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001530/// \brief Allocate a TemplateArgumentLoc where all locations have
1531/// been initialized to the given location.
1532///
1533/// \param S The semantic analysis object.
1534///
1535/// \param The template argument we are producing template argument
1536/// location information for.
1537///
1538/// \param NTTPType For a declaration template argument, the type of
1539/// the non-type template parameter that corresponds to this template
1540/// argument.
1541///
1542/// \param Loc The source location to use for the resulting template
1543/// argument.
1544static TemplateArgumentLoc
1545getTrivialTemplateArgumentLoc(Sema &S,
1546 const TemplateArgument &Arg,
1547 QualType NTTPType,
1548 SourceLocation Loc) {
1549 switch (Arg.getKind()) {
1550 case TemplateArgument::Null:
1551 llvm_unreachable("Can't get a NULL template argument here");
1552 break;
1553
1554 case TemplateArgument::Type:
1555 return TemplateArgumentLoc(Arg,
1556 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1557
1558 case TemplateArgument::Declaration: {
1559 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001560 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001561 .takeAs<Expr>();
1562 return TemplateArgumentLoc(TemplateArgument(E), E);
1563 }
1564
1565 case TemplateArgument::Integral: {
1566 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001567 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001568 return TemplateArgumentLoc(TemplateArgument(E), E);
1569 }
1570
1571 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001572 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1573
1574 case TemplateArgument::TemplateExpansion:
1575 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1576
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001577 case TemplateArgument::Expression:
1578 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1579
1580 case TemplateArgument::Pack:
1581 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1582 }
1583
1584 return TemplateArgumentLoc();
1585}
1586
1587
1588/// \brief Convert the given deduced template argument and add it to the set of
1589/// fully-converted template arguments.
1590static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1591 DeducedTemplateArgument Arg,
1592 NamedDecl *Template,
1593 QualType NTTPType,
1594 TemplateDeductionInfo &Info,
1595 bool InFunctionTemplate,
1596 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1597 if (Arg.getKind() == TemplateArgument::Pack) {
1598 // This is a template argument pack, so check each of its arguments against
1599 // the template parameter.
1600 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1601 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001602 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001603 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001604 // When converting the deduced template argument, append it to the
1605 // general output list. We need to do this so that the template argument
1606 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001607 DeducedTemplateArgument InnerArg(*PA);
1608 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1609 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1610 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001611 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001612 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001613
1614 // Move the converted template argument into our argument pack.
1615 PackedArgsBuilder.push_back(Output.back());
1616 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001617 }
1618
1619 // Create the resulting argument pack.
1620 TemplateArgument *PackedArgs = 0;
1621 if (!PackedArgsBuilder.empty()) {
1622 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1623 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1624 }
1625 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1626 return false;
1627 }
1628
1629 // Convert the deduced template argument into a template
1630 // argument that we can check, almost as if the user had written
1631 // the template argument explicitly.
1632 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1633 Info.getLocation());
1634
1635 // Check the template argument, converting it as necessary.
1636 return S.CheckTemplateArgument(Param, ArgLoc,
1637 Template,
1638 Template->getLocation(),
1639 Template->getSourceRange().getEnd(),
1640 Output,
1641 InFunctionTemplate
1642 ? (Arg.wasDeducedFromArrayBound()
1643 ? Sema::CTAK_DeducedFromArrayBound
1644 : Sema::CTAK_Deduced)
1645 : Sema::CTAK_Specified);
1646}
1647
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001648/// Complete template argument deduction for a class template partial
1649/// specialization.
1650static Sema::TemplateDeductionResult
1651FinishTemplateArgumentDeduction(Sema &S,
1652 ClassTemplatePartialSpecializationDecl *Partial,
1653 const TemplateArgumentList &TemplateArgs,
1654 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001655 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001656 // Trap errors.
1657 Sema::SFINAETrap Trap(S);
1658
1659 Sema::ContextRAII SavedContext(S, Partial);
1660
1661 // C++ [temp.deduct.type]p2:
1662 // [...] or if any template argument remains neither deduced nor
1663 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001664 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001665 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1666 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001667 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001668 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001669 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001670 return Sema::TDK_Incomplete;
1671 }
1672
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001673 // We have deduced this argument, so it still needs to be
1674 // checked and converted.
1675
1676 // First, for a non-type template parameter type that is
1677 // initialized by a declaration, we need the type of the
1678 // corresponding non-type template parameter.
1679 QualType NTTPType;
1680 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001681 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001682 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001683 if (NTTPType->isDependentType()) {
1684 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1685 Builder.data(), Builder.size());
1686 NTTPType = S.SubstType(NTTPType,
1687 MultiLevelTemplateArgumentList(TemplateArgs),
1688 NTTP->getLocation(),
1689 NTTP->getDeclName());
1690 if (NTTPType.isNull()) {
1691 Info.Param = makeTemplateParameter(Param);
1692 // FIXME: These template arguments are temporary. Free them!
1693 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1694 Builder.data(),
1695 Builder.size()));
1696 return Sema::TDK_SubstitutionFailure;
1697 }
1698 }
1699 }
1700
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001701 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1702 Partial, NTTPType, Info, false,
1703 Builder)) {
1704 Info.Param = makeTemplateParameter(Param);
1705 // FIXME: These template arguments are temporary. Free them!
1706 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1707 Builder.size()));
1708 return Sema::TDK_SubstitutionFailure;
1709 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001710 }
1711
1712 // Form the template argument list from the deduced template arguments.
1713 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001714 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1715 Builder.size());
1716
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001717 Info.reset(DeducedArgumentList);
1718
1719 // Substitute the deduced template arguments into the template
1720 // arguments of the class template partial specialization, and
1721 // verify that the instantiated template arguments are both valid
1722 // and are equivalent to the template arguments originally provided
1723 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001724 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001725 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1726 const TemplateArgumentLoc *PartialTemplateArgs
1727 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001728
1729 // Note that we don't provide the langle and rangle locations.
1730 TemplateArgumentListInfo InstArgs;
1731
Douglas Gregore02e2622010-12-22 21:19:48 +00001732 if (S.Subst(PartialTemplateArgs,
1733 Partial->getNumTemplateArgsAsWritten(),
1734 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1735 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1736 if (ParamIdx >= Partial->getTemplateParameters()->size())
1737 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1738
1739 Decl *Param
1740 = const_cast<NamedDecl *>(
1741 Partial->getTemplateParameters()->getParam(ParamIdx));
1742 Info.Param = makeTemplateParameter(Param);
1743 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1744 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001745 }
1746
Douglas Gregor910f8002010-11-07 23:05:16 +00001747 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001748 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001749 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001750 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001751
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001752 TemplateParameterList *TemplateParams
1753 = ClassTemplate->getTemplateParameters();
1754 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001755 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001756 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001757 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001758 Info.FirstArg = TemplateArgs[I];
1759 Info.SecondArg = InstArg;
1760 return Sema::TDK_NonDeducedMismatch;
1761 }
1762 }
1763
1764 if (Trap.hasErrorOccurred())
1765 return Sema::TDK_SubstitutionFailure;
1766
1767 return Sema::TDK_Success;
1768}
1769
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001770/// \brief Perform template argument deduction to determine whether
1771/// the given template arguments match the given class template
1772/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001773Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001774Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001775 const TemplateArgumentList &TemplateArgs,
1776 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001777 // C++ [temp.class.spec.match]p2:
1778 // A partial specialization matches a given actual template
1779 // argument list if the template arguments of the partial
1780 // specialization can be deduced from the actual template argument
1781 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001782 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001783 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001784 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001785 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001786 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001787 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001788 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001789 TemplateArgs, Info, Deduced))
1790 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001791
Douglas Gregor637a4092009-06-10 23:47:09 +00001792 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001793 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001794 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001795 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001796
Douglas Gregorbb260412009-06-14 08:02:22 +00001797 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001798 return Sema::TDK_SubstitutionFailure;
1799
1800 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1801 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001802}
Douglas Gregor031a5882009-06-13 00:26:55 +00001803
Douglas Gregor41128772009-06-26 23:27:24 +00001804/// \brief Determine whether the given type T is a simple-template-id type.
1805static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001806 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001807 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001808 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Douglas Gregor41128772009-06-26 23:27:24 +00001810 return false;
1811}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001812
1813/// \brief Substitute the explicitly-provided template arguments into the
1814/// given function template according to C++ [temp.arg.explicit].
1815///
1816/// \param FunctionTemplate the function template into which the explicit
1817/// template arguments will be substituted.
1818///
Mike Stump1eb44332009-09-09 15:08:12 +00001819/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001820/// arguments.
1821///
Mike Stump1eb44332009-09-09 15:08:12 +00001822/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001823/// with the converted and checked explicit template arguments.
1824///
Mike Stump1eb44332009-09-09 15:08:12 +00001825/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001826/// parameters.
1827///
1828/// \param FunctionType if non-NULL, the result type of the function template
1829/// will also be instantiated and the pointed-to value will be updated with
1830/// the instantiated function type.
1831///
1832/// \param Info if substitution fails for any reason, this object will be
1833/// populated with more information about the failure.
1834///
1835/// \returns TDK_Success if substitution was successful, or some failure
1836/// condition.
1837Sema::TemplateDeductionResult
1838Sema::SubstituteExplicitTemplateArguments(
1839 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001840 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001841 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001842 llvm::SmallVectorImpl<QualType> &ParamTypes,
1843 QualType *FunctionType,
1844 TemplateDeductionInfo &Info) {
1845 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1846 TemplateParameterList *TemplateParams
1847 = FunctionTemplate->getTemplateParameters();
1848
John McCalld5532b62009-11-23 01:53:49 +00001849 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001850 // No arguments to substitute; just copy over the parameter types and
1851 // fill in the function type.
1852 for (FunctionDecl::param_iterator P = Function->param_begin(),
1853 PEnd = Function->param_end();
1854 P != PEnd;
1855 ++P)
1856 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Douglas Gregor83314aa2009-07-08 20:55:45 +00001858 if (FunctionType)
1859 *FunctionType = Function->getType();
1860 return TDK_Success;
1861 }
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor83314aa2009-07-08 20:55:45 +00001863 // Substitution of the explicit template arguments into a function template
1864 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001865 SFINAETrap Trap(*this);
1866
Douglas Gregor83314aa2009-07-08 20:55:45 +00001867 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001868 // Template arguments that are present shall be specified in the
1869 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001870 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001871 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001872 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001873
1874 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001875 // explicitly-specified template arguments against this function template,
1876 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001877 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001878 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001879 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1880 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001881 if (Inst)
1882 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001883
Douglas Gregor83314aa2009-07-08 20:55:45 +00001884 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001885 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001886 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001887 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001888 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001889 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001890 if (Index >= TemplateParams->size())
1891 Index = TemplateParams->size() - 1;
1892 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001893 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001894 }
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Douglas Gregor83314aa2009-07-08 20:55:45 +00001896 // Form the template argument list from the explicitly-specified
1897 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001898 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001899 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001900 Info.reset(ExplicitArgumentList);
Douglas Gregord3731192011-01-10 07:32:04 +00001901
John McCalldf41f182010-10-12 19:40:14 +00001902 // Template argument deduction and the final substitution should be
1903 // done in the context of the templated declaration. Explicit
1904 // argument substitution, on the other hand, needs to happen in the
1905 // calling context.
1906 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1907
Douglas Gregord3731192011-01-10 07:32:04 +00001908 // If we deduced template arguments for a template parameter pack,
1909 // note that the template argument pack is partially substituted and record
1910 // the explicit template arguments. They'll be used as part of deduction
1911 // for this template parameter pack.
1912 bool HasPartiallySubstitutedPack = false;
1913 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
1914 const TemplateArgument &Arg = Builder[I];
1915 if (Arg.getKind() == TemplateArgument::Pack) {
1916 HasPartiallySubstitutedPack = true;
1917 CurrentInstantiationScope->SetPartiallySubstitutedPack(
1918 TemplateParams->getParam(I),
1919 Arg.pack_begin(),
1920 Arg.pack_size());
1921 break;
1922 }
1923 }
1924
Douglas Gregor83314aa2009-07-08 20:55:45 +00001925 // Instantiate the types of each of the function parameters given the
1926 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00001927 if (SubstParmTypes(Function->getLocation(),
1928 Function->param_begin(), Function->getNumParams(),
1929 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1930 ParamTypes))
1931 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001932
1933 // If the caller wants a full function type back, instantiate the return
1934 // type and form that function type.
1935 if (FunctionType) {
1936 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001937 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001938 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001939 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001940
1941 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001942 = SubstType(Proto->getResultType(),
1943 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1944 Function->getTypeSpecStartLoc(),
1945 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001946 if (ResultType.isNull() || Trap.hasErrorOccurred())
1947 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001948
1949 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001950 ParamTypes.data(), ParamTypes.size(),
1951 Proto->isVariadic(),
1952 Proto->getTypeQuals(),
1953 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001954 Function->getDeclName(),
1955 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001956 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1957 return TDK_SubstitutionFailure;
1958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Douglas Gregor83314aa2009-07-08 20:55:45 +00001960 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001961 // Trailing template arguments that can be deduced (14.8.2) may be
1962 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001963 // template arguments can be deduced, they may all be omitted; in this
1964 // case, the empty template argument list <> itself may also be omitted.
1965 //
Douglas Gregord3731192011-01-10 07:32:04 +00001966 // Take all of the explicitly-specified arguments and put them into
1967 // the set of deduced template arguments. Explicitly-specified
1968 // parameter packs, however, will be set to NULL since the deduction
1969 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001970 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00001971 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
1972 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
1973 if (Arg.getKind() == TemplateArgument::Pack)
1974 Deduced.push_back(DeducedTemplateArgument());
1975 else
1976 Deduced.push_back(Arg);
1977 }
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Douglas Gregor83314aa2009-07-08 20:55:45 +00001979 return TDK_Success;
1980}
1981
Mike Stump1eb44332009-09-09 15:08:12 +00001982/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001983/// checking the deduced template arguments for completeness and forming
1984/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001985Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001986Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001987 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1988 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001989 FunctionDecl *&Specialization,
1990 TemplateDeductionInfo &Info) {
1991 TemplateParameterList *TemplateParams
1992 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregor83314aa2009-07-08 20:55:45 +00001994 // Template argument deduction for function templates in a SFINAE context.
1995 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001996 SFINAETrap Trap(*this);
1997
Douglas Gregor83314aa2009-07-08 20:55:45 +00001998 // Enter a new template instantiation context while we instantiate the
1999 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002000 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002001 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002002 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2003 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002004 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002005 return TDK_InstantiationDepth;
2006
John McCall96db3102010-04-29 01:18:58 +00002007 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002008
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002009 // C++ [temp.deduct.type]p2:
2010 // [...] or if any template argument remains neither deduced nor
2011 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00002012 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002013 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2014 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002015
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002016 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002017 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002018 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002019 // argument, because it was explicitly-specified. Just record the
2020 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002021 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002022 continue;
2023 }
2024
2025 // We have deduced this argument, so it still needs to be
2026 // checked and converted.
2027
2028 // First, for a non-type template parameter type that is
2029 // initialized by a declaration, we need the type of the
2030 // corresponding non-type template parameter.
2031 QualType NTTPType;
2032 if (NonTypeTemplateParmDecl *NTTP
2033 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002034 NTTPType = NTTP->getType();
2035 if (NTTPType->isDependentType()) {
2036 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2037 Builder.data(), Builder.size());
2038 NTTPType = SubstType(NTTPType,
2039 MultiLevelTemplateArgumentList(TemplateArgs),
2040 NTTP->getLocation(),
2041 NTTP->getDeclName());
2042 if (NTTPType.isNull()) {
2043 Info.Param = makeTemplateParameter(Param);
2044 // FIXME: These template arguments are temporary. Free them!
2045 Info.reset(TemplateArgumentList::CreateCopy(Context,
2046 Builder.data(),
2047 Builder.size()));
2048 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002049 }
2050 }
2051 }
2052
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002053 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2054 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002055 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002056 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002057 // FIXME: These template arguments are temporary. Free them!
2058 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002059 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002060 return TDK_SubstitutionFailure;
2061 }
2062
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002063 continue;
2064 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002065
2066 // C++0x [temp.arg.explicit]p3:
2067 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2068 // be deduced to an empty sequence of template arguments.
2069 // FIXME: Where did the word "trailing" come from?
2070 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002071 // We may have had explicitly-specified template arguments for this
2072 // template parameter pack. If so, our empty deduction extends the
2073 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2074 const TemplateArgument *ExplicitArgs;
2075 unsigned NumExplicitArgs;
2076 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2077 &NumExplicitArgs)
2078 == Param)
2079 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2080 else
2081 Builder.push_back(TemplateArgument(0, 0));
2082
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002083 continue;
2084 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002085
2086 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002087 TemplateArgumentLoc DefArg
2088 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2089 FunctionTemplate->getLocation(),
2090 FunctionTemplate->getSourceRange().getEnd(),
2091 Param,
2092 Builder);
2093
2094 // If there was no default argument, deduction is incomplete.
2095 if (DefArg.getArgument().isNull()) {
2096 Info.Param = makeTemplateParameter(
2097 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2098 return TDK_Incomplete;
2099 }
2100
2101 // Check whether we can actually use the default argument.
2102 if (CheckTemplateArgument(Param, DefArg,
2103 FunctionTemplate,
2104 FunctionTemplate->getLocation(),
2105 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002106 Builder,
2107 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002108 Info.Param = makeTemplateParameter(
2109 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002110 // FIXME: These template arguments are temporary. Free them!
2111 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2112 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002113 return TDK_SubstitutionFailure;
2114 }
2115
2116 // If we get here, we successfully used the default template argument.
2117 }
2118
2119 // Form the template argument list from the deduced template arguments.
2120 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002121 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002122 Info.reset(DeducedArgumentList);
2123
Mike Stump1eb44332009-09-09 15:08:12 +00002124 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002125 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002126 DeclContext *Owner = FunctionTemplate->getDeclContext();
2127 if (FunctionTemplate->getFriendObjectKind())
2128 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002129 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002130 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002131 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002132 if (!Specialization)
2133 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Douglas Gregorf8825742009-09-15 18:26:13 +00002135 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2136 FunctionTemplate->getCanonicalDecl());
2137
Mike Stump1eb44332009-09-09 15:08:12 +00002138 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002139 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002140 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2141 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002142 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Douglas Gregor83314aa2009-07-08 20:55:45 +00002144 // There may have been an error that did not prevent us from constructing a
2145 // declaration. Mark the declaration invalid and return with a substitution
2146 // failure.
2147 if (Trap.hasErrorOccurred()) {
2148 Specialization->setInvalidDecl(true);
2149 return TDK_SubstitutionFailure;
2150 }
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Douglas Gregor9b623632010-10-12 23:32:35 +00002152 // If we suppressed any diagnostics while performing template argument
2153 // deduction, and if we haven't already instantiated this declaration,
2154 // keep track of these diagnostics. They'll be emitted if this specialization
2155 // is actually used.
2156 if (Info.diag_begin() != Info.diag_end()) {
2157 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2158 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2159 if (Pos == SuppressedDiagnostics.end())
2160 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2161 .append(Info.diag_begin(), Info.diag_end());
2162 }
2163
Mike Stump1eb44332009-09-09 15:08:12 +00002164 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002165}
2166
John McCall9c72c602010-08-27 09:08:28 +00002167/// Gets the type of a function for template-argument-deducton
2168/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002169static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002170 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002171 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002172 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002173 if (Method->isInstance()) {
2174 // An instance method that's referenced in a form that doesn't
2175 // look like a member pointer is just invalid.
2176 if (!R.HasFormOfMemberPointer) return QualType();
2177
John McCalleff92132010-02-02 02:21:27 +00002178 return Context.getMemberPointerType(Fn->getType(),
2179 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002180 }
2181
2182 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002183 return Context.getPointerType(Fn->getType());
2184}
2185
2186/// Apply the deduction rules for overload sets.
2187///
2188/// \return the null type if this argument should be treated as an
2189/// undeduced context
2190static QualType
2191ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002192 Expr *Arg, QualType ParamType,
2193 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002194
2195 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002196
John McCall9c72c602010-08-27 09:08:28 +00002197 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002198
Douglas Gregor75f21af2010-08-30 21:04:23 +00002199 // C++0x [temp.deduct.call]p4
2200 unsigned TDF = 0;
2201 if (ParamWasReference)
2202 TDF |= TDF_ParamWithReferenceType;
2203 if (R.IsAddressOfOperand)
2204 TDF |= TDF_IgnoreQualifiers;
2205
John McCalleff92132010-02-02 02:21:27 +00002206 // If there were explicit template arguments, we can only find
2207 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2208 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002209 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002210 // But we can still look for an explicit specialization.
2211 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002212 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002213 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002214 return QualType();
2215 }
2216
2217 // C++0x [temp.deduct.call]p6:
2218 // When P is a function type, pointer to function type, or pointer
2219 // to member function type:
2220
2221 if (!ParamType->isFunctionType() &&
2222 !ParamType->isFunctionPointerType() &&
2223 !ParamType->isMemberFunctionPointerType())
2224 return QualType();
2225
2226 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002227 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2228 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002229 NamedDecl *D = (*I)->getUnderlyingDecl();
2230
2231 // - If the argument is an overload set containing one or more
2232 // function templates, the parameter is treated as a
2233 // non-deduced context.
2234 if (isa<FunctionTemplateDecl>(D))
2235 return QualType();
2236
2237 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002238 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2239 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002240
Douglas Gregor75f21af2010-08-30 21:04:23 +00002241 // Function-to-pointer conversion.
2242 if (!ParamWasReference && ParamType->isPointerType() &&
2243 ArgType->isFunctionType())
2244 ArgType = S.Context.getPointerType(ArgType);
2245
John McCalleff92132010-02-02 02:21:27 +00002246 // - If the argument is an overload set (not containing function
2247 // templates), trial argument deduction is attempted using each
2248 // of the members of the set. If deduction succeeds for only one
2249 // of the overload set members, that member is used as the
2250 // argument value for the deduction. If deduction succeeds for
2251 // more than one member of the overload set the parameter is
2252 // treated as a non-deduced context.
2253
2254 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2255 // Type deduction is done independently for each P/A pair, and
2256 // the deduced template argument values are then combined.
2257 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002258 llvm::SmallVector<DeducedTemplateArgument, 8>
2259 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002260 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002261 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002262 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002263 ParamType, ArgType,
2264 Info, Deduced, TDF);
2265 if (Result) continue;
2266 if (!Match.isNull()) return QualType();
2267 Match = ArgType;
2268 }
2269
2270 return Match;
2271}
2272
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002273/// \brief Perform the adjustments to the parameter and argument types
2274/// described in C++ [temp.deduct.call].
2275///
2276/// \returns true if the caller should not attempt to perform any template
2277/// argument deduction based on this P/A pair.
2278static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2279 TemplateParameterList *TemplateParams,
2280 QualType &ParamType,
2281 QualType &ArgType,
2282 Expr *Arg,
2283 unsigned &TDF) {
2284 // C++0x [temp.deduct.call]p3:
2285 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2286 // are ignored for type deduction.
2287 if (ParamType.getCVRQualifiers())
2288 ParamType = ParamType.getLocalUnqualifiedType();
2289 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2290 if (ParamRefType) {
2291 // [...] If P is a reference type, the type referred to by P is used
2292 // for type deduction.
2293 ParamType = ParamRefType->getPointeeType();
2294 }
2295
2296 // Overload sets usually make this parameter an undeduced
2297 // context, but there are sometimes special circumstances.
2298 if (ArgType == S.Context.OverloadTy) {
2299 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2300 Arg, ParamType,
2301 ParamRefType != 0);
2302 if (ArgType.isNull())
2303 return true;
2304 }
2305
2306 if (ParamRefType) {
2307 // C++0x [temp.deduct.call]p3:
2308 // [...] If P is of the form T&&, where T is a template parameter, and
2309 // the argument is an lvalue, the type A& is used in place of A for
2310 // type deduction.
2311 if (ParamRefType->isRValueReferenceType() &&
2312 ParamRefType->getAs<TemplateTypeParmType>() &&
2313 Arg->isLValue())
2314 ArgType = S.Context.getLValueReferenceType(ArgType);
2315 } else {
2316 // C++ [temp.deduct.call]p2:
2317 // If P is not a reference type:
2318 // - If A is an array type, the pointer type produced by the
2319 // array-to-pointer standard conversion (4.2) is used in place of
2320 // A for type deduction; otherwise,
2321 if (ArgType->isArrayType())
2322 ArgType = S.Context.getArrayDecayedType(ArgType);
2323 // - If A is a function type, the pointer type produced by the
2324 // function-to-pointer standard conversion (4.3) is used in place
2325 // of A for type deduction; otherwise,
2326 else if (ArgType->isFunctionType())
2327 ArgType = S.Context.getPointerType(ArgType);
2328 else {
2329 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2330 // type are ignored for type deduction.
2331 QualType CanonArgType = S.Context.getCanonicalType(ArgType);
2332 if (ArgType.getCVRQualifiers())
2333 ArgType = ArgType.getUnqualifiedType();
2334 }
2335 }
2336
2337 // C++0x [temp.deduct.call]p4:
2338 // In general, the deduction process attempts to find template argument
2339 // values that will make the deduced A identical to A (after the type A
2340 // is transformed as described above). [...]
2341 TDF = TDF_SkipNonDependent;
2342
2343 // - If the original P is a reference type, the deduced A (i.e., the
2344 // type referred to by the reference) can be more cv-qualified than
2345 // the transformed A.
2346 if (ParamRefType)
2347 TDF |= TDF_ParamWithReferenceType;
2348 // - The transformed A can be another pointer or pointer to member
2349 // type that can be converted to the deduced A via a qualification
2350 // conversion (4.4).
2351 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2352 ArgType->isObjCObjectPointerType())
2353 TDF |= TDF_IgnoreQualifiers;
2354 // - If P is a class and P has the form simple-template-id, then the
2355 // transformed A can be a derived class of the deduced A. Likewise,
2356 // if P is a pointer to a class of the form simple-template-id, the
2357 // transformed A can be a pointer to a derived class pointed to by
2358 // the deduced A.
2359 if (isSimpleTemplateIdType(ParamType) ||
2360 (isa<PointerType>(ParamType) &&
2361 isSimpleTemplateIdType(
2362 ParamType->getAs<PointerType>()->getPointeeType())))
2363 TDF |= TDF_DerivedClass;
2364
2365 return false;
2366}
2367
Douglas Gregore53060f2009-06-25 22:08:12 +00002368/// \brief Perform template argument deduction from a function call
2369/// (C++ [temp.deduct.call]).
2370///
2371/// \param FunctionTemplate the function template for which we are performing
2372/// template argument deduction.
2373///
Douglas Gregor48026d22010-01-11 18:40:55 +00002374/// \param ExplicitTemplateArguments the explicit template arguments provided
2375/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002376///
Douglas Gregore53060f2009-06-25 22:08:12 +00002377/// \param Args the function call arguments
2378///
2379/// \param NumArgs the number of arguments in Args
2380///
Douglas Gregor48026d22010-01-11 18:40:55 +00002381/// \param Name the name of the function being called. This is only significant
2382/// when the function template is a conversion function template, in which
2383/// case this routine will also perform template argument deduction based on
2384/// the function to which
2385///
Douglas Gregore53060f2009-06-25 22:08:12 +00002386/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002387/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002388/// template argument deduction.
2389///
2390/// \param Info the argument will be updated to provide additional information
2391/// about template argument deduction.
2392///
2393/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002394Sema::TemplateDeductionResult
2395Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002396 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002397 Expr **Args, unsigned NumArgs,
2398 FunctionDecl *&Specialization,
2399 TemplateDeductionInfo &Info) {
2400 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002401
Douglas Gregore53060f2009-06-25 22:08:12 +00002402 // C++ [temp.deduct.call]p1:
2403 // Template argument deduction is done by comparing each function template
2404 // parameter type (call it P) with the type of the corresponding argument
2405 // of the call (call it A) as described below.
2406 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002407 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002408 return TDK_TooFewArguments;
2409 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002410 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002411 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002412 if (Proto->isTemplateVariadic())
2413 /* Do nothing */;
2414 else if (Proto->isVariadic())
2415 CheckArgs = Function->getNumParams();
2416 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002417 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002418 }
Mike Stump1eb44332009-09-09 15:08:12 +00002419
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002420 // The types of the parameters from which we will perform template argument
2421 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002422 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002423 TemplateParameterList *TemplateParams
2424 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002425 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002426 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002427 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002428 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002429 TemplateDeductionResult Result =
2430 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002431 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002432 Deduced,
2433 ParamTypes,
2434 0,
2435 Info);
2436 if (Result)
2437 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002438
2439 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002440 } else {
2441 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002442 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002443 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2444 }
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002446 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002447 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002448 unsigned ArgIdx = 0;
2449 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2450 ParamIdx != NumParams; ++ParamIdx) {
2451 QualType ParamType = ParamTypes[ParamIdx];
2452
2453 const PackExpansionType *ParamExpansion
2454 = dyn_cast<PackExpansionType>(ParamType);
2455 if (!ParamExpansion) {
2456 // Simple case: matching a function parameter to a function argument.
2457 if (ArgIdx >= CheckArgs)
2458 break;
2459
2460 Expr *Arg = Args[ArgIdx++];
2461 QualType ArgType = Arg->getType();
2462 unsigned TDF = 0;
2463 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2464 ParamType, ArgType, Arg,
2465 TDF))
2466 continue;
2467
2468 if (TemplateDeductionResult Result
2469 = ::DeduceTemplateArguments(*this, TemplateParams,
2470 ParamType, ArgType, Info, Deduced,
2471 TDF))
2472 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002474 // FIXME: we need to check that the deduced A is the same as A,
2475 // modulo the various allowed differences.
2476 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002477 }
2478
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002479 // C++0x [temp.deduct.call]p1:
2480 // For a function parameter pack that occurs at the end of the
2481 // parameter-declaration-list, the type A of each remaining argument of
2482 // the call is compared with the type P of the declarator-id of the
2483 // function parameter pack. Each comparison deduces template arguments
2484 // for subsequent positions in the template parameter packs expanded by
2485 // the function parameter pack.
2486 QualType ParamPattern = ParamExpansion->getPattern();
2487 llvm::SmallVector<unsigned, 2> PackIndices;
2488 {
2489 llvm::BitVector SawIndices(TemplateParams->size());
2490 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2491 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2492 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2493 unsigned Depth, Index;
2494 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2495 if (Depth == 0 && !SawIndices[Index]) {
2496 SawIndices[Index] = true;
2497 PackIndices.push_back(Index);
2498 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002499 }
2500 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002501 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2502
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002503 // Keep track of the deduced template arguments for each parameter pack
2504 // expanded by this pack expansion (the outer index) and for each
2505 // template argument (the inner SmallVectors).
2506 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00002507 NewlyDeducedPacks(PackIndices.size());
2508
2509 // Save the deduced template arguments for each parameter pack expanded
2510 // by this pack expansion, then clear out the deduction.
2511 llvm::SmallVector<DeducedTemplateArgument, 2>
2512 SavedPacks(PackIndices.size());
2513 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2514 // Save the previously-deduced argument pack, then clear it out so that we
2515 // can deduce a new argument pack.
2516 SavedPacks[I] = Deduced[PackIndices[I]];
2517 Deduced[PackIndices[I]] = TemplateArgument();
2518
2519 // If the template arugment pack was explicitly specified, add that to
2520 // the set of deduced arguments.
2521 const TemplateArgument *ExplicitArgs;
2522 unsigned NumExplicitArgs;
2523 if (NamedDecl *PartiallySubstitutedPack
2524 = CurrentInstantiationScope->getPartiallySubstitutedPack(
2525 &ExplicitArgs,
2526 &NumExplicitArgs)) {
2527 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
2528 NewlyDeducedPacks[I].append(ExplicitArgs,
2529 ExplicitArgs + NumExplicitArgs);
2530 }
2531 }
2532
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002533 bool HasAnyArguments = false;
2534 for (; ArgIdx < NumArgs; ++ArgIdx) {
2535 HasAnyArguments = true;
2536
2537 ParamType = ParamPattern;
2538 Expr *Arg = Args[ArgIdx];
2539 QualType ArgType = Arg->getType();
2540 unsigned TDF = 0;
2541 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2542 ParamType, ArgType, Arg,
2543 TDF)) {
2544 // We can't actually perform any deduction for this argument, so stop
2545 // deduction at this point.
2546 ++ArgIdx;
2547 break;
2548 }
2549
2550 if (TemplateDeductionResult Result
2551 = ::DeduceTemplateArguments(*this, TemplateParams,
2552 ParamType, ArgType, Info, Deduced,
2553 TDF))
2554 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002556 // Capture the deduced template arguments for each parameter pack expanded
2557 // by this pack expansion, add them to the list of arguments we've deduced
2558 // for that pack, then clear out the deduced argument.
2559 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2560 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2561 if (!DeducedArg.isNull()) {
2562 NewlyDeducedPacks[I].push_back(DeducedArg);
2563 DeducedArg = DeducedTemplateArgument();
2564 }
2565 }
2566 }
2567
2568 // Build argument packs for each of the parameter packs expanded by this
2569 // pack expansion.
2570 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2571 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
2572 // We were not able to deduce anything for this parameter pack,
2573 // so just restore the saved argument pack.
2574 Deduced[PackIndices[I]] = SavedPacks[I];
2575 continue;
2576 }
2577
2578 DeducedTemplateArgument NewPack;
2579
2580 if (NewlyDeducedPacks[I].empty()) {
2581 // If we deduced an empty argument pack, create it now.
2582 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
2583 } else {
2584 TemplateArgument *ArgumentPack
2585 = new (Context) TemplateArgument [NewlyDeducedPacks[I].size()];
2586 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
2587 ArgumentPack);
2588 NewPack
2589 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
2590 NewlyDeducedPacks[I].size()),
2591 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
2592 }
2593
2594 DeducedTemplateArgument Result
2595 = checkDeducedTemplateArguments(Context, SavedPacks[I], NewPack);
2596 if (Result.isNull()) {
2597 Info.Param
2598 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
2599 Info.FirstArg = SavedPacks[I];
2600 Info.SecondArg = NewPack;
2601 return Sema::TDK_Inconsistent;
2602 }
2603
2604 Deduced[PackIndices[I]] = Result;
2605 }
Mike Stump1eb44332009-09-09 15:08:12 +00002606
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002607 // After we've matching against a parameter pack, we're done.
2608 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002609 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002610
Mike Stump1eb44332009-09-09 15:08:12 +00002611 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002612 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002613 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002614}
2615
Douglas Gregor83314aa2009-07-08 20:55:45 +00002616/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002617/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2618/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002619///
2620/// \param FunctionTemplate the function template for which we are performing
2621/// template argument deduction.
2622///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002623/// \param ExplicitTemplateArguments the explicitly-specified template
2624/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002625///
2626/// \param ArgFunctionType the function type that will be used as the
2627/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002628/// function template's function type. This type may be NULL, if there is no
2629/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002630///
2631/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002632/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002633/// template argument deduction.
2634///
2635/// \param Info the argument will be updated to provide additional information
2636/// about template argument deduction.
2637///
2638/// \returns the result of template argument deduction.
2639Sema::TemplateDeductionResult
2640Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002641 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002642 QualType ArgFunctionType,
2643 FunctionDecl *&Specialization,
2644 TemplateDeductionInfo &Info) {
2645 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2646 TemplateParameterList *TemplateParams
2647 = FunctionTemplate->getTemplateParameters();
2648 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002649
Douglas Gregor83314aa2009-07-08 20:55:45 +00002650 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002651 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002652 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2653 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002654 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002655 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002656 if (TemplateDeductionResult Result
2657 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002658 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002659 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002660 &FunctionType, Info))
2661 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002662
2663 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002664 }
2665
2666 // Template argument deduction for function templates in a SFINAE context.
2667 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002668 SFINAETrap Trap(*this);
2669
John McCalleff92132010-02-02 02:21:27 +00002670 Deduced.resize(TemplateParams->size());
2671
Douglas Gregor4b52e252009-12-21 23:17:24 +00002672 if (!ArgFunctionType.isNull()) {
2673 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002674 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002675 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002676 FunctionType, ArgFunctionType, Info,
2677 Deduced, 0))
2678 return Result;
2679 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002680
2681 if (TemplateDeductionResult Result
2682 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2683 NumExplicitlySpecified,
2684 Specialization, Info))
2685 return Result;
2686
2687 // If the requested function type does not match the actual type of the
2688 // specialization, template argument deduction fails.
2689 if (!ArgFunctionType.isNull() &&
2690 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2691 return TDK_NonDeducedMismatch;
2692
2693 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002694}
2695
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002696/// \brief Deduce template arguments for a templated conversion
2697/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2698/// conversion function template specialization.
2699Sema::TemplateDeductionResult
2700Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2701 QualType ToType,
2702 CXXConversionDecl *&Specialization,
2703 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002704 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002705 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2706 QualType FromType = Conv->getConversionType();
2707
2708 // Canonicalize the types for deduction.
2709 QualType P = Context.getCanonicalType(FromType);
2710 QualType A = Context.getCanonicalType(ToType);
2711
2712 // C++0x [temp.deduct.conv]p3:
2713 // If P is a reference type, the type referred to by P is used for
2714 // type deduction.
2715 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2716 P = PRef->getPointeeType();
2717
2718 // C++0x [temp.deduct.conv]p3:
2719 // If A is a reference type, the type referred to by A is used
2720 // for type deduction.
2721 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2722 A = ARef->getPointeeType();
2723 // C++ [temp.deduct.conv]p2:
2724 //
Mike Stump1eb44332009-09-09 15:08:12 +00002725 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002726 else {
2727 assert(!A->isReferenceType() && "Reference types were handled above");
2728
2729 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002730 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002731 // of P for type deduction; otherwise,
2732 if (P->isArrayType())
2733 P = Context.getArrayDecayedType(P);
2734 // - If P is a function type, the pointer type produced by the
2735 // function-to-pointer standard conversion (4.3) is used in
2736 // place of P for type deduction; otherwise,
2737 else if (P->isFunctionType())
2738 P = Context.getPointerType(P);
2739 // - If P is a cv-qualified type, the top level cv-qualifiers of
2740 // P’s type are ignored for type deduction.
2741 else
2742 P = P.getUnqualifiedType();
2743
2744 // C++0x [temp.deduct.conv]p3:
2745 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2746 // type are ignored for type deduction.
2747 A = A.getUnqualifiedType();
2748 }
2749
2750 // Template argument deduction for function templates in a SFINAE context.
2751 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002752 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002753
2754 // C++ [temp.deduct.conv]p1:
2755 // Template argument deduction is done by comparing the return
2756 // type of the template conversion function (call it P) with the
2757 // type that is required as the result of the conversion (call it
2758 // A) as described in 14.8.2.4.
2759 TemplateParameterList *TemplateParams
2760 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002761 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002762 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002763
2764 // C++0x [temp.deduct.conv]p4:
2765 // In general, the deduction process attempts to find template
2766 // argument values that will make the deduced A identical to
2767 // A. However, there are two cases that allow a difference:
2768 unsigned TDF = 0;
2769 // - If the original A is a reference type, A can be more
2770 // cv-qualified than the deduced A (i.e., the type referred to
2771 // by the reference)
2772 if (ToType->isReferenceType())
2773 TDF |= TDF_ParamWithReferenceType;
2774 // - The deduced A can be another pointer or pointer to member
2775 // type that can be converted to A via a qualification
2776 // conversion.
2777 //
2778 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2779 // both P and A are pointers or member pointers. In this case, we
2780 // just ignore cv-qualifiers completely).
2781 if ((P->isPointerType() && A->isPointerType()) ||
2782 (P->isMemberPointerType() && P->isMemberPointerType()))
2783 TDF |= TDF_IgnoreQualifiers;
2784 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002785 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002786 P, A, Info, Deduced, TDF))
2787 return Result;
2788
2789 // FIXME: we need to check that the deduced A is the same as A,
2790 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002792 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002793 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002794 FunctionDecl *Spec = 0;
2795 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002796 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2797 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002798 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2799 return Result;
2800}
2801
Douglas Gregor4b52e252009-12-21 23:17:24 +00002802/// \brief Deduce template arguments for a function template when there is
2803/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2804///
2805/// \param FunctionTemplate the function template for which we are performing
2806/// template argument deduction.
2807///
2808/// \param ExplicitTemplateArguments the explicitly-specified template
2809/// arguments.
2810///
2811/// \param Specialization if template argument deduction was successful,
2812/// this will be set to the function template specialization produced by
2813/// template argument deduction.
2814///
2815/// \param Info the argument will be updated to provide additional information
2816/// about template argument deduction.
2817///
2818/// \returns the result of template argument deduction.
2819Sema::TemplateDeductionResult
2820Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2821 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2822 FunctionDecl *&Specialization,
2823 TemplateDeductionInfo &Info) {
2824 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2825 QualType(), Specialization, Info);
2826}
2827
Douglas Gregor8a514912009-09-14 18:39:43 +00002828/// \brief Stores the result of comparing the qualifiers of two types.
2829enum DeductionQualifierComparison {
2830 NeitherMoreQualified = 0,
2831 ParamMoreQualified,
2832 ArgMoreQualified
2833};
2834
2835/// \brief Deduce the template arguments during partial ordering by comparing
2836/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2837///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002838/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002839///
2840/// \param TemplateParams the template parameters that we are deducing
2841///
2842/// \param ParamIn the parameter type
2843///
2844/// \param ArgIn the argument type
2845///
2846/// \param Info information about the template argument deduction itself
2847///
2848/// \param Deduced the deduced template arguments
2849///
2850/// \returns the result of template argument deduction so far. Note that a
2851/// "success" result means that template argument deduction has not yet failed,
2852/// but it may still fail, later, for other reasons.
2853static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002854DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002855 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002856 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002857 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002858 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2859 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002860 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2861 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002862
2863 // C++0x [temp.deduct.partial]p5:
2864 // Before the partial ordering is done, certain transformations are
2865 // performed on the types used for partial ordering:
2866 // - If P is a reference type, P is replaced by the type referred to.
2867 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002868 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002869 Param = ParamRef->getPointeeType();
2870
2871 // - If A is a reference type, A is replaced by the type referred to.
2872 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002873 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002874 Arg = ArgRef->getPointeeType();
2875
John McCalle27ec8a2009-10-23 23:03:21 +00002876 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002877 // C++0x [temp.deduct.partial]p6:
2878 // If both P and A were reference types (before being replaced with the
2879 // type referred to above), determine which of the two types (if any) is
2880 // more cv-qualified than the other; otherwise the types are considered to
2881 // be equally cv-qualified for partial ordering purposes. The result of this
2882 // determination will be used below.
2883 //
2884 // We save this information for later, using it only when deduction
2885 // succeeds in both directions.
2886 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2887 if (Param.isMoreQualifiedThan(Arg))
2888 QualifierResult = ParamMoreQualified;
2889 else if (Arg.isMoreQualifiedThan(Param))
2890 QualifierResult = ArgMoreQualified;
2891 QualifierComparisons->push_back(QualifierResult);
2892 }
2893
2894 // C++0x [temp.deduct.partial]p7:
2895 // Remove any top-level cv-qualifiers:
2896 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2897 // version of P.
2898 Param = Param.getUnqualifiedType();
2899 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2900 // version of A.
2901 Arg = Arg.getUnqualifiedType();
2902
2903 // C++0x [temp.deduct.partial]p8:
2904 // Using the resulting types P and A the deduction is then done as
2905 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2906 // from the argument template is considered to be at least as specialized
2907 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002908 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002909 Deduced, TDF_None);
2910}
2911
2912static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002913MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2914 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002915 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002916 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002917
2918/// \brief If this is a non-static member function,
2919static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2920 CXXMethodDecl *Method,
2921 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2922 if (Method->isStatic())
2923 return;
2924
2925 // C++ [over.match.funcs]p4:
2926 //
2927 // For non-static member functions, the type of the implicit
2928 // object parameter is
2929 // — "lvalue reference to cv X" for functions declared without a
2930 // ref-qualifier or with the & ref-qualifier
2931 // - "rvalue reference to cv X" for functions declared with the
2932 // && ref-qualifier
2933 //
2934 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2935 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2936 ArgTy = Context.getQualifiedType(ArgTy,
2937 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2938 ArgTy = Context.getLValueReferenceType(ArgTy);
2939 ArgTypes.push_back(ArgTy);
2940}
2941
Douglas Gregor8a514912009-09-14 18:39:43 +00002942/// \brief Determine whether the function template \p FT1 is at least as
2943/// specialized as \p FT2.
2944static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002945 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002946 FunctionTemplateDecl *FT1,
2947 FunctionTemplateDecl *FT2,
2948 TemplatePartialOrderingContext TPOC,
2949 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2950 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2951 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2952 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2953 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2954
2955 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2956 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002957 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002958 Deduced.resize(TemplateParams->size());
2959
2960 // C++0x [temp.deduct.partial]p3:
2961 // The types used to determine the ordering depend on the context in which
2962 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002963 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002964 CXXMethodDecl *Method1 = 0;
2965 CXXMethodDecl *Method2 = 0;
2966 bool IsNonStatic2 = false;
2967 bool IsNonStatic1 = false;
2968 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002969 switch (TPOC) {
2970 case TPOC_Call: {
2971 // - In the context of a function call, the function parameter types are
2972 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002973 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2974 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2975 IsNonStatic1 = Method1 && !Method1->isStatic();
2976 IsNonStatic2 = Method2 && !Method2->isStatic();
2977
2978 // C++0x [temp.func.order]p3:
2979 // [...] If only one of the function templates is a non-static
2980 // member, that function template is considered to have a new
2981 // first parameter inserted in its function parameter list. The
2982 // new parameter is of type "reference to cv A," where cv are
2983 // the cv-qualifiers of the function template (if any) and A is
2984 // the class of which the function template is a member.
2985 //
2986 // C++98/03 doesn't have this provision, so instead we drop the
2987 // first argument of the free function or static member, which
2988 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002989 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002990 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2991 IsNonStatic2 && !IsNonStatic1;
2992 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002993 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2994 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002995 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002996
2997 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002998 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2999 IsNonStatic1 && !IsNonStatic2;
3000 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00003001 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
3002 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003003 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00003004
3005 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00003006 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003007 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00003008 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00003009 Args2[I],
3010 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00003011 Info,
3012 Deduced,
3013 QualifierComparisons))
3014 return false;
3015
3016 break;
3017 }
3018
3019 case TPOC_Conversion:
3020 // - In the context of a call to a conversion operator, the return types
3021 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003022 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00003023 TemplateParams,
3024 Proto2->getResultType(),
3025 Proto1->getResultType(),
3026 Info,
3027 Deduced,
3028 QualifierComparisons))
3029 return false;
3030 break;
3031
3032 case TPOC_Other:
3033 // - In other contexts (14.6.6.2) the function template’s function type
3034 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003035 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00003036 TemplateParams,
3037 FD2->getType(),
3038 FD1->getType(),
3039 Info,
3040 Deduced,
3041 QualifierComparisons))
3042 return false;
3043 break;
3044 }
3045
3046 // C++0x [temp.deduct.partial]p11:
3047 // In most cases, all template parameters must have values in order for
3048 // deduction to succeed, but for partial ordering purposes a template
3049 // parameter may remain without a value provided it is not used in the
3050 // types being used for partial ordering. [ Note: a template parameter used
3051 // in a non-deduced context is considered used. -end note]
3052 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3053 for (; ArgIdx != NumArgs; ++ArgIdx)
3054 if (Deduced[ArgIdx].isNull())
3055 break;
3056
3057 if (ArgIdx == NumArgs) {
3058 // All template arguments were deduced. FT1 is at least as specialized
3059 // as FT2.
3060 return true;
3061 }
3062
Douglas Gregore73bb602009-09-14 21:25:05 +00003063 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003064 llvm::SmallVector<bool, 4> UsedParameters;
3065 UsedParameters.resize(TemplateParams->size());
3066 switch (TPOC) {
3067 case TPOC_Call: {
3068 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003069 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3070 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3071 TemplateParams->getDepth(), UsedParameters);
3072 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003073 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3074 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003075 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003076 break;
3077 }
3078
3079 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003080 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3081 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003082 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003083 break;
3084
3085 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003086 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3087 TemplateParams->getDepth(),
3088 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003089 break;
3090 }
3091
3092 for (; ArgIdx != NumArgs; ++ArgIdx)
3093 // If this argument had no value deduced but was used in one of the types
3094 // used for partial ordering, then deduction fails.
3095 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3096 return false;
3097
3098 return true;
3099}
3100
3101
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003102/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003103/// to the rules of function template partial ordering (C++ [temp.func.order]).
3104///
3105/// \param FT1 the first function template
3106///
3107/// \param FT2 the second function template
3108///
Douglas Gregor8a514912009-09-14 18:39:43 +00003109/// \param TPOC the context in which we are performing partial ordering of
3110/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003111///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003112/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003113/// template is more specialized, returns NULL.
3114FunctionTemplateDecl *
3115Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3116 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003117 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003118 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003119 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00003120 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
3121 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00003122 &QualifierComparisons);
3123
3124 if (Better1 != Better2) // We have a clear winner
3125 return Better1? FT1 : FT2;
3126
3127 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003128 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003129
3130
3131 // C++0x [temp.deduct.partial]p10:
3132 // If for each type being considered a given template is at least as
3133 // specialized for all types and more specialized for some set of types and
3134 // the other template is not more specialized for any types or is not at
3135 // least as specialized for any types, then the given template is more
3136 // specialized than the other template. Otherwise, neither template is more
3137 // specialized than the other.
3138 Better1 = false;
3139 Better2 = false;
3140 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3141 // C++0x [temp.deduct.partial]p9:
3142 // If, for a given type, deduction succeeds in both directions (i.e., the
3143 // types are identical after the transformations above) and if the type
3144 // from the argument template is more cv-qualified than the type from the
3145 // parameter template (as described above) that type is considered to be
3146 // more specialized than the other. If neither type is more cv-qualified
3147 // than the other then neither type is more specialized than the other.
3148 switch (QualifierComparisons[I]) {
3149 case NeitherMoreQualified:
3150 break;
3151
3152 case ParamMoreQualified:
3153 Better1 = true;
3154 if (Better2)
3155 return 0;
3156 break;
3157
3158 case ArgMoreQualified:
3159 Better2 = true;
3160 if (Better1)
3161 return 0;
3162 break;
3163 }
3164 }
3165
3166 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003167 if (Better1)
3168 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003169 else if (Better2)
3170 return FT2;
3171 else
3172 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003173}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003174
Douglas Gregord5a423b2009-09-25 18:43:00 +00003175/// \brief Determine if the two templates are equivalent.
3176static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3177 if (T1 == T2)
3178 return true;
3179
3180 if (!T1 || !T2)
3181 return false;
3182
3183 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3184}
3185
3186/// \brief Retrieve the most specialized of the given function template
3187/// specializations.
3188///
John McCallc373d482010-01-27 01:50:18 +00003189/// \param SpecBegin the start iterator of the function template
3190/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003191///
John McCallc373d482010-01-27 01:50:18 +00003192/// \param SpecEnd the end iterator of the function template
3193/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003194///
3195/// \param TPOC the partial ordering context to use to compare the function
3196/// template specializations.
3197///
3198/// \param Loc the location where the ambiguity or no-specializations
3199/// diagnostic should occur.
3200///
3201/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3202/// no matching candidates.
3203///
3204/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3205/// occurs.
3206///
3207/// \param CandidateDiag partial diagnostic used for each function template
3208/// specialization that is a candidate in the ambiguous ordering. One parameter
3209/// in this diagnostic should be unbound, which will correspond to the string
3210/// describing the template arguments for the function template specialization.
3211///
3212/// \param Index if non-NULL and the result of this function is non-nULL,
3213/// receives the index corresponding to the resulting function template
3214/// specialization.
3215///
3216/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003217/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003218///
3219/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3220/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003221UnresolvedSetIterator
3222Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3223 UnresolvedSetIterator SpecEnd,
3224 TemplatePartialOrderingContext TPOC,
3225 SourceLocation Loc,
3226 const PartialDiagnostic &NoneDiag,
3227 const PartialDiagnostic &AmbigDiag,
3228 const PartialDiagnostic &CandidateDiag) {
3229 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003230 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003231 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003232 }
3233
John McCallc373d482010-01-27 01:50:18 +00003234 if (SpecBegin + 1 == SpecEnd)
3235 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003236
3237 // Find the function template that is better than all of the templates it
3238 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003239 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003240 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003241 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003242 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003243 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3244 FunctionTemplateDecl *Challenger
3245 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003246 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003247 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003248 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003249 Challenger)) {
3250 Best = I;
3251 BestTemplate = Challenger;
3252 }
3253 }
3254
3255 // Make sure that the "best" function template is more specialized than all
3256 // of the others.
3257 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003258 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3259 FunctionTemplateDecl *Challenger
3260 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003261 if (I != Best &&
3262 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003263 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003264 BestTemplate)) {
3265 Ambiguous = true;
3266 break;
3267 }
3268 }
3269
3270 if (!Ambiguous) {
3271 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003272 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003273 }
3274
3275 // Diagnose the ambiguity.
3276 Diag(Loc, AmbigDiag);
3277
3278 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003279 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3280 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003281 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003282 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3283 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003284
John McCallc373d482010-01-27 01:50:18 +00003285 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003286}
3287
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003288/// \brief Returns the more specialized class template partial specialization
3289/// according to the rules of partial ordering of class template partial
3290/// specializations (C++ [temp.class.order]).
3291///
3292/// \param PS1 the first class template partial specialization
3293///
3294/// \param PS2 the second class template partial specialization
3295///
3296/// \returns the more specialized class template partial specialization. If
3297/// neither partial specialization is more specialized, returns NULL.
3298ClassTemplatePartialSpecializationDecl *
3299Sema::getMoreSpecializedPartialSpecialization(
3300 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003301 ClassTemplatePartialSpecializationDecl *PS2,
3302 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003303 // C++ [temp.class.order]p1:
3304 // For two class template partial specializations, the first is at least as
3305 // specialized as the second if, given the following rewrite to two
3306 // function templates, the first function template is at least as
3307 // specialized as the second according to the ordering rules for function
3308 // templates (14.6.6.2):
3309 // - the first function template has the same template parameters as the
3310 // first partial specialization and has a single function parameter
3311 // whose type is a class template specialization with the template
3312 // arguments of the first partial specialization, and
3313 // - the second function template has the same template parameters as the
3314 // second partial specialization and has a single function parameter
3315 // whose type is a class template specialization with the template
3316 // arguments of the second partial specialization.
3317 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003318 // Rather than synthesize function templates, we merely perform the
3319 // equivalent partial ordering by performing deduction directly on
3320 // the template arguments of the class template partial
3321 // specializations. This computation is slightly simpler than the
3322 // general problem of function template partial ordering, because
3323 // class template partial specializations are more constrained. We
3324 // know that every template parameter is deducible from the class
3325 // template partial specialization's template arguments, for
3326 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003327 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003328 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003329
3330 QualType PT1 = PS1->getInjectedSpecializationType();
3331 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003332
3333 // Determine whether PS1 is at least as specialized as PS2
3334 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003335 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003336 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003337 PT2,
3338 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003339 Info,
3340 Deduced,
3341 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003342 if (Better1) {
3343 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3344 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003345 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3346 PS1->getTemplateArgs(),
3347 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003348 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003349
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003350 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003351 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003352 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003353 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003354 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003355 PT1,
3356 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003357 Info,
3358 Deduced,
3359 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003360 if (Better2) {
3361 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3362 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003363 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3364 PS2->getTemplateArgs(),
3365 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003366 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003367
3368 if (Better1 == Better2)
3369 return 0;
3370
3371 return Better1? PS1 : PS2;
3372}
3373
Mike Stump1eb44332009-09-09 15:08:12 +00003374static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003375MarkUsedTemplateParameters(Sema &SemaRef,
3376 const TemplateArgument &TemplateArg,
3377 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003378 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003379 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003380
Douglas Gregore73bb602009-09-14 21:25:05 +00003381/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003382/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003383static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003384MarkUsedTemplateParameters(Sema &SemaRef,
3385 const Expr *E,
3386 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003387 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003388 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003389 // We can deduce from a pack expansion.
3390 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3391 E = Expansion->getPattern();
3392
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003393 // Skip through any implicit casts we added while type-checking.
3394 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3395 E = ICE->getSubExpr();
3396
Douglas Gregore73bb602009-09-14 21:25:05 +00003397 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3398 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003399 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003400 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003401 return;
3402
Mike Stump1eb44332009-09-09 15:08:12 +00003403 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003404 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3405 if (!NTTP)
3406 return;
3407
Douglas Gregored9c0f92009-10-29 00:04:11 +00003408 if (NTTP->getDepth() == Depth)
3409 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003410}
3411
Douglas Gregore73bb602009-09-14 21:25:05 +00003412/// \brief Mark the template parameters that are used by the given
3413/// nested name specifier.
3414static void
3415MarkUsedTemplateParameters(Sema &SemaRef,
3416 NestedNameSpecifier *NNS,
3417 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003418 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003419 llvm::SmallVectorImpl<bool> &Used) {
3420 if (!NNS)
3421 return;
3422
Douglas Gregored9c0f92009-10-29 00:04:11 +00003423 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3424 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003425 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003426 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003427}
3428
3429/// \brief Mark the template parameters that are used by the given
3430/// template name.
3431static void
3432MarkUsedTemplateParameters(Sema &SemaRef,
3433 TemplateName Name,
3434 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003435 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003436 llvm::SmallVectorImpl<bool> &Used) {
3437 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3438 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003439 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3440 if (TTP->getDepth() == Depth)
3441 Used[TTP->getIndex()] = true;
3442 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003443 return;
3444 }
3445
Douglas Gregor788cd062009-11-11 01:00:40 +00003446 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3447 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3448 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003449 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003450 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3451 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003452}
3453
3454/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003455/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003456static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003457MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3458 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003459 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003460 llvm::SmallVectorImpl<bool> &Used) {
3461 if (T.isNull())
3462 return;
3463
Douglas Gregor031a5882009-06-13 00:26:55 +00003464 // Non-dependent types have nothing deducible
3465 if (!T->isDependentType())
3466 return;
3467
3468 T = SemaRef.Context.getCanonicalType(T);
3469 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003470 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003471 MarkUsedTemplateParameters(SemaRef,
3472 cast<PointerType>(T)->getPointeeType(),
3473 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003474 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003475 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003476 break;
3477
3478 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003479 MarkUsedTemplateParameters(SemaRef,
3480 cast<BlockPointerType>(T)->getPointeeType(),
3481 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003482 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003483 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003484 break;
3485
3486 case Type::LValueReference:
3487 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003488 MarkUsedTemplateParameters(SemaRef,
3489 cast<ReferenceType>(T)->getPointeeType(),
3490 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003491 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003492 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003493 break;
3494
3495 case Type::MemberPointer: {
3496 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003497 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003498 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003499 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003500 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003501 break;
3502 }
3503
3504 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003505 MarkUsedTemplateParameters(SemaRef,
3506 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003507 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003508 // Fall through to check the element type
3509
3510 case Type::ConstantArray:
3511 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003512 MarkUsedTemplateParameters(SemaRef,
3513 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003514 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003515 break;
3516
3517 case Type::Vector:
3518 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003519 MarkUsedTemplateParameters(SemaRef,
3520 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003521 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003522 break;
3523
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003524 case Type::DependentSizedExtVector: {
3525 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003526 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003527 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003528 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003529 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003530 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003531 break;
3532 }
3533
Douglas Gregor031a5882009-06-13 00:26:55 +00003534 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003535 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003536 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003537 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003538 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003539 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003540 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003541 break;
3542 }
3543
Douglas Gregored9c0f92009-10-29 00:04:11 +00003544 case Type::TemplateTypeParm: {
3545 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3546 if (TTP->getDepth() == Depth)
3547 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003548 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003549 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003550
John McCall31f17ec2010-04-27 00:57:59 +00003551 case Type::InjectedClassName:
3552 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3553 // fall through
3554
Douglas Gregor031a5882009-06-13 00:26:55 +00003555 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003556 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003557 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003558 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003559 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003560
3561 // C++0x [temp.deduct.type]p9:
3562 // If the template argument list of P contains a pack expansion that is not
3563 // the last template argument, the entire template argument list is a
3564 // non-deduced context.
3565 if (OnlyDeduced &&
3566 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3567 break;
3568
Douglas Gregore73bb602009-09-14 21:25:05 +00003569 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003570 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3571 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003572 break;
3573 }
3574
Douglas Gregore73bb602009-09-14 21:25:05 +00003575 case Type::Complex:
3576 if (!OnlyDeduced)
3577 MarkUsedTemplateParameters(SemaRef,
3578 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003579 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003580 break;
3581
Douglas Gregor4714c122010-03-31 17:34:00 +00003582 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003583 if (!OnlyDeduced)
3584 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003585 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003586 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003587 break;
3588
John McCall33500952010-06-11 00:33:02 +00003589 case Type::DependentTemplateSpecialization: {
3590 const DependentTemplateSpecializationType *Spec
3591 = cast<DependentTemplateSpecializationType>(T);
3592 if (!OnlyDeduced)
3593 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3594 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003595
3596 // C++0x [temp.deduct.type]p9:
3597 // If the template argument list of P contains a pack expansion that is not
3598 // the last template argument, the entire template argument list is a
3599 // non-deduced context.
3600 if (OnlyDeduced &&
3601 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3602 break;
3603
John McCall33500952010-06-11 00:33:02 +00003604 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3605 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3606 Used);
3607 break;
3608 }
3609
John McCallad5e7382010-03-01 23:49:17 +00003610 case Type::TypeOf:
3611 if (!OnlyDeduced)
3612 MarkUsedTemplateParameters(SemaRef,
3613 cast<TypeOfType>(T)->getUnderlyingType(),
3614 OnlyDeduced, Depth, Used);
3615 break;
3616
3617 case Type::TypeOfExpr:
3618 if (!OnlyDeduced)
3619 MarkUsedTemplateParameters(SemaRef,
3620 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3621 OnlyDeduced, Depth, Used);
3622 break;
3623
3624 case Type::Decltype:
3625 if (!OnlyDeduced)
3626 MarkUsedTemplateParameters(SemaRef,
3627 cast<DecltypeType>(T)->getUnderlyingExpr(),
3628 OnlyDeduced, Depth, Used);
3629 break;
3630
Douglas Gregor7536dd52010-12-20 02:24:11 +00003631 case Type::PackExpansion:
3632 MarkUsedTemplateParameters(SemaRef,
3633 cast<PackExpansionType>(T)->getPattern(),
3634 OnlyDeduced, Depth, Used);
3635 break;
3636
Douglas Gregore73bb602009-09-14 21:25:05 +00003637 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003638 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003639 case Type::VariableArray:
3640 case Type::FunctionNoProto:
3641 case Type::Record:
3642 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003643 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003644 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003645 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003646 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003647#define TYPE(Class, Base)
3648#define ABSTRACT_TYPE(Class, Base)
3649#define DEPENDENT_TYPE(Class, Base)
3650#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3651#include "clang/AST/TypeNodes.def"
3652 break;
3653 }
3654}
3655
Douglas Gregore73bb602009-09-14 21:25:05 +00003656/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003657/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003658static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003659MarkUsedTemplateParameters(Sema &SemaRef,
3660 const TemplateArgument &TemplateArg,
3661 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003662 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003663 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003664 switch (TemplateArg.getKind()) {
3665 case TemplateArgument::Null:
3666 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003667 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003668 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003669
Douglas Gregor031a5882009-06-13 00:26:55 +00003670 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003671 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003672 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003673 break;
3674
Douglas Gregor788cd062009-11-11 01:00:40 +00003675 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003676 case TemplateArgument::TemplateExpansion:
3677 MarkUsedTemplateParameters(SemaRef,
3678 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003679 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003680 break;
3681
3682 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003683 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003684 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003685 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003686
Anders Carlssond01b1da2009-06-15 17:04:53 +00003687 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003688 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3689 PEnd = TemplateArg.pack_end();
3690 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003691 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003692 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003693 }
3694}
3695
3696/// \brief Mark the template parameters can be deduced by the given
3697/// template argument list.
3698///
3699/// \param TemplateArgs the template argument list from which template
3700/// parameters will be deduced.
3701///
3702/// \param Deduced a bit vector whose elements will be set to \c true
3703/// to indicate when the corresponding template parameter will be
3704/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003705void
Douglas Gregore73bb602009-09-14 21:25:05 +00003706Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003707 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003708 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003709 // C++0x [temp.deduct.type]p9:
3710 // If the template argument list of P contains a pack expansion that is not
3711 // the last template argument, the entire template argument list is a
3712 // non-deduced context.
3713 if (OnlyDeduced &&
3714 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3715 return;
3716
Douglas Gregor031a5882009-06-13 00:26:55 +00003717 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003718 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3719 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003720}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003721
3722/// \brief Marks all of the template parameters that will be deduced by a
3723/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003724void
3725Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3726 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003727 TemplateParameterList *TemplateParams
3728 = FunctionTemplate->getTemplateParameters();
3729 Deduced.clear();
3730 Deduced.resize(TemplateParams->size());
3731
3732 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3733 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3734 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003735 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003736}