blob: 644ff35c3e0fa9b8b7d47859582f03d7aa537864 [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregor20a55e22010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
Douglas Gregore02e2622010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000026
27namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregor508f1c82009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
52 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor0b9247f2009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor9d0e4412010-03-26 05:50:28 +000058/// \brief Compare two APSInts, extending and switching the sign as
59/// necessary to compare their values regardless of underlying type.
60static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
61 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000065
66 // If there is a signedness mismatch, correct it.
67 if (X.isSigned() != Y.isSigned()) {
68 // If the signed value is negative, then the values cannot be the same.
69 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
70 return false;
71
72 Y.setIsSigned(true);
73 X.setIsSigned(true);
74 }
75
76 return X == Y;
77}
78
Douglas Gregorf67875d2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000083 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000086
Douglas Gregor20a55e22010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
Douglas Gregor603cfb42011-01-05 23:12:31 +000090 QualType Param,
91 QualType Arg,
92 TemplateDeductionInfo &Info,
93 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 unsigned TDF);
95
96static Sema::TemplateDeductionResult
97DeduceTemplateArguments(Sema &S,
98 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +000099 const TemplateArgument *Params, unsigned NumParams,
100 const TemplateArgument *Args, unsigned NumArgs,
101 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000102 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
103 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000104
Douglas Gregor199d9912009-06-05 00:53:49 +0000105/// \brief If the given expression is of a form that permits the deduction
106/// of a non-type template parameter, return the declaration of that
107/// non-type template parameter.
108static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
109 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
110 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Douglas Gregor199d9912009-06-05 00:53:49 +0000112 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
113 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Douglas Gregor199d9912009-06-05 00:53:49 +0000115 return 0;
116}
117
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000118/// \brief Determine whether two declaration pointers refer to the same
119/// declaration.
120static bool isSameDeclaration(Decl *X, Decl *Y) {
121 if (!X || !Y)
122 return !X && !Y;
123
124 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
125 X = NX->getUnderlyingDecl();
126 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
127 Y = NY->getUnderlyingDecl();
128
129 return X->getCanonicalDecl() == Y->getCanonicalDecl();
130}
131
132/// \brief Verify that the given, deduced template arguments are compatible.
133///
134/// \returns The deduced template argument, or a NULL template argument if
135/// the deduced template arguments were incompatible.
136static DeducedTemplateArgument
137checkDeducedTemplateArguments(ASTContext &Context,
138 const DeducedTemplateArgument &X,
139 const DeducedTemplateArgument &Y) {
140 // We have no deduction for one or both of the arguments; they're compatible.
141 if (X.isNull())
142 return Y;
143 if (Y.isNull())
144 return X;
145
146 switch (X.getKind()) {
147 case TemplateArgument::Null:
148 llvm_unreachable("Non-deduced template arguments handled above");
149
150 case TemplateArgument::Type:
151 // If two template type arguments have the same type, they're compatible.
152 if (Y.getKind() == TemplateArgument::Type &&
153 Context.hasSameType(X.getAsType(), Y.getAsType()))
154 return X;
155
156 return DeducedTemplateArgument();
157
158 case TemplateArgument::Integral:
159 // If we deduced a constant in one case and either a dependent expression or
160 // declaration in another case, keep the integral constant.
161 // If both are integral constants with the same value, keep that value.
162 if (Y.getKind() == TemplateArgument::Expression ||
163 Y.getKind() == TemplateArgument::Declaration ||
164 (Y.getKind() == TemplateArgument::Integral &&
165 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
166 return DeducedTemplateArgument(X,
167 X.wasDeducedFromArrayBound() &&
168 Y.wasDeducedFromArrayBound());
169
170 // All other combinations are incompatible.
171 return DeducedTemplateArgument();
172
173 case TemplateArgument::Template:
174 if (Y.getKind() == TemplateArgument::Template &&
175 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
176 return X;
177
178 // All other combinations are incompatible.
179 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000180
181 case TemplateArgument::TemplateExpansion:
182 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
183 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
184 Y.getAsTemplateOrTemplatePattern()))
185 return X;
186
187 // All other combinations are incompatible.
188 return DeducedTemplateArgument();
189
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000190 case TemplateArgument::Expression:
191 // If we deduced a dependent expression in one case and either an integral
192 // constant or a declaration in another case, keep the integral constant
193 // or declaration.
194 if (Y.getKind() == TemplateArgument::Integral ||
195 Y.getKind() == TemplateArgument::Declaration)
196 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
197 Y.wasDeducedFromArrayBound());
198
199 if (Y.getKind() == TemplateArgument::Expression) {
200 // Compare the expressions for equality
201 llvm::FoldingSetNodeID ID1, ID2;
202 X.getAsExpr()->Profile(ID1, Context, true);
203 Y.getAsExpr()->Profile(ID2, Context, true);
204 if (ID1 == ID2)
205 return X;
206 }
207
208 // All other combinations are incompatible.
209 return DeducedTemplateArgument();
210
211 case TemplateArgument::Declaration:
212 // If we deduced a declaration and a dependent expression, keep the
213 // declaration.
214 if (Y.getKind() == TemplateArgument::Expression)
215 return X;
216
217 // If we deduced a declaration and an integral constant, keep the
218 // integral constant.
219 if (Y.getKind() == TemplateArgument::Integral)
220 return Y;
221
222 // If we deduced two declarations, make sure they they refer to the
223 // same declaration.
224 if (Y.getKind() == TemplateArgument::Declaration &&
225 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
226 return X;
227
228 // All other combinations are incompatible.
229 return DeducedTemplateArgument();
230
231 case TemplateArgument::Pack:
232 if (Y.getKind() != TemplateArgument::Pack ||
233 X.pack_size() != Y.pack_size())
234 return DeducedTemplateArgument();
235
236 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
237 XAEnd = X.pack_end(),
238 YA = Y.pack_begin();
239 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000240 if (checkDeducedTemplateArguments(Context,
241 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
242 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
243 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000244 return DeducedTemplateArgument();
245 }
246
247 return X;
248 }
249
250 return DeducedTemplateArgument();
251}
252
Mike Stump1eb44332009-09-09 15:08:12 +0000253/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000254/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000255static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000256DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000257 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000258 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000259 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000260 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000261 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000262 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000263 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000265 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
266 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
267 Deduced[NTTP->getIndex()],
268 NewDeduced);
269 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000270 Info.Param = NTTP;
271 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000272 Info.SecondArg = NewDeduced;
273 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000274 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000275
276 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000277 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000281/// from the given type- or value-dependent expression.
282///
283/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000284static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000285DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000286 NonTypeTemplateParmDecl *NTTP,
287 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000288 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000289 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000290 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000291 "Cannot deduce non-type template argument with depth > 0");
292 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
293 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000295 DeducedTemplateArgument NewDeduced(Value);
296 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
297 Deduced[NTTP->getIndex()],
298 NewDeduced);
299
300 if (Result.isNull()) {
301 Info.Param = NTTP;
302 Info.FirstArg = Deduced[NTTP->getIndex()];
303 Info.SecondArg = NewDeduced;
304 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000305 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000306
307 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000308 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000309}
310
Douglas Gregor15755cb2009-11-13 23:45:44 +0000311/// \brief Deduce the value of the given non-type template parameter
312/// from the given declaration.
313///
314/// \returns true if deduction succeeded, false otherwise.
315static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000316DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000317 NonTypeTemplateParmDecl *NTTP,
318 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000319 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000320 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000321 assert(NTTP->getDepth() == 0 &&
322 "Cannot deduce non-type template argument with depth > 0");
323
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000324 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
325 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
326 Deduced[NTTP->getIndex()],
327 NewDeduced);
328 if (Result.isNull()) {
329 Info.Param = NTTP;
330 Info.FirstArg = Deduced[NTTP->getIndex()];
331 Info.SecondArg = NewDeduced;
332 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000333 }
334
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000335 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000336 return Sema::TDK_Success;
337}
338
Douglas Gregorf67875d2009-06-12 18:26:56 +0000339static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000340DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000341 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000342 TemplateName Param,
343 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000344 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000345 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000346 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000347 if (!ParamDecl) {
348 // The parameter type is dependent and is not a template template parameter,
349 // so there is nothing that we can deduce.
350 return Sema::TDK_Success;
351 }
352
353 if (TemplateTemplateParmDecl *TempParam
354 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000355 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
356 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
357 Deduced[TempParam->getIndex()],
358 NewDeduced);
359 if (Result.isNull()) {
360 Info.Param = TempParam;
361 Info.FirstArg = Deduced[TempParam->getIndex()];
362 Info.SecondArg = NewDeduced;
363 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000364 }
365
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000366 Deduced[TempParam->getIndex()] = Result;
367 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000368 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000369
370 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000371 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000372 return Sema::TDK_Success;
373
374 // Mismatch of non-dependent template parameter to argument.
375 Info.FirstArg = TemplateArgument(Param);
376 Info.SecondArg = TemplateArgument(Arg);
377 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000378}
379
Mike Stump1eb44332009-09-09 15:08:12 +0000380/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000381/// type (which is a template-id) with the template argument type.
382///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000383/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000384///
385/// \param TemplateParams the template parameters that we are deducing
386///
387/// \param Param the parameter type
388///
389/// \param Arg the argument type
390///
391/// \param Info information about the template argument deduction itself
392///
393/// \param Deduced the deduced template arguments
394///
395/// \returns the result of template argument deduction so far. Note that a
396/// "success" result means that template argument deduction has not yet failed,
397/// but it may still fail, later, for other reasons.
398static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000399DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000400 TemplateParameterList *TemplateParams,
401 const TemplateSpecializationType *Param,
402 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000403 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000404 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000405 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000407 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000408 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000409 = dyn_cast<TemplateSpecializationType>(Arg)) {
410 // Perform template argument deduction for the template name.
411 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000412 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000413 Param->getTemplateName(),
414 SpecArg->getTemplateName(),
415 Info, Deduced))
416 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000419 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000420 // argument. Ignore any missing/extra arguments, since they could be
421 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000422 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000423 Param->getArgs(), Param->getNumArgs(),
424 SpecArg->getArgs(), SpecArg->getNumArgs(),
425 Info, Deduced,
426 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000429 // If the argument type is a class template specialization, we
430 // perform template argument deduction using its template
431 // arguments.
432 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
433 if (!RecordArg)
434 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
436 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000437 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
438 if (!SpecArg)
439 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000441 // Perform template argument deduction for the template name.
442 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000443 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000444 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000445 Param->getTemplateName(),
446 TemplateName(SpecArg->getSpecializedTemplate()),
447 Info, Deduced))
448 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Douglas Gregor20a55e22010-12-22 18:17:10 +0000450 // Perform template argument deduction for the template arguments.
451 return DeduceTemplateArguments(S, TemplateParams,
452 Param->getArgs(), Param->getNumArgs(),
453 SpecArg->getTemplateArgs().data(),
454 SpecArg->getTemplateArgs().size(),
455 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000456}
457
John McCallcd05e812010-08-28 22:14:41 +0000458/// \brief Determines whether the given type is an opaque type that
459/// might be more qualified when instantiated.
460static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
461 switch (T->getTypeClass()) {
462 case Type::TypeOfExpr:
463 case Type::TypeOf:
464 case Type::DependentName:
465 case Type::Decltype:
466 case Type::UnresolvedUsing:
467 return true;
468
469 case Type::ConstantArray:
470 case Type::IncompleteArray:
471 case Type::VariableArray:
472 case Type::DependentSizedArray:
473 return IsPossiblyOpaquelyQualifiedType(
474 cast<ArrayType>(T)->getElementType());
475
476 default:
477 return false;
478 }
479}
480
Douglas Gregor603cfb42011-01-05 23:12:31 +0000481/// \brief Retrieve the depth and index of an unexpanded parameter pack.
482static std::pair<unsigned, unsigned>
483getDepthAndIndex(UnexpandedParameterPack UPP) {
484 if (const TemplateTypeParmType *TTP
485 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
486 return std::make_pair(TTP->getDepth(), TTP->getIndex());
487
488 NamedDecl *ND = UPP.first.get<NamedDecl *>();
489 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
490 return std::make_pair(TTP->getDepth(), TTP->getIndex());
491
492 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
493 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
494
495 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
496 return std::make_pair(TTP->getDepth(), TTP->getIndex());
497}
498
499/// \brief Helper function to build a TemplateParameter when we don't
500/// know its type statically.
501static TemplateParameter makeTemplateParameter(Decl *D) {
502 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
503 return TemplateParameter(TTP);
504 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
505 return TemplateParameter(NTTP);
506
507 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
508}
509
510/// \brief Deduce the template arguments by comparing the list of parameter
511/// types to the list of argument types, as in the parameter-type-lists of
512/// function types (C++ [temp.deduct.type]p10).
513///
514/// \param S The semantic analysis object within which we are deducing
515///
516/// \param TemplateParams The template parameters that we are deducing
517///
518/// \param Params The list of parameter types
519///
520/// \param NumParams The number of types in \c Params
521///
522/// \param Args The list of argument types
523///
524/// \param NumArgs The number of types in \c Args
525///
526/// \param Info information about the template argument deduction itself
527///
528/// \param Deduced the deduced template arguments
529///
530/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
531/// how template argument deduction is performed.
532///
533/// \returns the result of template argument deduction so far. Note that a
534/// "success" result means that template argument deduction has not yet failed,
535/// but it may still fail, later, for other reasons.
536static Sema::TemplateDeductionResult
537DeduceTemplateArguments(Sema &S,
538 TemplateParameterList *TemplateParams,
539 const QualType *Params, unsigned NumParams,
540 const QualType *Args, unsigned NumArgs,
541 TemplateDeductionInfo &Info,
542 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
543 unsigned TDF) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000544 // Fast-path check to see if we have too many/too few arguments.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +0000545 // FIXME: Variadic templates broken!
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000546 if (NumParams != NumArgs &&
547 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
548 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
549 return NumArgs < NumParams ? Sema::TDK_TooFewArguments
550 : Sema::TDK_TooManyArguments;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000551
552 // C++0x [temp.deduct.type]p10:
553 // Similarly, if P has a form that contains (T), then each parameter type
554 // Pi of the respective parameter-type- list of P is compared with the
555 // corresponding parameter type Ai of the corresponding parameter-type-list
556 // of A. [...]
557 unsigned ArgIdx = 0, ParamIdx = 0;
558 for (; ParamIdx != NumParams; ++ParamIdx) {
559 // Check argument types.
560 const PackExpansionType *Expansion
561 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
562 if (!Expansion) {
563 // Simple case: compare the parameter and argument types at this point.
564
565 // Make sure we have an argument.
566 if (ArgIdx >= NumArgs)
567 return Sema::TDK_TooFewArguments;
568
569 if (Sema::TemplateDeductionResult Result
570 = DeduceTemplateArguments(S, TemplateParams,
571 Params[ParamIdx],
572 Args[ArgIdx],
573 Info, Deduced, TDF))
574 return Result;
575
576 ++ArgIdx;
577 continue;
578 }
579
580 // C++0x [temp.deduct.type]p10:
581 // If the parameter-declaration corresponding to Pi is a function
582 // parameter pack, then the type of its declarator- id is compared with
583 // each remaining parameter type in the parameter-type-list of A. Each
584 // comparison deduces template arguments for subsequent positions in the
585 // template parameter packs expanded by the function parameter pack.
586
587 // Compute the set of template parameter indices that correspond to
588 // parameter packs expanded by the pack expansion.
589 llvm::SmallVector<unsigned, 2> PackIndices;
590 QualType Pattern = Expansion->getPattern();
591 {
592 llvm::BitVector SawIndices(TemplateParams->size());
593 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
594 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
595 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
596 unsigned Depth, Index;
597 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
598 if (Depth == 0 && !SawIndices[Index]) {
599 SawIndices[Index] = true;
600 PackIndices.push_back(Index);
601 }
602 }
603 }
604 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
605
606 // Save the deduced template arguments for each parameter pack expanded
607 // by this pack expansion, then clear out the deduction.
608 llvm::SmallVector<DeducedTemplateArgument, 2>
609 SavedPacks(PackIndices.size());
610 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
611 SavedPacks[I] = Deduced[PackIndices[I]];
612 Deduced[PackIndices[I]] = DeducedTemplateArgument();
613 }
614
615 // Keep track of the deduced template arguments for each parameter pack
616 // expanded by this pack expansion (the outer index) and for each
617 // template argument (the inner SmallVectors).
618 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
619 NewlyDeducedPacks(PackIndices.size());
620 bool HasAnyArguments = false;
621 for (; ArgIdx < NumArgs; ++ArgIdx) {
622 HasAnyArguments = true;
623
624 // Deduce template arguments from the pattern.
625 if (Sema::TemplateDeductionResult Result
626 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
627 Info, Deduced))
628 return Result;
629
630 // Capture the deduced template arguments for each parameter pack expanded
631 // by this pack expansion, add them to the list of arguments we've deduced
632 // for that pack, then clear out the deduced argument.
633 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
634 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
635 if (!DeducedArg.isNull()) {
636 NewlyDeducedPacks[I].push_back(DeducedArg);
637 DeducedArg = DeducedTemplateArgument();
638 }
639 }
640 }
641
642 // Build argument packs for each of the parameter packs expanded by this
643 // pack expansion.
644 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
645 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
646 // We were not able to deduce anything for this parameter pack,
647 // so just restore the saved argument pack.
648 Deduced[PackIndices[I]] = SavedPacks[I];
649 continue;
650 }
651
652 DeducedTemplateArgument NewPack;
653
654 if (NewlyDeducedPacks[I].empty()) {
655 // If we deduced an empty argument pack, create it now.
656 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
657 } else {
658 TemplateArgument *ArgumentPack
659 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
660 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
661 ArgumentPack);
662 NewPack
663 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
664 NewlyDeducedPacks[I].size()),
665 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
666 }
667
668 DeducedTemplateArgument Result
669 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
670 if (Result.isNull()) {
671 Info.Param
672 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
673 Info.FirstArg = SavedPacks[I];
674 Info.SecondArg = NewPack;
675 return Sema::TDK_Inconsistent;
676 }
677
678 Deduced[PackIndices[I]] = Result;
679 }
680 }
681
682 // Make sure we don't have any extra arguments.
683 if (ArgIdx < NumArgs)
684 return Sema::TDK_TooManyArguments;
685
686 return Sema::TDK_Success;
687}
688
Douglas Gregor500d3312009-06-26 18:27:22 +0000689/// \brief Deduce the template arguments by comparing the parameter type and
690/// the argument type (C++ [temp.deduct.type]).
691///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000692/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000693///
694/// \param TemplateParams the template parameters that we are deducing
695///
696/// \param ParamIn the parameter type
697///
698/// \param ArgIn the argument type
699///
700/// \param Info information about the template argument deduction itself
701///
702/// \param Deduced the deduced template arguments
703///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000704/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000705/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000706///
707/// \returns the result of template argument deduction so far. Note that a
708/// "success" result means that template argument deduction has not yet failed,
709/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000710static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000711DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000712 TemplateParameterList *TemplateParams,
713 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000714 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000715 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000716 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000717 // We only want to look at the canonical types, since typedefs and
718 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000719 QualType Param = S.Context.getCanonicalType(ParamIn);
720 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000721
Douglas Gregor500d3312009-06-26 18:27:22 +0000722 // C++0x [temp.deduct.call]p4 bullet 1:
723 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000724 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000725 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000726 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000727 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000728 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000729 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
730 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000731 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000732 }
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000734 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000735 if (!Param->isDependentType()) {
736 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
737
738 return Sema::TDK_NonDeducedMismatch;
739 }
740
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000741 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000742 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000743
Douglas Gregor199d9912009-06-05 00:53:49 +0000744 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000745 // A template type argument T, a template template argument TT or a
746 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000747 // the following forms:
748 //
749 // T
750 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000751 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000752 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000753 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000754 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000756 // If the argument type is an array type, move the qualifiers up to the
757 // top level, so they can be matched with the qualifiers on the parameter.
758 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000759 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000760 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000761 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000762 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000763 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000764 RecanonicalizeArg = true;
765 }
766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000768 // The argument type can not be less qualified than the parameter
769 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000770 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000771 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000772 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000773 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000774 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000775 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000776
777 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000778 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000779 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000780
781 // local manipulation is okay because it's canonical
782 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000783 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000784 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000786 DeducedTemplateArgument NewDeduced(DeducedType);
787 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
788 Deduced[Index],
789 NewDeduced);
790 if (Result.isNull()) {
791 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
792 Info.FirstArg = Deduced[Index];
793 Info.SecondArg = NewDeduced;
794 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000795 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000796
797 Deduced[Index] = Result;
798 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000799 }
800
Douglas Gregorf67875d2009-06-12 18:26:56 +0000801 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000802 Info.FirstArg = TemplateArgument(ParamIn);
803 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000804
Douglas Gregor508f1c82009-06-26 23:10:12 +0000805 // Check the cv-qualifiers on the parameter and argument types.
806 if (!(TDF & TDF_IgnoreQualifiers)) {
807 if (TDF & TDF_ParamWithReferenceType) {
808 if (Param.isMoreQualifiedThan(Arg))
809 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000810 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000811 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000812 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000813 }
814 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000815
Douglas Gregord560d502009-06-04 00:21:18 +0000816 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000817 // No deduction possible for these types
818 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000819 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Douglas Gregor199d9912009-06-05 00:53:49 +0000821 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000822 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000823 QualType PointeeType;
824 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
825 PointeeType = PointerArg->getPointeeType();
826 } else if (const ObjCObjectPointerType *PointerArg
827 = Arg->getAs<ObjCObjectPointerType>()) {
828 PointeeType = PointerArg->getPointeeType();
829 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000830 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000831 }
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Douglas Gregor41128772009-06-26 23:27:24 +0000833 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000834 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000835 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000836 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000837 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000838 }
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Douglas Gregor199d9912009-06-05 00:53:49 +0000840 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000841 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000842 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000843 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000844 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000846 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000847 cast<LValueReferenceType>(Param)->getPointeeType(),
848 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000849 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000850 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000851
Douglas Gregor199d9912009-06-05 00:53:49 +0000852 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000853 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000854 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000855 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000856 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000858 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000859 cast<RValueReferenceType>(Param)->getPointeeType(),
860 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000861 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000862 }
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Douglas Gregor199d9912009-06-05 00:53:49 +0000864 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000865 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000866 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000867 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000868 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000869 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000870
John McCalle4f26e52010-08-19 00:20:19 +0000871 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000872 return DeduceTemplateArguments(S, TemplateParams,
873 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000874 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000875 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000876 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000877
878 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000879 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000880 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000881 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000882 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000883 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000884
885 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000886 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000887 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000888 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
John McCalle4f26e52010-08-19 00:20:19 +0000890 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000891 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000892 ConstantArrayParm->getElementType(),
893 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000894 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000895 }
896
Douglas Gregor199d9912009-06-05 00:53:49 +0000897 // type [i]
898 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000899 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000900 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000901 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000902
John McCalle4f26e52010-08-19 00:20:19 +0000903 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
904
Douglas Gregor199d9912009-06-05 00:53:49 +0000905 // Check the element type of the arrays
906 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000907 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000908 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000909 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000910 DependentArrayParm->getElementType(),
911 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000912 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000913 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Douglas Gregor199d9912009-06-05 00:53:49 +0000915 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000916 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000917 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
918 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000919 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000920
921 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000922 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000923 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000924 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000925 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000926 = dyn_cast<ConstantArrayType>(ArrayArg)) {
927 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000928 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
929 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000930 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000931 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000932 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000933 if (const DependentSizedArrayType *DependentArrayArg
934 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000935 if (DependentArrayArg->getSizeExpr())
936 return DeduceNonTypeTemplateArgument(S, NTTP,
937 DependentArrayArg->getSizeExpr(),
938 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Douglas Gregor199d9912009-06-05 00:53:49 +0000940 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000941 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
944 // type(*)(T)
945 // T(*)()
946 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000947 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000948 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000949 dyn_cast<FunctionProtoType>(Arg);
950 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000951 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000952
953 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000954 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000955
Mike Stump1eb44332009-09-09 15:08:12 +0000956 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000957 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000958 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000960 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000961 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000962
Anders Carlssona27fad52009-06-08 15:19:08 +0000963 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000964 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000965 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000966 FunctionProtoParam->getResultType(),
967 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000968 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000969 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Douglas Gregor603cfb42011-01-05 23:12:31 +0000971 return DeduceTemplateArguments(S, TemplateParams,
972 FunctionProtoParam->arg_type_begin(),
973 FunctionProtoParam->getNumArgs(),
974 FunctionProtoArg->arg_type_begin(),
975 FunctionProtoArg->getNumArgs(),
976 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +0000977 }
Mike Stump1eb44332009-09-09 15:08:12 +0000978
John McCall3cb0ebd2010-03-10 03:28:59 +0000979 case Type::InjectedClassName: {
980 // Treat a template's injected-class-name as if the template
981 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000982 Param = cast<InjectedClassNameType>(Param)
983 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000984 assert(isa<TemplateSpecializationType>(Param) &&
985 "injected class name is not a template specialization type");
986 // fall through
987 }
988
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000989 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000990 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000991 // TT<T>
992 // TT<i>
993 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000994 case Type::TemplateSpecialization: {
995 const TemplateSpecializationType *SpecParam
996 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000998 // Try to deduce template arguments from the template-id.
999 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001000 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001001 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001003 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001004 // C++ [temp.deduct.call]p3b3:
1005 // If P is a class, and P has the form template-id, then A can be a
1006 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001007 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001008 // class pointed to by the deduced A.
1009 //
1010 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001011 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001012 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001013 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1014 // We cannot inspect base classes as part of deduction when the type
1015 // is incomplete, so either instantiate any templates necessary to
1016 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001017 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001018 return Result;
1019
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001020 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001021 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001022 // ToVisit is our stack of records that we still need to visit.
1023 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1024 llvm::SmallVector<const RecordType *, 8> ToVisit;
1025 ToVisit.push_back(RecordT);
1026 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001027 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1028 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001029 while (!ToVisit.empty()) {
1030 // Retrieve the next class in the inheritance hierarchy.
1031 const RecordType *NextT = ToVisit.back();
1032 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001034 // If we have already seen this type, skip it.
1035 if (!Visited.insert(NextT))
1036 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001038 // If this is a base class, try to perform template argument
1039 // deduction from it.
1040 if (NextT != RecordT) {
1041 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001042 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001043 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001045 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001046 // note that we had some success. Otherwise, ignore any deductions
1047 // from this base class.
1048 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001049 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001050 DeducedOrig = Deduced;
1051 }
1052 else
1053 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001054 }
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001056 // Visit base classes
1057 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1058 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1059 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001060 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001061 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001062 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001063 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001064 }
1065 }
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001067 if (Successful)
1068 return Sema::TDK_Success;
1069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001071 }
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001073 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001074 }
1075
Douglas Gregor637a4092009-06-10 23:47:09 +00001076 // T type::*
1077 // T T::*
1078 // T (type::*)()
1079 // type (T::*)()
1080 // type (type::*)(T)
1081 // type (T::*)(T)
1082 // T (type::*)(T)
1083 // T (T::*)()
1084 // T (T::*)(T)
1085 case Type::MemberPointer: {
1086 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1087 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1088 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001089 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001090
Douglas Gregorf67875d2009-06-12 18:26:56 +00001091 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001092 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001093 MemPtrParam->getPointeeType(),
1094 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001095 Info, Deduced,
1096 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001097 return Result;
1098
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001099 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001100 QualType(MemPtrParam->getClass(), 0),
1101 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001102 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001103 }
1104
Anders Carlsson9a917e42009-06-12 22:56:54 +00001105 // (clang extension)
1106 //
Mike Stump1eb44332009-09-09 15:08:12 +00001107 // type(^)(T)
1108 // T(^)()
1109 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001110 case Type::BlockPointer: {
1111 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1112 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Anders Carlsson859ba502009-06-12 16:23:10 +00001114 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001115 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001117 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001118 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001119 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001120 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001121 }
1122
Douglas Gregor637a4092009-06-10 23:47:09 +00001123 case Type::TypeOfExpr:
1124 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001125 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001126 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001127 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001128
Douglas Gregord560d502009-06-04 00:21:18 +00001129 default:
1130 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001131 }
1132
1133 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001134 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001135}
1136
Douglas Gregorf67875d2009-06-12 18:26:56 +00001137static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001138DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001139 TemplateParameterList *TemplateParams,
1140 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001141 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001142 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001143 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001144 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001145 case TemplateArgument::Null:
1146 assert(false && "Null template argument in parameter list");
1147 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001148
1149 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001150 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001151 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001152 Arg.getAsType(), Info, Deduced, 0);
1153 Info.FirstArg = Param;
1154 Info.SecondArg = Arg;
1155 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001156
Douglas Gregor788cd062009-11-11 01:00:40 +00001157 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001158 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001159 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001160 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001161 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001162 Info.FirstArg = Param;
1163 Info.SecondArg = Arg;
1164 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001165
1166 case TemplateArgument::TemplateExpansion:
1167 llvm_unreachable("caller should handle pack expansions");
1168 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001169
Douglas Gregor199d9912009-06-05 00:53:49 +00001170 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001171 if (Arg.getKind() == TemplateArgument::Declaration &&
1172 Param.getAsDecl()->getCanonicalDecl() ==
1173 Arg.getAsDecl()->getCanonicalDecl())
1174 return Sema::TDK_Success;
1175
Douglas Gregorf67875d2009-06-12 18:26:56 +00001176 Info.FirstArg = Param;
1177 Info.SecondArg = Arg;
1178 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Douglas Gregor199d9912009-06-05 00:53:49 +00001180 case TemplateArgument::Integral:
1181 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001182 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001183 return Sema::TDK_Success;
1184
1185 Info.FirstArg = Param;
1186 Info.SecondArg = Arg;
1187 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001188 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001189
1190 if (Arg.getKind() == TemplateArgument::Expression) {
1191 Info.FirstArg = Param;
1192 Info.SecondArg = Arg;
1193 return Sema::TDK_NonDeducedMismatch;
1194 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001195
Douglas Gregorf67875d2009-06-12 18:26:56 +00001196 Info.FirstArg = Param;
1197 Info.SecondArg = Arg;
1198 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Douglas Gregor199d9912009-06-05 00:53:49 +00001200 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001201 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001202 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1203 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001204 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001205 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001206 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001207 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001208 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001209 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001210 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001211 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001212 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001213 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001214 Info, Deduced);
1215
Douglas Gregorf67875d2009-06-12 18:26:56 +00001216 Info.FirstArg = Param;
1217 Info.SecondArg = Arg;
1218 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Douglas Gregor199d9912009-06-05 00:53:49 +00001221 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001222 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001223 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001224 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001225 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregorf67875d2009-06-12 18:26:56 +00001228 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001229}
1230
Douglas Gregor20a55e22010-12-22 18:17:10 +00001231/// \brief Determine whether there is a template argument to be used for
1232/// deduction.
1233///
1234/// This routine "expands" argument packs in-place, overriding its input
1235/// parameters so that \c Args[ArgIdx] will be the available template argument.
1236///
1237/// \returns true if there is another template argument (which will be at
1238/// \c Args[ArgIdx]), false otherwise.
1239static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1240 unsigned &ArgIdx,
1241 unsigned &NumArgs) {
1242 if (ArgIdx == NumArgs)
1243 return false;
1244
1245 const TemplateArgument &Arg = Args[ArgIdx];
1246 if (Arg.getKind() != TemplateArgument::Pack)
1247 return true;
1248
1249 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1250 Args = Arg.pack_begin();
1251 NumArgs = Arg.pack_size();
1252 ArgIdx = 0;
1253 return ArgIdx < NumArgs;
1254}
1255
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001256/// \brief Determine whether the given set of template arguments has a pack
1257/// expansion that is not the last template argument.
1258static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1259 unsigned NumArgs) {
1260 unsigned ArgIdx = 0;
1261 while (ArgIdx < NumArgs) {
1262 const TemplateArgument &Arg = Args[ArgIdx];
1263
1264 // Unwrap argument packs.
1265 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1266 Args = Arg.pack_begin();
1267 NumArgs = Arg.pack_size();
1268 ArgIdx = 0;
1269 continue;
1270 }
1271
1272 ++ArgIdx;
1273 if (ArgIdx == NumArgs)
1274 return false;
1275
1276 if (Arg.isPackExpansion())
1277 return true;
1278 }
1279
1280 return false;
1281}
1282
Douglas Gregor20a55e22010-12-22 18:17:10 +00001283static Sema::TemplateDeductionResult
1284DeduceTemplateArguments(Sema &S,
1285 TemplateParameterList *TemplateParams,
1286 const TemplateArgument *Params, unsigned NumParams,
1287 const TemplateArgument *Args, unsigned NumArgs,
1288 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001289 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1290 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001291 // C++0x [temp.deduct.type]p9:
1292 // If the template argument list of P contains a pack expansion that is not
1293 // the last template argument, the entire template argument list is a
1294 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001295 if (hasPackExpansionBeforeEnd(Params, NumParams))
1296 return Sema::TDK_Success;
1297
Douglas Gregore02e2622010-12-22 21:19:48 +00001298 // C++0x [temp.deduct.type]p9:
1299 // If P has a form that contains <T> or <i>, then each argument Pi of the
1300 // respective template argument list P is compared with the corresponding
1301 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001302 unsigned ArgIdx = 0, ParamIdx = 0;
1303 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1304 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001305 // FIXME: Variadic templates.
1306 // What do we do if the argument is a pack expansion?
1307
Douglas Gregor20a55e22010-12-22 18:17:10 +00001308 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001309 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001310
1311 // Check whether we have enough arguments.
1312 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001313 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1314 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001315
Douglas Gregore02e2622010-12-22 21:19:48 +00001316 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001317 if (Sema::TemplateDeductionResult Result
1318 = DeduceTemplateArguments(S, TemplateParams,
1319 Params[ParamIdx], Args[ArgIdx],
1320 Info, Deduced))
1321 return Result;
1322
1323 // Move to the next argument.
1324 ++ArgIdx;
1325 continue;
1326 }
1327
Douglas Gregore02e2622010-12-22 21:19:48 +00001328 // The parameter is a pack expansion.
1329
1330 // C++0x [temp.deduct.type]p9:
1331 // If Pi is a pack expansion, then the pattern of Pi is compared with
1332 // each remaining argument in the template argument list of A. Each
1333 // comparison deduces template arguments for subsequent positions in the
1334 // template parameter packs expanded by Pi.
1335 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1336
1337 // Compute the set of template parameter indices that correspond to
1338 // parameter packs expanded by the pack expansion.
1339 llvm::SmallVector<unsigned, 2> PackIndices;
1340 {
1341 llvm::BitVector SawIndices(TemplateParams->size());
1342 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1343 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1344 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1345 unsigned Depth, Index;
1346 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1347 if (Depth == 0 && !SawIndices[Index]) {
1348 SawIndices[Index] = true;
1349 PackIndices.push_back(Index);
1350 }
1351 }
1352 }
1353 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1354
1355 // FIXME: If there are no remaining arguments, we can bail out early
1356 // and set any deduced parameter packs to an empty argument pack.
1357 // The latter part of this is a (minor) correctness issue.
1358
1359 // Save the deduced template arguments for each parameter pack expanded
1360 // by this pack expansion, then clear out the deduction.
1361 llvm::SmallVector<DeducedTemplateArgument, 2>
1362 SavedPacks(PackIndices.size());
1363 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1364 SavedPacks[I] = Deduced[PackIndices[I]];
1365 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1366 }
1367
1368 // Keep track of the deduced template arguments for each parameter pack
1369 // expanded by this pack expansion (the outer index) and for each
1370 // template argument (the inner SmallVectors).
1371 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1372 NewlyDeducedPacks(PackIndices.size());
1373 bool HasAnyArguments = false;
1374 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1375 HasAnyArguments = true;
1376
1377 // Deduce template arguments from the pattern.
1378 if (Sema::TemplateDeductionResult Result
1379 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1380 Info, Deduced))
1381 return Result;
1382
1383 // Capture the deduced template arguments for each parameter pack expanded
1384 // by this pack expansion, add them to the list of arguments we've deduced
1385 // for that pack, then clear out the deduced argument.
1386 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1387 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1388 if (!DeducedArg.isNull()) {
1389 NewlyDeducedPacks[I].push_back(DeducedArg);
1390 DeducedArg = DeducedTemplateArgument();
1391 }
1392 }
1393
1394 ++ArgIdx;
1395 }
1396
1397 // Build argument packs for each of the parameter packs expanded by this
1398 // pack expansion.
1399 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1400 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1401 // We were not able to deduce anything for this parameter pack,
1402 // so just restore the saved argument pack.
1403 Deduced[PackIndices[I]] = SavedPacks[I];
1404 continue;
1405 }
1406
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001407 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001408
1409 if (NewlyDeducedPacks[I].empty()) {
1410 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001411 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1412 } else {
1413 TemplateArgument *ArgumentPack
1414 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1415 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1416 ArgumentPack);
1417 NewPack
1418 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001419 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001420 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1421 }
1422
1423 DeducedTemplateArgument Result
1424 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1425 if (Result.isNull()) {
1426 Info.Param
1427 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1428 Info.FirstArg = SavedPacks[I];
1429 Info.SecondArg = NewPack;
1430 return Sema::TDK_Inconsistent;
1431 }
1432
1433 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001434 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001435 }
1436
1437 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001438 if (NumberOfArgumentsMustMatch &&
1439 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001440 return Sema::TDK_TooManyArguments;
1441
1442 return Sema::TDK_Success;
1443}
1444
Mike Stump1eb44332009-09-09 15:08:12 +00001445static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001446DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001447 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001448 const TemplateArgumentList &ParamList,
1449 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001450 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001451 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001452 return DeduceTemplateArguments(S, TemplateParams,
1453 ParamList.data(), ParamList.size(),
1454 ArgList.data(), ArgList.size(),
1455 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001456}
1457
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001458/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001459static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001460 const TemplateArgument &X,
1461 const TemplateArgument &Y) {
1462 if (X.getKind() != Y.getKind())
1463 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001465 switch (X.getKind()) {
1466 case TemplateArgument::Null:
1467 assert(false && "Comparing NULL template argument");
1468 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001470 case TemplateArgument::Type:
1471 return Context.getCanonicalType(X.getAsType()) ==
1472 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001474 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001475 return X.getAsDecl()->getCanonicalDecl() ==
1476 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Douglas Gregor788cd062009-11-11 01:00:40 +00001478 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001479 case TemplateArgument::TemplateExpansion:
1480 return Context.getCanonicalTemplateName(
1481 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1482 Context.getCanonicalTemplateName(
1483 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001484
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001485 case TemplateArgument::Integral:
1486 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Douglas Gregor788cd062009-11-11 01:00:40 +00001488 case TemplateArgument::Expression: {
1489 llvm::FoldingSetNodeID XID, YID;
1490 X.getAsExpr()->Profile(XID, Context, true);
1491 Y.getAsExpr()->Profile(YID, Context, true);
1492 return XID == YID;
1493 }
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001495 case TemplateArgument::Pack:
1496 if (X.pack_size() != Y.pack_size())
1497 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001498
1499 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1500 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001501 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001502 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001503 if (!isSameTemplateArg(Context, *XP, *YP))
1504 return false;
1505
1506 return true;
1507 }
1508
1509 return false;
1510}
1511
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001512/// \brief Allocate a TemplateArgumentLoc where all locations have
1513/// been initialized to the given location.
1514///
1515/// \param S The semantic analysis object.
1516///
1517/// \param The template argument we are producing template argument
1518/// location information for.
1519///
1520/// \param NTTPType For a declaration template argument, the type of
1521/// the non-type template parameter that corresponds to this template
1522/// argument.
1523///
1524/// \param Loc The source location to use for the resulting template
1525/// argument.
1526static TemplateArgumentLoc
1527getTrivialTemplateArgumentLoc(Sema &S,
1528 const TemplateArgument &Arg,
1529 QualType NTTPType,
1530 SourceLocation Loc) {
1531 switch (Arg.getKind()) {
1532 case TemplateArgument::Null:
1533 llvm_unreachable("Can't get a NULL template argument here");
1534 break;
1535
1536 case TemplateArgument::Type:
1537 return TemplateArgumentLoc(Arg,
1538 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1539
1540 case TemplateArgument::Declaration: {
1541 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001542 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001543 .takeAs<Expr>();
1544 return TemplateArgumentLoc(TemplateArgument(E), E);
1545 }
1546
1547 case TemplateArgument::Integral: {
1548 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001549 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001550 return TemplateArgumentLoc(TemplateArgument(E), E);
1551 }
1552
1553 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001554 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1555
1556 case TemplateArgument::TemplateExpansion:
1557 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1558
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001559 case TemplateArgument::Expression:
1560 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1561
1562 case TemplateArgument::Pack:
1563 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1564 }
1565
1566 return TemplateArgumentLoc();
1567}
1568
1569
1570/// \brief Convert the given deduced template argument and add it to the set of
1571/// fully-converted template arguments.
1572static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1573 DeducedTemplateArgument Arg,
1574 NamedDecl *Template,
1575 QualType NTTPType,
1576 TemplateDeductionInfo &Info,
1577 bool InFunctionTemplate,
1578 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1579 if (Arg.getKind() == TemplateArgument::Pack) {
1580 // This is a template argument pack, so check each of its arguments against
1581 // the template parameter.
1582 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1583 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001584 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001585 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001586 // When converting the deduced template argument, append it to the
1587 // general output list. We need to do this so that the template argument
1588 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001589 DeducedTemplateArgument InnerArg(*PA);
1590 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1591 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1592 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001593 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001594 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001595
1596 // Move the converted template argument into our argument pack.
1597 PackedArgsBuilder.push_back(Output.back());
1598 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001599 }
1600
1601 // Create the resulting argument pack.
1602 TemplateArgument *PackedArgs = 0;
1603 if (!PackedArgsBuilder.empty()) {
1604 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1605 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1606 }
1607 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1608 return false;
1609 }
1610
1611 // Convert the deduced template argument into a template
1612 // argument that we can check, almost as if the user had written
1613 // the template argument explicitly.
1614 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1615 Info.getLocation());
1616
1617 // Check the template argument, converting it as necessary.
1618 return S.CheckTemplateArgument(Param, ArgLoc,
1619 Template,
1620 Template->getLocation(),
1621 Template->getSourceRange().getEnd(),
1622 Output,
1623 InFunctionTemplate
1624 ? (Arg.wasDeducedFromArrayBound()
1625 ? Sema::CTAK_DeducedFromArrayBound
1626 : Sema::CTAK_Deduced)
1627 : Sema::CTAK_Specified);
1628}
1629
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001630/// Complete template argument deduction for a class template partial
1631/// specialization.
1632static Sema::TemplateDeductionResult
1633FinishTemplateArgumentDeduction(Sema &S,
1634 ClassTemplatePartialSpecializationDecl *Partial,
1635 const TemplateArgumentList &TemplateArgs,
1636 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001637 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001638 // Trap errors.
1639 Sema::SFINAETrap Trap(S);
1640
1641 Sema::ContextRAII SavedContext(S, Partial);
1642
1643 // C++ [temp.deduct.type]p2:
1644 // [...] or if any template argument remains neither deduced nor
1645 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001646 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001647 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1648 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001649 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001650 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001651 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001652 return Sema::TDK_Incomplete;
1653 }
1654
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001655 // We have deduced this argument, so it still needs to be
1656 // checked and converted.
1657
1658 // First, for a non-type template parameter type that is
1659 // initialized by a declaration, we need the type of the
1660 // corresponding non-type template parameter.
1661 QualType NTTPType;
1662 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001663 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001664 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001665 if (NTTPType->isDependentType()) {
1666 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1667 Builder.data(), Builder.size());
1668 NTTPType = S.SubstType(NTTPType,
1669 MultiLevelTemplateArgumentList(TemplateArgs),
1670 NTTP->getLocation(),
1671 NTTP->getDeclName());
1672 if (NTTPType.isNull()) {
1673 Info.Param = makeTemplateParameter(Param);
1674 // FIXME: These template arguments are temporary. Free them!
1675 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1676 Builder.data(),
1677 Builder.size()));
1678 return Sema::TDK_SubstitutionFailure;
1679 }
1680 }
1681 }
1682
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001683 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1684 Partial, NTTPType, Info, false,
1685 Builder)) {
1686 Info.Param = makeTemplateParameter(Param);
1687 // FIXME: These template arguments are temporary. Free them!
1688 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1689 Builder.size()));
1690 return Sema::TDK_SubstitutionFailure;
1691 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001692 }
1693
1694 // Form the template argument list from the deduced template arguments.
1695 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001696 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1697 Builder.size());
1698
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001699 Info.reset(DeducedArgumentList);
1700
1701 // Substitute the deduced template arguments into the template
1702 // arguments of the class template partial specialization, and
1703 // verify that the instantiated template arguments are both valid
1704 // and are equivalent to the template arguments originally provided
1705 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001706 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001707 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1708 const TemplateArgumentLoc *PartialTemplateArgs
1709 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001710
1711 // Note that we don't provide the langle and rangle locations.
1712 TemplateArgumentListInfo InstArgs;
1713
Douglas Gregore02e2622010-12-22 21:19:48 +00001714 if (S.Subst(PartialTemplateArgs,
1715 Partial->getNumTemplateArgsAsWritten(),
1716 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1717 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1718 if (ParamIdx >= Partial->getTemplateParameters()->size())
1719 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1720
1721 Decl *Param
1722 = const_cast<NamedDecl *>(
1723 Partial->getTemplateParameters()->getParam(ParamIdx));
1724 Info.Param = makeTemplateParameter(Param);
1725 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1726 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001727 }
1728
Douglas Gregor910f8002010-11-07 23:05:16 +00001729 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001730 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001731 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001732 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001733
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001734 TemplateParameterList *TemplateParams
1735 = ClassTemplate->getTemplateParameters();
1736 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001737 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001738 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001739 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001740 Info.FirstArg = TemplateArgs[I];
1741 Info.SecondArg = InstArg;
1742 return Sema::TDK_NonDeducedMismatch;
1743 }
1744 }
1745
1746 if (Trap.hasErrorOccurred())
1747 return Sema::TDK_SubstitutionFailure;
1748
1749 return Sema::TDK_Success;
1750}
1751
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001752/// \brief Perform template argument deduction to determine whether
1753/// the given template arguments match the given class template
1754/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001755Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001756Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001757 const TemplateArgumentList &TemplateArgs,
1758 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001759 // C++ [temp.class.spec.match]p2:
1760 // A partial specialization matches a given actual template
1761 // argument list if the template arguments of the partial
1762 // specialization can be deduced from the actual template argument
1763 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001764 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001765 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001766 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001767 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001768 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001769 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001770 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001771 TemplateArgs, Info, Deduced))
1772 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001773
Douglas Gregor637a4092009-06-10 23:47:09 +00001774 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001775 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001776 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001777 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001778
Douglas Gregorbb260412009-06-14 08:02:22 +00001779 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001780 return Sema::TDK_SubstitutionFailure;
1781
1782 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1783 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001784}
Douglas Gregor031a5882009-06-13 00:26:55 +00001785
Douglas Gregor41128772009-06-26 23:27:24 +00001786/// \brief Determine whether the given type T is a simple-template-id type.
1787static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001788 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001789 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001790 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Douglas Gregor41128772009-06-26 23:27:24 +00001792 return false;
1793}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001794
1795/// \brief Substitute the explicitly-provided template arguments into the
1796/// given function template according to C++ [temp.arg.explicit].
1797///
1798/// \param FunctionTemplate the function template into which the explicit
1799/// template arguments will be substituted.
1800///
Mike Stump1eb44332009-09-09 15:08:12 +00001801/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001802/// arguments.
1803///
Mike Stump1eb44332009-09-09 15:08:12 +00001804/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001805/// with the converted and checked explicit template arguments.
1806///
Mike Stump1eb44332009-09-09 15:08:12 +00001807/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001808/// parameters.
1809///
1810/// \param FunctionType if non-NULL, the result type of the function template
1811/// will also be instantiated and the pointed-to value will be updated with
1812/// the instantiated function type.
1813///
1814/// \param Info if substitution fails for any reason, this object will be
1815/// populated with more information about the failure.
1816///
1817/// \returns TDK_Success if substitution was successful, or some failure
1818/// condition.
1819Sema::TemplateDeductionResult
1820Sema::SubstituteExplicitTemplateArguments(
1821 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001822 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001823 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001824 llvm::SmallVectorImpl<QualType> &ParamTypes,
1825 QualType *FunctionType,
1826 TemplateDeductionInfo &Info) {
1827 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1828 TemplateParameterList *TemplateParams
1829 = FunctionTemplate->getTemplateParameters();
1830
John McCalld5532b62009-11-23 01:53:49 +00001831 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001832 // No arguments to substitute; just copy over the parameter types and
1833 // fill in the function type.
1834 for (FunctionDecl::param_iterator P = Function->param_begin(),
1835 PEnd = Function->param_end();
1836 P != PEnd;
1837 ++P)
1838 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Douglas Gregor83314aa2009-07-08 20:55:45 +00001840 if (FunctionType)
1841 *FunctionType = Function->getType();
1842 return TDK_Success;
1843 }
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Douglas Gregor83314aa2009-07-08 20:55:45 +00001845 // Substitution of the explicit template arguments into a function template
1846 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001847 SFINAETrap Trap(*this);
1848
Douglas Gregor83314aa2009-07-08 20:55:45 +00001849 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001850 // Template arguments that are present shall be specified in the
1851 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001852 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001853 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001854 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001855
1856 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001857 // explicitly-specified template arguments against this function template,
1858 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001859 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001860 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001861 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1862 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001863 if (Inst)
1864 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Douglas Gregor83314aa2009-07-08 20:55:45 +00001866 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001867 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001868 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001869 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001870 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001871 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001872 if (Index >= TemplateParams->size())
1873 Index = TemplateParams->size() - 1;
1874 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001875 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001876 }
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Douglas Gregor83314aa2009-07-08 20:55:45 +00001878 // Form the template argument list from the explicitly-specified
1879 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001880 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001881 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001882 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001883
John McCalldf41f182010-10-12 19:40:14 +00001884 // Template argument deduction and the final substitution should be
1885 // done in the context of the templated declaration. Explicit
1886 // argument substitution, on the other hand, needs to happen in the
1887 // calling context.
1888 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1889
Douglas Gregor83314aa2009-07-08 20:55:45 +00001890 // Instantiate the types of each of the function parameters given the
1891 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00001892 if (SubstParmTypes(Function->getLocation(),
1893 Function->param_begin(), Function->getNumParams(),
1894 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1895 ParamTypes))
1896 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001897
1898 // If the caller wants a full function type back, instantiate the return
1899 // type and form that function type.
1900 if (FunctionType) {
1901 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001902 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001903 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001904 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001905
1906 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001907 = SubstType(Proto->getResultType(),
1908 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1909 Function->getTypeSpecStartLoc(),
1910 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001911 if (ResultType.isNull() || Trap.hasErrorOccurred())
1912 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001913
1914 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001915 ParamTypes.data(), ParamTypes.size(),
1916 Proto->isVariadic(),
1917 Proto->getTypeQuals(),
1918 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001919 Function->getDeclName(),
1920 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001921 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1922 return TDK_SubstitutionFailure;
1923 }
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Douglas Gregor83314aa2009-07-08 20:55:45 +00001925 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001926 // Trailing template arguments that can be deduced (14.8.2) may be
1927 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001928 // template arguments can be deduced, they may all be omitted; in this
1929 // case, the empty template argument list <> itself may also be omitted.
1930 //
1931 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001932 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001933 Deduced.reserve(TemplateParams->size());
1934 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001935 Deduced.push_back(ExplicitArgumentList->get(I));
1936
Douglas Gregor83314aa2009-07-08 20:55:45 +00001937 return TDK_Success;
1938}
1939
Mike Stump1eb44332009-09-09 15:08:12 +00001940/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001941/// checking the deduced template arguments for completeness and forming
1942/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001943Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001944Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001945 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1946 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001947 FunctionDecl *&Specialization,
1948 TemplateDeductionInfo &Info) {
1949 TemplateParameterList *TemplateParams
1950 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Douglas Gregor83314aa2009-07-08 20:55:45 +00001952 // Template argument deduction for function templates in a SFINAE context.
1953 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001954 SFINAETrap Trap(*this);
1955
Douglas Gregor83314aa2009-07-08 20:55:45 +00001956 // Enter a new template instantiation context while we instantiate the
1957 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001958 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001959 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001960 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1961 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001962 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001963 return TDK_InstantiationDepth;
1964
John McCall96db3102010-04-29 01:18:58 +00001965 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001966
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001967 // C++ [temp.deduct.type]p2:
1968 // [...] or if any template argument remains neither deduced nor
1969 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001970 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001971 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
1972 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001973
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001974 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001975 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001976 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001977 // argument, because it was explicitly-specified. Just record the
1978 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001979 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001980 continue;
1981 }
1982
1983 // We have deduced this argument, so it still needs to be
1984 // checked and converted.
1985
1986 // First, for a non-type template parameter type that is
1987 // initialized by a declaration, we need the type of the
1988 // corresponding non-type template parameter.
1989 QualType NTTPType;
1990 if (NonTypeTemplateParmDecl *NTTP
1991 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001992 NTTPType = NTTP->getType();
1993 if (NTTPType->isDependentType()) {
1994 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1995 Builder.data(), Builder.size());
1996 NTTPType = SubstType(NTTPType,
1997 MultiLevelTemplateArgumentList(TemplateArgs),
1998 NTTP->getLocation(),
1999 NTTP->getDeclName());
2000 if (NTTPType.isNull()) {
2001 Info.Param = makeTemplateParameter(Param);
2002 // FIXME: These template arguments are temporary. Free them!
2003 Info.reset(TemplateArgumentList::CreateCopy(Context,
2004 Builder.data(),
2005 Builder.size()));
2006 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002007 }
2008 }
2009 }
2010
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002011 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2012 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002013 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002014 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002015 // FIXME: These template arguments are temporary. Free them!
2016 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002017 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002018 return TDK_SubstitutionFailure;
2019 }
2020
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002021 continue;
2022 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002023
2024 // C++0x [temp.arg.explicit]p3:
2025 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2026 // be deduced to an empty sequence of template arguments.
2027 // FIXME: Where did the word "trailing" come from?
2028 if (Param->isTemplateParameterPack()) {
2029 Builder.push_back(TemplateArgument(0, 0));
2030 continue;
2031 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002032
2033 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002034 TemplateArgumentLoc DefArg
2035 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2036 FunctionTemplate->getLocation(),
2037 FunctionTemplate->getSourceRange().getEnd(),
2038 Param,
2039 Builder);
2040
2041 // If there was no default argument, deduction is incomplete.
2042 if (DefArg.getArgument().isNull()) {
2043 Info.Param = makeTemplateParameter(
2044 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2045 return TDK_Incomplete;
2046 }
2047
2048 // Check whether we can actually use the default argument.
2049 if (CheckTemplateArgument(Param, DefArg,
2050 FunctionTemplate,
2051 FunctionTemplate->getLocation(),
2052 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002053 Builder,
2054 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002055 Info.Param = makeTemplateParameter(
2056 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002057 // FIXME: These template arguments are temporary. Free them!
2058 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2059 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002060 return TDK_SubstitutionFailure;
2061 }
2062
2063 // If we get here, we successfully used the default template argument.
2064 }
2065
2066 // Form the template argument list from the deduced template arguments.
2067 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002068 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002069 Info.reset(DeducedArgumentList);
2070
Mike Stump1eb44332009-09-09 15:08:12 +00002071 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002072 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002073 DeclContext *Owner = FunctionTemplate->getDeclContext();
2074 if (FunctionTemplate->getFriendObjectKind())
2075 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002076 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002077 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002078 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002079 if (!Specialization)
2080 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Douglas Gregorf8825742009-09-15 18:26:13 +00002082 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2083 FunctionTemplate->getCanonicalDecl());
2084
Mike Stump1eb44332009-09-09 15:08:12 +00002085 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002086 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002087 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2088 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002089 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Douglas Gregor83314aa2009-07-08 20:55:45 +00002091 // There may have been an error that did not prevent us from constructing a
2092 // declaration. Mark the declaration invalid and return with a substitution
2093 // failure.
2094 if (Trap.hasErrorOccurred()) {
2095 Specialization->setInvalidDecl(true);
2096 return TDK_SubstitutionFailure;
2097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Douglas Gregor9b623632010-10-12 23:32:35 +00002099 // If we suppressed any diagnostics while performing template argument
2100 // deduction, and if we haven't already instantiated this declaration,
2101 // keep track of these diagnostics. They'll be emitted if this specialization
2102 // is actually used.
2103 if (Info.diag_begin() != Info.diag_end()) {
2104 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2105 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2106 if (Pos == SuppressedDiagnostics.end())
2107 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2108 .append(Info.diag_begin(), Info.diag_end());
2109 }
2110
Mike Stump1eb44332009-09-09 15:08:12 +00002111 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002112}
2113
John McCall9c72c602010-08-27 09:08:28 +00002114/// Gets the type of a function for template-argument-deducton
2115/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002116static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002117 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002118 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002119 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002120 if (Method->isInstance()) {
2121 // An instance method that's referenced in a form that doesn't
2122 // look like a member pointer is just invalid.
2123 if (!R.HasFormOfMemberPointer) return QualType();
2124
John McCalleff92132010-02-02 02:21:27 +00002125 return Context.getMemberPointerType(Fn->getType(),
2126 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002127 }
2128
2129 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002130 return Context.getPointerType(Fn->getType());
2131}
2132
2133/// Apply the deduction rules for overload sets.
2134///
2135/// \return the null type if this argument should be treated as an
2136/// undeduced context
2137static QualType
2138ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002139 Expr *Arg, QualType ParamType,
2140 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002141
2142 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002143
John McCall9c72c602010-08-27 09:08:28 +00002144 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002145
Douglas Gregor75f21af2010-08-30 21:04:23 +00002146 // C++0x [temp.deduct.call]p4
2147 unsigned TDF = 0;
2148 if (ParamWasReference)
2149 TDF |= TDF_ParamWithReferenceType;
2150 if (R.IsAddressOfOperand)
2151 TDF |= TDF_IgnoreQualifiers;
2152
John McCalleff92132010-02-02 02:21:27 +00002153 // If there were explicit template arguments, we can only find
2154 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2155 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002156 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002157 // But we can still look for an explicit specialization.
2158 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002159 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002160 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002161 return QualType();
2162 }
2163
2164 // C++0x [temp.deduct.call]p6:
2165 // When P is a function type, pointer to function type, or pointer
2166 // to member function type:
2167
2168 if (!ParamType->isFunctionType() &&
2169 !ParamType->isFunctionPointerType() &&
2170 !ParamType->isMemberFunctionPointerType())
2171 return QualType();
2172
2173 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002174 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2175 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002176 NamedDecl *D = (*I)->getUnderlyingDecl();
2177
2178 // - If the argument is an overload set containing one or more
2179 // function templates, the parameter is treated as a
2180 // non-deduced context.
2181 if (isa<FunctionTemplateDecl>(D))
2182 return QualType();
2183
2184 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002185 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2186 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002187
Douglas Gregor75f21af2010-08-30 21:04:23 +00002188 // Function-to-pointer conversion.
2189 if (!ParamWasReference && ParamType->isPointerType() &&
2190 ArgType->isFunctionType())
2191 ArgType = S.Context.getPointerType(ArgType);
2192
John McCalleff92132010-02-02 02:21:27 +00002193 // - If the argument is an overload set (not containing function
2194 // templates), trial argument deduction is attempted using each
2195 // of the members of the set. If deduction succeeds for only one
2196 // of the overload set members, that member is used as the
2197 // argument value for the deduction. If deduction succeeds for
2198 // more than one member of the overload set the parameter is
2199 // treated as a non-deduced context.
2200
2201 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2202 // Type deduction is done independently for each P/A pair, and
2203 // the deduced template argument values are then combined.
2204 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002205 llvm::SmallVector<DeducedTemplateArgument, 8>
2206 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002207 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002208 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002209 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002210 ParamType, ArgType,
2211 Info, Deduced, TDF);
2212 if (Result) continue;
2213 if (!Match.isNull()) return QualType();
2214 Match = ArgType;
2215 }
2216
2217 return Match;
2218}
2219
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002220/// \brief Perform the adjustments to the parameter and argument types
2221/// described in C++ [temp.deduct.call].
2222///
2223/// \returns true if the caller should not attempt to perform any template
2224/// argument deduction based on this P/A pair.
2225static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2226 TemplateParameterList *TemplateParams,
2227 QualType &ParamType,
2228 QualType &ArgType,
2229 Expr *Arg,
2230 unsigned &TDF) {
2231 // C++0x [temp.deduct.call]p3:
2232 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2233 // are ignored for type deduction.
2234 if (ParamType.getCVRQualifiers())
2235 ParamType = ParamType.getLocalUnqualifiedType();
2236 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2237 if (ParamRefType) {
2238 // [...] If P is a reference type, the type referred to by P is used
2239 // for type deduction.
2240 ParamType = ParamRefType->getPointeeType();
2241 }
2242
2243 // Overload sets usually make this parameter an undeduced
2244 // context, but there are sometimes special circumstances.
2245 if (ArgType == S.Context.OverloadTy) {
2246 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2247 Arg, ParamType,
2248 ParamRefType != 0);
2249 if (ArgType.isNull())
2250 return true;
2251 }
2252
2253 if (ParamRefType) {
2254 // C++0x [temp.deduct.call]p3:
2255 // [...] If P is of the form T&&, where T is a template parameter, and
2256 // the argument is an lvalue, the type A& is used in place of A for
2257 // type deduction.
2258 if (ParamRefType->isRValueReferenceType() &&
2259 ParamRefType->getAs<TemplateTypeParmType>() &&
2260 Arg->isLValue())
2261 ArgType = S.Context.getLValueReferenceType(ArgType);
2262 } else {
2263 // C++ [temp.deduct.call]p2:
2264 // If P is not a reference type:
2265 // - If A is an array type, the pointer type produced by the
2266 // array-to-pointer standard conversion (4.2) is used in place of
2267 // A for type deduction; otherwise,
2268 if (ArgType->isArrayType())
2269 ArgType = S.Context.getArrayDecayedType(ArgType);
2270 // - If A is a function type, the pointer type produced by the
2271 // function-to-pointer standard conversion (4.3) is used in place
2272 // of A for type deduction; otherwise,
2273 else if (ArgType->isFunctionType())
2274 ArgType = S.Context.getPointerType(ArgType);
2275 else {
2276 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2277 // type are ignored for type deduction.
2278 QualType CanonArgType = S.Context.getCanonicalType(ArgType);
2279 if (ArgType.getCVRQualifiers())
2280 ArgType = ArgType.getUnqualifiedType();
2281 }
2282 }
2283
2284 // C++0x [temp.deduct.call]p4:
2285 // In general, the deduction process attempts to find template argument
2286 // values that will make the deduced A identical to A (after the type A
2287 // is transformed as described above). [...]
2288 TDF = TDF_SkipNonDependent;
2289
2290 // - If the original P is a reference type, the deduced A (i.e., the
2291 // type referred to by the reference) can be more cv-qualified than
2292 // the transformed A.
2293 if (ParamRefType)
2294 TDF |= TDF_ParamWithReferenceType;
2295 // - The transformed A can be another pointer or pointer to member
2296 // type that can be converted to the deduced A via a qualification
2297 // conversion (4.4).
2298 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2299 ArgType->isObjCObjectPointerType())
2300 TDF |= TDF_IgnoreQualifiers;
2301 // - If P is a class and P has the form simple-template-id, then the
2302 // transformed A can be a derived class of the deduced A. Likewise,
2303 // if P is a pointer to a class of the form simple-template-id, the
2304 // transformed A can be a pointer to a derived class pointed to by
2305 // the deduced A.
2306 if (isSimpleTemplateIdType(ParamType) ||
2307 (isa<PointerType>(ParamType) &&
2308 isSimpleTemplateIdType(
2309 ParamType->getAs<PointerType>()->getPointeeType())))
2310 TDF |= TDF_DerivedClass;
2311
2312 return false;
2313}
2314
Douglas Gregore53060f2009-06-25 22:08:12 +00002315/// \brief Perform template argument deduction from a function call
2316/// (C++ [temp.deduct.call]).
2317///
2318/// \param FunctionTemplate the function template for which we are performing
2319/// template argument deduction.
2320///
Douglas Gregor48026d22010-01-11 18:40:55 +00002321/// \param ExplicitTemplateArguments the explicit template arguments provided
2322/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002323///
Douglas Gregore53060f2009-06-25 22:08:12 +00002324/// \param Args the function call arguments
2325///
2326/// \param NumArgs the number of arguments in Args
2327///
Douglas Gregor48026d22010-01-11 18:40:55 +00002328/// \param Name the name of the function being called. This is only significant
2329/// when the function template is a conversion function template, in which
2330/// case this routine will also perform template argument deduction based on
2331/// the function to which
2332///
Douglas Gregore53060f2009-06-25 22:08:12 +00002333/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002334/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002335/// template argument deduction.
2336///
2337/// \param Info the argument will be updated to provide additional information
2338/// about template argument deduction.
2339///
2340/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002341Sema::TemplateDeductionResult
2342Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002343 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002344 Expr **Args, unsigned NumArgs,
2345 FunctionDecl *&Specialization,
2346 TemplateDeductionInfo &Info) {
2347 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002348
Douglas Gregore53060f2009-06-25 22:08:12 +00002349 // C++ [temp.deduct.call]p1:
2350 // Template argument deduction is done by comparing each function template
2351 // parameter type (call it P) with the type of the corresponding argument
2352 // of the call (call it A) as described below.
2353 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002354 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002355 return TDK_TooFewArguments;
2356 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002357 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002358 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002359 if (Proto->isTemplateVariadic())
2360 /* Do nothing */;
2361 else if (Proto->isVariadic())
2362 CheckArgs = Function->getNumParams();
2363 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002364 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002365 }
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002367 // The types of the parameters from which we will perform template argument
2368 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002369 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002370 TemplateParameterList *TemplateParams
2371 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002372 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002373 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002374 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002375 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002376 TemplateDeductionResult Result =
2377 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002378 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002379 Deduced,
2380 ParamTypes,
2381 0,
2382 Info);
2383 if (Result)
2384 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002385
2386 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002387 } else {
2388 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002389 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002390 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2391 }
Mike Stump1eb44332009-09-09 15:08:12 +00002392
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002393 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002394 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002395 unsigned ArgIdx = 0;
2396 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2397 ParamIdx != NumParams; ++ParamIdx) {
2398 QualType ParamType = ParamTypes[ParamIdx];
2399
2400 const PackExpansionType *ParamExpansion
2401 = dyn_cast<PackExpansionType>(ParamType);
2402 if (!ParamExpansion) {
2403 // Simple case: matching a function parameter to a function argument.
2404 if (ArgIdx >= CheckArgs)
2405 break;
2406
2407 Expr *Arg = Args[ArgIdx++];
2408 QualType ArgType = Arg->getType();
2409 unsigned TDF = 0;
2410 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2411 ParamType, ArgType, Arg,
2412 TDF))
2413 continue;
2414
2415 if (TemplateDeductionResult Result
2416 = ::DeduceTemplateArguments(*this, TemplateParams,
2417 ParamType, ArgType, Info, Deduced,
2418 TDF))
2419 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002420
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002421 // FIXME: we need to check that the deduced A is the same as A,
2422 // modulo the various allowed differences.
2423 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002424 }
2425
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002426 // C++0x [temp.deduct.call]p1:
2427 // For a function parameter pack that occurs at the end of the
2428 // parameter-declaration-list, the type A of each remaining argument of
2429 // the call is compared with the type P of the declarator-id of the
2430 // function parameter pack. Each comparison deduces template arguments
2431 // for subsequent positions in the template parameter packs expanded by
2432 // the function parameter pack.
2433 QualType ParamPattern = ParamExpansion->getPattern();
2434 llvm::SmallVector<unsigned, 2> PackIndices;
2435 {
2436 llvm::BitVector SawIndices(TemplateParams->size());
2437 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2438 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2439 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2440 unsigned Depth, Index;
2441 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2442 if (Depth == 0 && !SawIndices[Index]) {
2443 SawIndices[Index] = true;
2444 PackIndices.push_back(Index);
2445 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002446 }
2447 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002448 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2449
2450 // Save the deduced template arguments for each parameter pack expanded
2451 // by this pack expansion, then clear out the deduction.
2452 llvm::SmallVector<DeducedTemplateArgument, 2>
2453 SavedPacks(PackIndices.size());
2454 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2455 SavedPacks[I] = Deduced[PackIndices[I]];
2456 Deduced[PackIndices[I]] = DeducedTemplateArgument();
2457 }
2458
2459 // Keep track of the deduced template arguments for each parameter pack
2460 // expanded by this pack expansion (the outer index) and for each
2461 // template argument (the inner SmallVectors).
2462 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
2463 NewlyDeducedPacks(PackIndices.size());
2464 bool HasAnyArguments = false;
2465 for (; ArgIdx < NumArgs; ++ArgIdx) {
2466 HasAnyArguments = true;
2467
2468 ParamType = ParamPattern;
2469 Expr *Arg = Args[ArgIdx];
2470 QualType ArgType = Arg->getType();
2471 unsigned TDF = 0;
2472 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2473 ParamType, ArgType, Arg,
2474 TDF)) {
2475 // We can't actually perform any deduction for this argument, so stop
2476 // deduction at this point.
2477 ++ArgIdx;
2478 break;
2479 }
2480
2481 if (TemplateDeductionResult Result
2482 = ::DeduceTemplateArguments(*this, TemplateParams,
2483 ParamType, ArgType, Info, Deduced,
2484 TDF))
2485 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002486
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002487 // Capture the deduced template arguments for each parameter pack expanded
2488 // by this pack expansion, add them to the list of arguments we've deduced
2489 // for that pack, then clear out the deduced argument.
2490 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2491 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2492 if (!DeducedArg.isNull()) {
2493 NewlyDeducedPacks[I].push_back(DeducedArg);
2494 DeducedArg = DeducedTemplateArgument();
2495 }
2496 }
2497 }
2498
2499 // Build argument packs for each of the parameter packs expanded by this
2500 // pack expansion.
2501 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2502 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
2503 // We were not able to deduce anything for this parameter pack,
2504 // so just restore the saved argument pack.
2505 Deduced[PackIndices[I]] = SavedPacks[I];
2506 continue;
2507 }
2508
2509 DeducedTemplateArgument NewPack;
2510
2511 if (NewlyDeducedPacks[I].empty()) {
2512 // If we deduced an empty argument pack, create it now.
2513 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
2514 } else {
2515 TemplateArgument *ArgumentPack
2516 = new (Context) TemplateArgument [NewlyDeducedPacks[I].size()];
2517 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
2518 ArgumentPack);
2519 NewPack
2520 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
2521 NewlyDeducedPacks[I].size()),
2522 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
2523 }
2524
2525 DeducedTemplateArgument Result
2526 = checkDeducedTemplateArguments(Context, SavedPacks[I], NewPack);
2527 if (Result.isNull()) {
2528 Info.Param
2529 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
2530 Info.FirstArg = SavedPacks[I];
2531 Info.SecondArg = NewPack;
2532 return Sema::TDK_Inconsistent;
2533 }
2534
2535 Deduced[PackIndices[I]] = Result;
2536 }
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002538 // After we've matching against a parameter pack, we're done.
2539 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002540 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002541
Mike Stump1eb44332009-09-09 15:08:12 +00002542 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002543 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002544 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002545}
2546
Douglas Gregor83314aa2009-07-08 20:55:45 +00002547/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002548/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2549/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002550///
2551/// \param FunctionTemplate the function template for which we are performing
2552/// template argument deduction.
2553///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002554/// \param ExplicitTemplateArguments the explicitly-specified template
2555/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002556///
2557/// \param ArgFunctionType the function type that will be used as the
2558/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002559/// function template's function type. This type may be NULL, if there is no
2560/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002561///
2562/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002563/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002564/// template argument deduction.
2565///
2566/// \param Info the argument will be updated to provide additional information
2567/// about template argument deduction.
2568///
2569/// \returns the result of template argument deduction.
2570Sema::TemplateDeductionResult
2571Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002572 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002573 QualType ArgFunctionType,
2574 FunctionDecl *&Specialization,
2575 TemplateDeductionInfo &Info) {
2576 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2577 TemplateParameterList *TemplateParams
2578 = FunctionTemplate->getTemplateParameters();
2579 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002580
Douglas Gregor83314aa2009-07-08 20:55:45 +00002581 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002582 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002583 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2584 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002585 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002586 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002587 if (TemplateDeductionResult Result
2588 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002589 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002590 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002591 &FunctionType, Info))
2592 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002593
2594 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002595 }
2596
2597 // Template argument deduction for function templates in a SFINAE context.
2598 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002599 SFINAETrap Trap(*this);
2600
John McCalleff92132010-02-02 02:21:27 +00002601 Deduced.resize(TemplateParams->size());
2602
Douglas Gregor4b52e252009-12-21 23:17:24 +00002603 if (!ArgFunctionType.isNull()) {
2604 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002605 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002606 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002607 FunctionType, ArgFunctionType, Info,
2608 Deduced, 0))
2609 return Result;
2610 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002611
2612 if (TemplateDeductionResult Result
2613 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2614 NumExplicitlySpecified,
2615 Specialization, Info))
2616 return Result;
2617
2618 // If the requested function type does not match the actual type of the
2619 // specialization, template argument deduction fails.
2620 if (!ArgFunctionType.isNull() &&
2621 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2622 return TDK_NonDeducedMismatch;
2623
2624 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002625}
2626
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002627/// \brief Deduce template arguments for a templated conversion
2628/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2629/// conversion function template specialization.
2630Sema::TemplateDeductionResult
2631Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2632 QualType ToType,
2633 CXXConversionDecl *&Specialization,
2634 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002635 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002636 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2637 QualType FromType = Conv->getConversionType();
2638
2639 // Canonicalize the types for deduction.
2640 QualType P = Context.getCanonicalType(FromType);
2641 QualType A = Context.getCanonicalType(ToType);
2642
2643 // C++0x [temp.deduct.conv]p3:
2644 // If P is a reference type, the type referred to by P is used for
2645 // type deduction.
2646 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2647 P = PRef->getPointeeType();
2648
2649 // C++0x [temp.deduct.conv]p3:
2650 // If A is a reference type, the type referred to by A is used
2651 // for type deduction.
2652 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2653 A = ARef->getPointeeType();
2654 // C++ [temp.deduct.conv]p2:
2655 //
Mike Stump1eb44332009-09-09 15:08:12 +00002656 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002657 else {
2658 assert(!A->isReferenceType() && "Reference types were handled above");
2659
2660 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002661 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002662 // of P for type deduction; otherwise,
2663 if (P->isArrayType())
2664 P = Context.getArrayDecayedType(P);
2665 // - If P is a function type, the pointer type produced by the
2666 // function-to-pointer standard conversion (4.3) is used in
2667 // place of P for type deduction; otherwise,
2668 else if (P->isFunctionType())
2669 P = Context.getPointerType(P);
2670 // - If P is a cv-qualified type, the top level cv-qualifiers of
2671 // P’s type are ignored for type deduction.
2672 else
2673 P = P.getUnqualifiedType();
2674
2675 // C++0x [temp.deduct.conv]p3:
2676 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2677 // type are ignored for type deduction.
2678 A = A.getUnqualifiedType();
2679 }
2680
2681 // Template argument deduction for function templates in a SFINAE context.
2682 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002683 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002684
2685 // C++ [temp.deduct.conv]p1:
2686 // Template argument deduction is done by comparing the return
2687 // type of the template conversion function (call it P) with the
2688 // type that is required as the result of the conversion (call it
2689 // A) as described in 14.8.2.4.
2690 TemplateParameterList *TemplateParams
2691 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002692 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002693 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002694
2695 // C++0x [temp.deduct.conv]p4:
2696 // In general, the deduction process attempts to find template
2697 // argument values that will make the deduced A identical to
2698 // A. However, there are two cases that allow a difference:
2699 unsigned TDF = 0;
2700 // - If the original A is a reference type, A can be more
2701 // cv-qualified than the deduced A (i.e., the type referred to
2702 // by the reference)
2703 if (ToType->isReferenceType())
2704 TDF |= TDF_ParamWithReferenceType;
2705 // - The deduced A can be another pointer or pointer to member
2706 // type that can be converted to A via a qualification
2707 // conversion.
2708 //
2709 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2710 // both P and A are pointers or member pointers. In this case, we
2711 // just ignore cv-qualifiers completely).
2712 if ((P->isPointerType() && A->isPointerType()) ||
2713 (P->isMemberPointerType() && P->isMemberPointerType()))
2714 TDF |= TDF_IgnoreQualifiers;
2715 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002716 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002717 P, A, Info, Deduced, TDF))
2718 return Result;
2719
2720 // FIXME: we need to check that the deduced A is the same as A,
2721 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002723 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002724 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002725 FunctionDecl *Spec = 0;
2726 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002727 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2728 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002729 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2730 return Result;
2731}
2732
Douglas Gregor4b52e252009-12-21 23:17:24 +00002733/// \brief Deduce template arguments for a function template when there is
2734/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2735///
2736/// \param FunctionTemplate the function template for which we are performing
2737/// template argument deduction.
2738///
2739/// \param ExplicitTemplateArguments the explicitly-specified template
2740/// arguments.
2741///
2742/// \param Specialization if template argument deduction was successful,
2743/// this will be set to the function template specialization produced by
2744/// template argument deduction.
2745///
2746/// \param Info the argument will be updated to provide additional information
2747/// about template argument deduction.
2748///
2749/// \returns the result of template argument deduction.
2750Sema::TemplateDeductionResult
2751Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2752 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2753 FunctionDecl *&Specialization,
2754 TemplateDeductionInfo &Info) {
2755 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2756 QualType(), Specialization, Info);
2757}
2758
Douglas Gregor8a514912009-09-14 18:39:43 +00002759/// \brief Stores the result of comparing the qualifiers of two types.
2760enum DeductionQualifierComparison {
2761 NeitherMoreQualified = 0,
2762 ParamMoreQualified,
2763 ArgMoreQualified
2764};
2765
2766/// \brief Deduce the template arguments during partial ordering by comparing
2767/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2768///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002769/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002770///
2771/// \param TemplateParams the template parameters that we are deducing
2772///
2773/// \param ParamIn the parameter type
2774///
2775/// \param ArgIn the argument type
2776///
2777/// \param Info information about the template argument deduction itself
2778///
2779/// \param Deduced the deduced template arguments
2780///
2781/// \returns the result of template argument deduction so far. Note that a
2782/// "success" result means that template argument deduction has not yet failed,
2783/// but it may still fail, later, for other reasons.
2784static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002785DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002786 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002787 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002788 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002789 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2790 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002791 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2792 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002793
2794 // C++0x [temp.deduct.partial]p5:
2795 // Before the partial ordering is done, certain transformations are
2796 // performed on the types used for partial ordering:
2797 // - If P is a reference type, P is replaced by the type referred to.
2798 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002799 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002800 Param = ParamRef->getPointeeType();
2801
2802 // - If A is a reference type, A is replaced by the type referred to.
2803 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002804 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002805 Arg = ArgRef->getPointeeType();
2806
John McCalle27ec8a2009-10-23 23:03:21 +00002807 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002808 // C++0x [temp.deduct.partial]p6:
2809 // If both P and A were reference types (before being replaced with the
2810 // type referred to above), determine which of the two types (if any) is
2811 // more cv-qualified than the other; otherwise the types are considered to
2812 // be equally cv-qualified for partial ordering purposes. The result of this
2813 // determination will be used below.
2814 //
2815 // We save this information for later, using it only when deduction
2816 // succeeds in both directions.
2817 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2818 if (Param.isMoreQualifiedThan(Arg))
2819 QualifierResult = ParamMoreQualified;
2820 else if (Arg.isMoreQualifiedThan(Param))
2821 QualifierResult = ArgMoreQualified;
2822 QualifierComparisons->push_back(QualifierResult);
2823 }
2824
2825 // C++0x [temp.deduct.partial]p7:
2826 // Remove any top-level cv-qualifiers:
2827 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2828 // version of P.
2829 Param = Param.getUnqualifiedType();
2830 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2831 // version of A.
2832 Arg = Arg.getUnqualifiedType();
2833
2834 // C++0x [temp.deduct.partial]p8:
2835 // Using the resulting types P and A the deduction is then done as
2836 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2837 // from the argument template is considered to be at least as specialized
2838 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002839 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002840 Deduced, TDF_None);
2841}
2842
2843static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002844MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2845 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002846 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002847 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002848
2849/// \brief If this is a non-static member function,
2850static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2851 CXXMethodDecl *Method,
2852 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2853 if (Method->isStatic())
2854 return;
2855
2856 // C++ [over.match.funcs]p4:
2857 //
2858 // For non-static member functions, the type of the implicit
2859 // object parameter is
2860 // — "lvalue reference to cv X" for functions declared without a
2861 // ref-qualifier or with the & ref-qualifier
2862 // - "rvalue reference to cv X" for functions declared with the
2863 // && ref-qualifier
2864 //
2865 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2866 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2867 ArgTy = Context.getQualifiedType(ArgTy,
2868 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2869 ArgTy = Context.getLValueReferenceType(ArgTy);
2870 ArgTypes.push_back(ArgTy);
2871}
2872
Douglas Gregor8a514912009-09-14 18:39:43 +00002873/// \brief Determine whether the function template \p FT1 is at least as
2874/// specialized as \p FT2.
2875static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002876 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002877 FunctionTemplateDecl *FT1,
2878 FunctionTemplateDecl *FT2,
2879 TemplatePartialOrderingContext TPOC,
2880 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2881 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2882 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2883 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2884 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2885
2886 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2887 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002888 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002889 Deduced.resize(TemplateParams->size());
2890
2891 // C++0x [temp.deduct.partial]p3:
2892 // The types used to determine the ordering depend on the context in which
2893 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002894 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002895 CXXMethodDecl *Method1 = 0;
2896 CXXMethodDecl *Method2 = 0;
2897 bool IsNonStatic2 = false;
2898 bool IsNonStatic1 = false;
2899 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002900 switch (TPOC) {
2901 case TPOC_Call: {
2902 // - In the context of a function call, the function parameter types are
2903 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002904 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2905 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2906 IsNonStatic1 = Method1 && !Method1->isStatic();
2907 IsNonStatic2 = Method2 && !Method2->isStatic();
2908
2909 // C++0x [temp.func.order]p3:
2910 // [...] If only one of the function templates is a non-static
2911 // member, that function template is considered to have a new
2912 // first parameter inserted in its function parameter list. The
2913 // new parameter is of type "reference to cv A," where cv are
2914 // the cv-qualifiers of the function template (if any) and A is
2915 // the class of which the function template is a member.
2916 //
2917 // C++98/03 doesn't have this provision, so instead we drop the
2918 // first argument of the free function or static member, which
2919 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002920 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002921 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2922 IsNonStatic2 && !IsNonStatic1;
2923 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002924 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2925 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002926 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002927
2928 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002929 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2930 IsNonStatic1 && !IsNonStatic2;
2931 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002932 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2933 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002934 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002935
2936 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002937 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002938 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002939 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002940 Args2[I],
2941 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002942 Info,
2943 Deduced,
2944 QualifierComparisons))
2945 return false;
2946
2947 break;
2948 }
2949
2950 case TPOC_Conversion:
2951 // - In the context of a call to a conversion operator, the return types
2952 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002953 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002954 TemplateParams,
2955 Proto2->getResultType(),
2956 Proto1->getResultType(),
2957 Info,
2958 Deduced,
2959 QualifierComparisons))
2960 return false;
2961 break;
2962
2963 case TPOC_Other:
2964 // - In other contexts (14.6.6.2) the function template’s function type
2965 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002966 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002967 TemplateParams,
2968 FD2->getType(),
2969 FD1->getType(),
2970 Info,
2971 Deduced,
2972 QualifierComparisons))
2973 return false;
2974 break;
2975 }
2976
2977 // C++0x [temp.deduct.partial]p11:
2978 // In most cases, all template parameters must have values in order for
2979 // deduction to succeed, but for partial ordering purposes a template
2980 // parameter may remain without a value provided it is not used in the
2981 // types being used for partial ordering. [ Note: a template parameter used
2982 // in a non-deduced context is considered used. -end note]
2983 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2984 for (; ArgIdx != NumArgs; ++ArgIdx)
2985 if (Deduced[ArgIdx].isNull())
2986 break;
2987
2988 if (ArgIdx == NumArgs) {
2989 // All template arguments were deduced. FT1 is at least as specialized
2990 // as FT2.
2991 return true;
2992 }
2993
Douglas Gregore73bb602009-09-14 21:25:05 +00002994 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002995 llvm::SmallVector<bool, 4> UsedParameters;
2996 UsedParameters.resize(TemplateParams->size());
2997 switch (TPOC) {
2998 case TPOC_Call: {
2999 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003000 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3001 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3002 TemplateParams->getDepth(), UsedParameters);
3003 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003004 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3005 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003006 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003007 break;
3008 }
3009
3010 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003011 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3012 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003013 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003014 break;
3015
3016 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003017 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3018 TemplateParams->getDepth(),
3019 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003020 break;
3021 }
3022
3023 for (; ArgIdx != NumArgs; ++ArgIdx)
3024 // If this argument had no value deduced but was used in one of the types
3025 // used for partial ordering, then deduction fails.
3026 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3027 return false;
3028
3029 return true;
3030}
3031
3032
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003033/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003034/// to the rules of function template partial ordering (C++ [temp.func.order]).
3035///
3036/// \param FT1 the first function template
3037///
3038/// \param FT2 the second function template
3039///
Douglas Gregor8a514912009-09-14 18:39:43 +00003040/// \param TPOC the context in which we are performing partial ordering of
3041/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003042///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003043/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003044/// template is more specialized, returns NULL.
3045FunctionTemplateDecl *
3046Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3047 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003048 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003049 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003050 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00003051 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
3052 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00003053 &QualifierComparisons);
3054
3055 if (Better1 != Better2) // We have a clear winner
3056 return Better1? FT1 : FT2;
3057
3058 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003059 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003060
3061
3062 // C++0x [temp.deduct.partial]p10:
3063 // If for each type being considered a given template is at least as
3064 // specialized for all types and more specialized for some set of types and
3065 // the other template is not more specialized for any types or is not at
3066 // least as specialized for any types, then the given template is more
3067 // specialized than the other template. Otherwise, neither template is more
3068 // specialized than the other.
3069 Better1 = false;
3070 Better2 = false;
3071 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3072 // C++0x [temp.deduct.partial]p9:
3073 // If, for a given type, deduction succeeds in both directions (i.e., the
3074 // types are identical after the transformations above) and if the type
3075 // from the argument template is more cv-qualified than the type from the
3076 // parameter template (as described above) that type is considered to be
3077 // more specialized than the other. If neither type is more cv-qualified
3078 // than the other then neither type is more specialized than the other.
3079 switch (QualifierComparisons[I]) {
3080 case NeitherMoreQualified:
3081 break;
3082
3083 case ParamMoreQualified:
3084 Better1 = true;
3085 if (Better2)
3086 return 0;
3087 break;
3088
3089 case ArgMoreQualified:
3090 Better2 = true;
3091 if (Better1)
3092 return 0;
3093 break;
3094 }
3095 }
3096
3097 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003098 if (Better1)
3099 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003100 else if (Better2)
3101 return FT2;
3102 else
3103 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003104}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003105
Douglas Gregord5a423b2009-09-25 18:43:00 +00003106/// \brief Determine if the two templates are equivalent.
3107static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3108 if (T1 == T2)
3109 return true;
3110
3111 if (!T1 || !T2)
3112 return false;
3113
3114 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3115}
3116
3117/// \brief Retrieve the most specialized of the given function template
3118/// specializations.
3119///
John McCallc373d482010-01-27 01:50:18 +00003120/// \param SpecBegin the start iterator of the function template
3121/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003122///
John McCallc373d482010-01-27 01:50:18 +00003123/// \param SpecEnd the end iterator of the function template
3124/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003125///
3126/// \param TPOC the partial ordering context to use to compare the function
3127/// template specializations.
3128///
3129/// \param Loc the location where the ambiguity or no-specializations
3130/// diagnostic should occur.
3131///
3132/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3133/// no matching candidates.
3134///
3135/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3136/// occurs.
3137///
3138/// \param CandidateDiag partial diagnostic used for each function template
3139/// specialization that is a candidate in the ambiguous ordering. One parameter
3140/// in this diagnostic should be unbound, which will correspond to the string
3141/// describing the template arguments for the function template specialization.
3142///
3143/// \param Index if non-NULL and the result of this function is non-nULL,
3144/// receives the index corresponding to the resulting function template
3145/// specialization.
3146///
3147/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003148/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003149///
3150/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3151/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003152UnresolvedSetIterator
3153Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3154 UnresolvedSetIterator SpecEnd,
3155 TemplatePartialOrderingContext TPOC,
3156 SourceLocation Loc,
3157 const PartialDiagnostic &NoneDiag,
3158 const PartialDiagnostic &AmbigDiag,
3159 const PartialDiagnostic &CandidateDiag) {
3160 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003161 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003162 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003163 }
3164
John McCallc373d482010-01-27 01:50:18 +00003165 if (SpecBegin + 1 == SpecEnd)
3166 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003167
3168 // Find the function template that is better than all of the templates it
3169 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003170 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003171 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003172 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003173 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003174 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3175 FunctionTemplateDecl *Challenger
3176 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003177 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003178 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003179 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003180 Challenger)) {
3181 Best = I;
3182 BestTemplate = Challenger;
3183 }
3184 }
3185
3186 // Make sure that the "best" function template is more specialized than all
3187 // of the others.
3188 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003189 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3190 FunctionTemplateDecl *Challenger
3191 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003192 if (I != Best &&
3193 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003194 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003195 BestTemplate)) {
3196 Ambiguous = true;
3197 break;
3198 }
3199 }
3200
3201 if (!Ambiguous) {
3202 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003203 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003204 }
3205
3206 // Diagnose the ambiguity.
3207 Diag(Loc, AmbigDiag);
3208
3209 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003210 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3211 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003212 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003213 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3214 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003215
John McCallc373d482010-01-27 01:50:18 +00003216 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003217}
3218
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003219/// \brief Returns the more specialized class template partial specialization
3220/// according to the rules of partial ordering of class template partial
3221/// specializations (C++ [temp.class.order]).
3222///
3223/// \param PS1 the first class template partial specialization
3224///
3225/// \param PS2 the second class template partial specialization
3226///
3227/// \returns the more specialized class template partial specialization. If
3228/// neither partial specialization is more specialized, returns NULL.
3229ClassTemplatePartialSpecializationDecl *
3230Sema::getMoreSpecializedPartialSpecialization(
3231 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003232 ClassTemplatePartialSpecializationDecl *PS2,
3233 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003234 // C++ [temp.class.order]p1:
3235 // For two class template partial specializations, the first is at least as
3236 // specialized as the second if, given the following rewrite to two
3237 // function templates, the first function template is at least as
3238 // specialized as the second according to the ordering rules for function
3239 // templates (14.6.6.2):
3240 // - the first function template has the same template parameters as the
3241 // first partial specialization and has a single function parameter
3242 // whose type is a class template specialization with the template
3243 // arguments of the first partial specialization, and
3244 // - the second function template has the same template parameters as the
3245 // second partial specialization and has a single function parameter
3246 // whose type is a class template specialization with the template
3247 // arguments of the second partial specialization.
3248 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003249 // Rather than synthesize function templates, we merely perform the
3250 // equivalent partial ordering by performing deduction directly on
3251 // the template arguments of the class template partial
3252 // specializations. This computation is slightly simpler than the
3253 // general problem of function template partial ordering, because
3254 // class template partial specializations are more constrained. We
3255 // know that every template parameter is deducible from the class
3256 // template partial specialization's template arguments, for
3257 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003258 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003259 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003260
3261 QualType PT1 = PS1->getInjectedSpecializationType();
3262 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003263
3264 // Determine whether PS1 is at least as specialized as PS2
3265 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003266 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003267 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003268 PT2,
3269 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003270 Info,
3271 Deduced,
3272 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003273 if (Better1) {
3274 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3275 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003276 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3277 PS1->getTemplateArgs(),
3278 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003279 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003280
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003281 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003282 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003283 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003284 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003285 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003286 PT1,
3287 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003288 Info,
3289 Deduced,
3290 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003291 if (Better2) {
3292 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3293 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003294 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3295 PS2->getTemplateArgs(),
3296 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003297 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003298
3299 if (Better1 == Better2)
3300 return 0;
3301
3302 return Better1? PS1 : PS2;
3303}
3304
Mike Stump1eb44332009-09-09 15:08:12 +00003305static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003306MarkUsedTemplateParameters(Sema &SemaRef,
3307 const TemplateArgument &TemplateArg,
3308 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003309 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003310 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003311
Douglas Gregore73bb602009-09-14 21:25:05 +00003312/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003313/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003314static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003315MarkUsedTemplateParameters(Sema &SemaRef,
3316 const Expr *E,
3317 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003318 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003319 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003320 // We can deduce from a pack expansion.
3321 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3322 E = Expansion->getPattern();
3323
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003324 // Skip through any implicit casts we added while type-checking.
3325 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3326 E = ICE->getSubExpr();
3327
Douglas Gregore73bb602009-09-14 21:25:05 +00003328 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3329 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003330 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003331 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003332 return;
3333
Mike Stump1eb44332009-09-09 15:08:12 +00003334 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003335 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3336 if (!NTTP)
3337 return;
3338
Douglas Gregored9c0f92009-10-29 00:04:11 +00003339 if (NTTP->getDepth() == Depth)
3340 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003341}
3342
Douglas Gregore73bb602009-09-14 21:25:05 +00003343/// \brief Mark the template parameters that are used by the given
3344/// nested name specifier.
3345static void
3346MarkUsedTemplateParameters(Sema &SemaRef,
3347 NestedNameSpecifier *NNS,
3348 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003349 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003350 llvm::SmallVectorImpl<bool> &Used) {
3351 if (!NNS)
3352 return;
3353
Douglas Gregored9c0f92009-10-29 00:04:11 +00003354 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3355 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003356 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003357 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003358}
3359
3360/// \brief Mark the template parameters that are used by the given
3361/// template name.
3362static void
3363MarkUsedTemplateParameters(Sema &SemaRef,
3364 TemplateName Name,
3365 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003366 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003367 llvm::SmallVectorImpl<bool> &Used) {
3368 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3369 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003370 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3371 if (TTP->getDepth() == Depth)
3372 Used[TTP->getIndex()] = true;
3373 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003374 return;
3375 }
3376
Douglas Gregor788cd062009-11-11 01:00:40 +00003377 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3378 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3379 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003380 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003381 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3382 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003383}
3384
3385/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003386/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003387static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003388MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3389 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003390 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003391 llvm::SmallVectorImpl<bool> &Used) {
3392 if (T.isNull())
3393 return;
3394
Douglas Gregor031a5882009-06-13 00:26:55 +00003395 // Non-dependent types have nothing deducible
3396 if (!T->isDependentType())
3397 return;
3398
3399 T = SemaRef.Context.getCanonicalType(T);
3400 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003401 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003402 MarkUsedTemplateParameters(SemaRef,
3403 cast<PointerType>(T)->getPointeeType(),
3404 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003405 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003406 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003407 break;
3408
3409 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003410 MarkUsedTemplateParameters(SemaRef,
3411 cast<BlockPointerType>(T)->getPointeeType(),
3412 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003413 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003414 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003415 break;
3416
3417 case Type::LValueReference:
3418 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003419 MarkUsedTemplateParameters(SemaRef,
3420 cast<ReferenceType>(T)->getPointeeType(),
3421 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003422 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003423 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003424 break;
3425
3426 case Type::MemberPointer: {
3427 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003428 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003429 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003430 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003431 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003432 break;
3433 }
3434
3435 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003436 MarkUsedTemplateParameters(SemaRef,
3437 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003438 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003439 // Fall through to check the element type
3440
3441 case Type::ConstantArray:
3442 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003443 MarkUsedTemplateParameters(SemaRef,
3444 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003445 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003446 break;
3447
3448 case Type::Vector:
3449 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003450 MarkUsedTemplateParameters(SemaRef,
3451 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003452 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003453 break;
3454
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003455 case Type::DependentSizedExtVector: {
3456 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003457 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003458 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003459 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003460 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003461 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003462 break;
3463 }
3464
Douglas Gregor031a5882009-06-13 00:26:55 +00003465 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003466 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003467 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003468 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003469 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003470 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003471 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003472 break;
3473 }
3474
Douglas Gregored9c0f92009-10-29 00:04:11 +00003475 case Type::TemplateTypeParm: {
3476 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3477 if (TTP->getDepth() == Depth)
3478 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003479 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003480 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003481
John McCall31f17ec2010-04-27 00:57:59 +00003482 case Type::InjectedClassName:
3483 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3484 // fall through
3485
Douglas Gregor031a5882009-06-13 00:26:55 +00003486 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003487 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003488 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003489 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003490 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003491
3492 // C++0x [temp.deduct.type]p9:
3493 // If the template argument list of P contains a pack expansion that is not
3494 // the last template argument, the entire template argument list is a
3495 // non-deduced context.
3496 if (OnlyDeduced &&
3497 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3498 break;
3499
Douglas Gregore73bb602009-09-14 21:25:05 +00003500 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003501 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3502 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003503 break;
3504 }
3505
Douglas Gregore73bb602009-09-14 21:25:05 +00003506 case Type::Complex:
3507 if (!OnlyDeduced)
3508 MarkUsedTemplateParameters(SemaRef,
3509 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003510 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003511 break;
3512
Douglas Gregor4714c122010-03-31 17:34:00 +00003513 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003514 if (!OnlyDeduced)
3515 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003516 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003517 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003518 break;
3519
John McCall33500952010-06-11 00:33:02 +00003520 case Type::DependentTemplateSpecialization: {
3521 const DependentTemplateSpecializationType *Spec
3522 = cast<DependentTemplateSpecializationType>(T);
3523 if (!OnlyDeduced)
3524 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3525 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003526
3527 // C++0x [temp.deduct.type]p9:
3528 // If the template argument list of P contains a pack expansion that is not
3529 // the last template argument, the entire template argument list is a
3530 // non-deduced context.
3531 if (OnlyDeduced &&
3532 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3533 break;
3534
John McCall33500952010-06-11 00:33:02 +00003535 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3536 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3537 Used);
3538 break;
3539 }
3540
John McCallad5e7382010-03-01 23:49:17 +00003541 case Type::TypeOf:
3542 if (!OnlyDeduced)
3543 MarkUsedTemplateParameters(SemaRef,
3544 cast<TypeOfType>(T)->getUnderlyingType(),
3545 OnlyDeduced, Depth, Used);
3546 break;
3547
3548 case Type::TypeOfExpr:
3549 if (!OnlyDeduced)
3550 MarkUsedTemplateParameters(SemaRef,
3551 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3552 OnlyDeduced, Depth, Used);
3553 break;
3554
3555 case Type::Decltype:
3556 if (!OnlyDeduced)
3557 MarkUsedTemplateParameters(SemaRef,
3558 cast<DecltypeType>(T)->getUnderlyingExpr(),
3559 OnlyDeduced, Depth, Used);
3560 break;
3561
Douglas Gregor7536dd52010-12-20 02:24:11 +00003562 case Type::PackExpansion:
3563 MarkUsedTemplateParameters(SemaRef,
3564 cast<PackExpansionType>(T)->getPattern(),
3565 OnlyDeduced, Depth, Used);
3566 break;
3567
Douglas Gregore73bb602009-09-14 21:25:05 +00003568 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003569 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003570 case Type::VariableArray:
3571 case Type::FunctionNoProto:
3572 case Type::Record:
3573 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003574 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003575 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003576 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003577 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003578#define TYPE(Class, Base)
3579#define ABSTRACT_TYPE(Class, Base)
3580#define DEPENDENT_TYPE(Class, Base)
3581#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3582#include "clang/AST/TypeNodes.def"
3583 break;
3584 }
3585}
3586
Douglas Gregore73bb602009-09-14 21:25:05 +00003587/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003588/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003589static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003590MarkUsedTemplateParameters(Sema &SemaRef,
3591 const TemplateArgument &TemplateArg,
3592 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003593 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003594 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003595 switch (TemplateArg.getKind()) {
3596 case TemplateArgument::Null:
3597 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003598 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003599 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Douglas Gregor031a5882009-06-13 00:26:55 +00003601 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003602 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003603 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003604 break;
3605
Douglas Gregor788cd062009-11-11 01:00:40 +00003606 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003607 case TemplateArgument::TemplateExpansion:
3608 MarkUsedTemplateParameters(SemaRef,
3609 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003610 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003611 break;
3612
3613 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003614 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003615 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003616 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003617
Anders Carlssond01b1da2009-06-15 17:04:53 +00003618 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003619 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3620 PEnd = TemplateArg.pack_end();
3621 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003622 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003623 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003624 }
3625}
3626
3627/// \brief Mark the template parameters can be deduced by the given
3628/// template argument list.
3629///
3630/// \param TemplateArgs the template argument list from which template
3631/// parameters will be deduced.
3632///
3633/// \param Deduced a bit vector whose elements will be set to \c true
3634/// to indicate when the corresponding template parameter will be
3635/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003636void
Douglas Gregore73bb602009-09-14 21:25:05 +00003637Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003638 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003639 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003640 // C++0x [temp.deduct.type]p9:
3641 // If the template argument list of P contains a pack expansion that is not
3642 // the last template argument, the entire template argument list is a
3643 // non-deduced context.
3644 if (OnlyDeduced &&
3645 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3646 return;
3647
Douglas Gregor031a5882009-06-13 00:26:55 +00003648 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003649 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3650 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003651}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003652
3653/// \brief Marks all of the template parameters that will be deduced by a
3654/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003655void
3656Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3657 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003658 TemplateParameterList *TemplateParams
3659 = FunctionTemplate->getTemplateParameters();
3660 Deduced.clear();
3661 Deduced.resize(TemplateParams->size());
3662
3663 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3664 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3665 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003666 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003667}