blob: fcc73b89747f9cea89d527a87ff311cd41afcbc6 [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.
1892 for (FunctionDecl::param_iterator P = Function->param_begin(),
1893 PEnd = Function->param_end();
1894 P != PEnd;
1895 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001896 QualType ParamType
1897 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001898 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1899 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001900 if (ParamType.isNull() || Trap.hasErrorOccurred())
1901 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Douglas Gregor83314aa2009-07-08 20:55:45 +00001903 ParamTypes.push_back(ParamType);
1904 }
1905
1906 // If the caller wants a full function type back, instantiate the return
1907 // type and form that function type.
1908 if (FunctionType) {
1909 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001910 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001911 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001912 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001913
1914 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001915 = SubstType(Proto->getResultType(),
1916 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1917 Function->getTypeSpecStartLoc(),
1918 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001919 if (ResultType.isNull() || Trap.hasErrorOccurred())
1920 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001921
1922 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001923 ParamTypes.data(), ParamTypes.size(),
1924 Proto->isVariadic(),
1925 Proto->getTypeQuals(),
1926 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001927 Function->getDeclName(),
1928 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001929 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1930 return TDK_SubstitutionFailure;
1931 }
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Douglas Gregor83314aa2009-07-08 20:55:45 +00001933 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001934 // Trailing template arguments that can be deduced (14.8.2) may be
1935 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001936 // template arguments can be deduced, they may all be omitted; in this
1937 // case, the empty template argument list <> itself may also be omitted.
1938 //
1939 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001940 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001941 Deduced.reserve(TemplateParams->size());
1942 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001943 Deduced.push_back(ExplicitArgumentList->get(I));
1944
Douglas Gregor83314aa2009-07-08 20:55:45 +00001945 return TDK_Success;
1946}
1947
Mike Stump1eb44332009-09-09 15:08:12 +00001948/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001949/// checking the deduced template arguments for completeness and forming
1950/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001951Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001952Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001953 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1954 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001955 FunctionDecl *&Specialization,
1956 TemplateDeductionInfo &Info) {
1957 TemplateParameterList *TemplateParams
1958 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Douglas Gregor83314aa2009-07-08 20:55:45 +00001960 // Template argument deduction for function templates in a SFINAE context.
1961 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001962 SFINAETrap Trap(*this);
1963
Douglas Gregor83314aa2009-07-08 20:55:45 +00001964 // Enter a new template instantiation context while we instantiate the
1965 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001966 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001967 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001968 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1969 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001970 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001971 return TDK_InstantiationDepth;
1972
John McCall96db3102010-04-29 01:18:58 +00001973 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001974
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001975 // C++ [temp.deduct.type]p2:
1976 // [...] or if any template argument remains neither deduced nor
1977 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001978 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001979 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
1980 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001981
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001982 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001983 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001984 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001985 // argument, because it was explicitly-specified. Just record the
1986 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001987 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001988 continue;
1989 }
1990
1991 // We have deduced this argument, so it still needs to be
1992 // checked and converted.
1993
1994 // First, for a non-type template parameter type that is
1995 // initialized by a declaration, we need the type of the
1996 // corresponding non-type template parameter.
1997 QualType NTTPType;
1998 if (NonTypeTemplateParmDecl *NTTP
1999 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002000 NTTPType = NTTP->getType();
2001 if (NTTPType->isDependentType()) {
2002 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2003 Builder.data(), Builder.size());
2004 NTTPType = SubstType(NTTPType,
2005 MultiLevelTemplateArgumentList(TemplateArgs),
2006 NTTP->getLocation(),
2007 NTTP->getDeclName());
2008 if (NTTPType.isNull()) {
2009 Info.Param = makeTemplateParameter(Param);
2010 // FIXME: These template arguments are temporary. Free them!
2011 Info.reset(TemplateArgumentList::CreateCopy(Context,
2012 Builder.data(),
2013 Builder.size()));
2014 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002015 }
2016 }
2017 }
2018
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002019 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2020 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002021 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002022 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002023 // FIXME: These template arguments are temporary. Free them!
2024 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002025 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002026 return TDK_SubstitutionFailure;
2027 }
2028
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002029 continue;
2030 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002031
2032 // C++0x [temp.arg.explicit]p3:
2033 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2034 // be deduced to an empty sequence of template arguments.
2035 // FIXME: Where did the word "trailing" come from?
2036 if (Param->isTemplateParameterPack()) {
2037 Builder.push_back(TemplateArgument(0, 0));
2038 continue;
2039 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002040
2041 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002042 TemplateArgumentLoc DefArg
2043 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2044 FunctionTemplate->getLocation(),
2045 FunctionTemplate->getSourceRange().getEnd(),
2046 Param,
2047 Builder);
2048
2049 // If there was no default argument, deduction is incomplete.
2050 if (DefArg.getArgument().isNull()) {
2051 Info.Param = makeTemplateParameter(
2052 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2053 return TDK_Incomplete;
2054 }
2055
2056 // Check whether we can actually use the default argument.
2057 if (CheckTemplateArgument(Param, DefArg,
2058 FunctionTemplate,
2059 FunctionTemplate->getLocation(),
2060 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002061 Builder,
2062 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002063 Info.Param = makeTemplateParameter(
2064 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002065 // FIXME: These template arguments are temporary. Free them!
2066 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2067 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002068 return TDK_SubstitutionFailure;
2069 }
2070
2071 // If we get here, we successfully used the default template argument.
2072 }
2073
2074 // Form the template argument list from the deduced template arguments.
2075 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002076 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002077 Info.reset(DeducedArgumentList);
2078
Mike Stump1eb44332009-09-09 15:08:12 +00002079 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002080 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002081 DeclContext *Owner = FunctionTemplate->getDeclContext();
2082 if (FunctionTemplate->getFriendObjectKind())
2083 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002084 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002085 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002086 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002087 if (!Specialization)
2088 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Douglas Gregorf8825742009-09-15 18:26:13 +00002090 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2091 FunctionTemplate->getCanonicalDecl());
2092
Mike Stump1eb44332009-09-09 15:08:12 +00002093 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002094 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002095 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2096 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002097 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Douglas Gregor83314aa2009-07-08 20:55:45 +00002099 // There may have been an error that did not prevent us from constructing a
2100 // declaration. Mark the declaration invalid and return with a substitution
2101 // failure.
2102 if (Trap.hasErrorOccurred()) {
2103 Specialization->setInvalidDecl(true);
2104 return TDK_SubstitutionFailure;
2105 }
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Douglas Gregor9b623632010-10-12 23:32:35 +00002107 // If we suppressed any diagnostics while performing template argument
2108 // deduction, and if we haven't already instantiated this declaration,
2109 // keep track of these diagnostics. They'll be emitted if this specialization
2110 // is actually used.
2111 if (Info.diag_begin() != Info.diag_end()) {
2112 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2113 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2114 if (Pos == SuppressedDiagnostics.end())
2115 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2116 .append(Info.diag_begin(), Info.diag_end());
2117 }
2118
Mike Stump1eb44332009-09-09 15:08:12 +00002119 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002120}
2121
John McCall9c72c602010-08-27 09:08:28 +00002122/// Gets the type of a function for template-argument-deducton
2123/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002124static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002125 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002126 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002127 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002128 if (Method->isInstance()) {
2129 // An instance method that's referenced in a form that doesn't
2130 // look like a member pointer is just invalid.
2131 if (!R.HasFormOfMemberPointer) return QualType();
2132
John McCalleff92132010-02-02 02:21:27 +00002133 return Context.getMemberPointerType(Fn->getType(),
2134 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002135 }
2136
2137 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002138 return Context.getPointerType(Fn->getType());
2139}
2140
2141/// Apply the deduction rules for overload sets.
2142///
2143/// \return the null type if this argument should be treated as an
2144/// undeduced context
2145static QualType
2146ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002147 Expr *Arg, QualType ParamType,
2148 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002149
2150 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002151
John McCall9c72c602010-08-27 09:08:28 +00002152 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002153
Douglas Gregor75f21af2010-08-30 21:04:23 +00002154 // C++0x [temp.deduct.call]p4
2155 unsigned TDF = 0;
2156 if (ParamWasReference)
2157 TDF |= TDF_ParamWithReferenceType;
2158 if (R.IsAddressOfOperand)
2159 TDF |= TDF_IgnoreQualifiers;
2160
John McCalleff92132010-02-02 02:21:27 +00002161 // If there were explicit template arguments, we can only find
2162 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2163 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002164 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002165 // But we can still look for an explicit specialization.
2166 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002167 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002168 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002169 return QualType();
2170 }
2171
2172 // C++0x [temp.deduct.call]p6:
2173 // When P is a function type, pointer to function type, or pointer
2174 // to member function type:
2175
2176 if (!ParamType->isFunctionType() &&
2177 !ParamType->isFunctionPointerType() &&
2178 !ParamType->isMemberFunctionPointerType())
2179 return QualType();
2180
2181 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002182 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2183 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002184 NamedDecl *D = (*I)->getUnderlyingDecl();
2185
2186 // - If the argument is an overload set containing one or more
2187 // function templates, the parameter is treated as a
2188 // non-deduced context.
2189 if (isa<FunctionTemplateDecl>(D))
2190 return QualType();
2191
2192 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002193 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2194 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002195
Douglas Gregor75f21af2010-08-30 21:04:23 +00002196 // Function-to-pointer conversion.
2197 if (!ParamWasReference && ParamType->isPointerType() &&
2198 ArgType->isFunctionType())
2199 ArgType = S.Context.getPointerType(ArgType);
2200
John McCalleff92132010-02-02 02:21:27 +00002201 // - If the argument is an overload set (not containing function
2202 // templates), trial argument deduction is attempted using each
2203 // of the members of the set. If deduction succeeds for only one
2204 // of the overload set members, that member is used as the
2205 // argument value for the deduction. If deduction succeeds for
2206 // more than one member of the overload set the parameter is
2207 // treated as a non-deduced context.
2208
2209 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2210 // Type deduction is done independently for each P/A pair, and
2211 // the deduced template argument values are then combined.
2212 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002213 llvm::SmallVector<DeducedTemplateArgument, 8>
2214 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002215 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002216 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002217 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002218 ParamType, ArgType,
2219 Info, Deduced, TDF);
2220 if (Result) continue;
2221 if (!Match.isNull()) return QualType();
2222 Match = ArgType;
2223 }
2224
2225 return Match;
2226}
2227
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002228/// \brief Perform the adjustments to the parameter and argument types
2229/// described in C++ [temp.deduct.call].
2230///
2231/// \returns true if the caller should not attempt to perform any template
2232/// argument deduction based on this P/A pair.
2233static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2234 TemplateParameterList *TemplateParams,
2235 QualType &ParamType,
2236 QualType &ArgType,
2237 Expr *Arg,
2238 unsigned &TDF) {
2239 // C++0x [temp.deduct.call]p3:
2240 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2241 // are ignored for type deduction.
2242 if (ParamType.getCVRQualifiers())
2243 ParamType = ParamType.getLocalUnqualifiedType();
2244 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2245 if (ParamRefType) {
2246 // [...] If P is a reference type, the type referred to by P is used
2247 // for type deduction.
2248 ParamType = ParamRefType->getPointeeType();
2249 }
2250
2251 // Overload sets usually make this parameter an undeduced
2252 // context, but there are sometimes special circumstances.
2253 if (ArgType == S.Context.OverloadTy) {
2254 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2255 Arg, ParamType,
2256 ParamRefType != 0);
2257 if (ArgType.isNull())
2258 return true;
2259 }
2260
2261 if (ParamRefType) {
2262 // C++0x [temp.deduct.call]p3:
2263 // [...] If P is of the form T&&, where T is a template parameter, and
2264 // the argument is an lvalue, the type A& is used in place of A for
2265 // type deduction.
2266 if (ParamRefType->isRValueReferenceType() &&
2267 ParamRefType->getAs<TemplateTypeParmType>() &&
2268 Arg->isLValue())
2269 ArgType = S.Context.getLValueReferenceType(ArgType);
2270 } else {
2271 // C++ [temp.deduct.call]p2:
2272 // If P is not a reference type:
2273 // - If A is an array type, the pointer type produced by the
2274 // array-to-pointer standard conversion (4.2) is used in place of
2275 // A for type deduction; otherwise,
2276 if (ArgType->isArrayType())
2277 ArgType = S.Context.getArrayDecayedType(ArgType);
2278 // - If A is a function type, the pointer type produced by the
2279 // function-to-pointer standard conversion (4.3) is used in place
2280 // of A for type deduction; otherwise,
2281 else if (ArgType->isFunctionType())
2282 ArgType = S.Context.getPointerType(ArgType);
2283 else {
2284 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2285 // type are ignored for type deduction.
2286 QualType CanonArgType = S.Context.getCanonicalType(ArgType);
2287 if (ArgType.getCVRQualifiers())
2288 ArgType = ArgType.getUnqualifiedType();
2289 }
2290 }
2291
2292 // C++0x [temp.deduct.call]p4:
2293 // In general, the deduction process attempts to find template argument
2294 // values that will make the deduced A identical to A (after the type A
2295 // is transformed as described above). [...]
2296 TDF = TDF_SkipNonDependent;
2297
2298 // - If the original P is a reference type, the deduced A (i.e., the
2299 // type referred to by the reference) can be more cv-qualified than
2300 // the transformed A.
2301 if (ParamRefType)
2302 TDF |= TDF_ParamWithReferenceType;
2303 // - The transformed A can be another pointer or pointer to member
2304 // type that can be converted to the deduced A via a qualification
2305 // conversion (4.4).
2306 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2307 ArgType->isObjCObjectPointerType())
2308 TDF |= TDF_IgnoreQualifiers;
2309 // - If P is a class and P has the form simple-template-id, then the
2310 // transformed A can be a derived class of the deduced A. Likewise,
2311 // if P is a pointer to a class of the form simple-template-id, the
2312 // transformed A can be a pointer to a derived class pointed to by
2313 // the deduced A.
2314 if (isSimpleTemplateIdType(ParamType) ||
2315 (isa<PointerType>(ParamType) &&
2316 isSimpleTemplateIdType(
2317 ParamType->getAs<PointerType>()->getPointeeType())))
2318 TDF |= TDF_DerivedClass;
2319
2320 return false;
2321}
2322
Douglas Gregore53060f2009-06-25 22:08:12 +00002323/// \brief Perform template argument deduction from a function call
2324/// (C++ [temp.deduct.call]).
2325///
2326/// \param FunctionTemplate the function template for which we are performing
2327/// template argument deduction.
2328///
Douglas Gregor48026d22010-01-11 18:40:55 +00002329/// \param ExplicitTemplateArguments the explicit template arguments provided
2330/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002331///
Douglas Gregore53060f2009-06-25 22:08:12 +00002332/// \param Args the function call arguments
2333///
2334/// \param NumArgs the number of arguments in Args
2335///
Douglas Gregor48026d22010-01-11 18:40:55 +00002336/// \param Name the name of the function being called. This is only significant
2337/// when the function template is a conversion function template, in which
2338/// case this routine will also perform template argument deduction based on
2339/// the function to which
2340///
Douglas Gregore53060f2009-06-25 22:08:12 +00002341/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002342/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002343/// template argument deduction.
2344///
2345/// \param Info the argument will be updated to provide additional information
2346/// about template argument deduction.
2347///
2348/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002349Sema::TemplateDeductionResult
2350Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002351 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002352 Expr **Args, unsigned NumArgs,
2353 FunctionDecl *&Specialization,
2354 TemplateDeductionInfo &Info) {
2355 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002356
Douglas Gregore53060f2009-06-25 22:08:12 +00002357 // C++ [temp.deduct.call]p1:
2358 // Template argument deduction is done by comparing each function template
2359 // parameter type (call it P) with the type of the corresponding argument
2360 // of the call (call it A) as described below.
2361 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002362 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002363 return TDK_TooFewArguments;
2364 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002365 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002366 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002367 if (Proto->isTemplateVariadic())
2368 /* Do nothing */;
2369 else if (Proto->isVariadic())
2370 CheckArgs = Function->getNumParams();
2371 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002372 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002373 }
Mike Stump1eb44332009-09-09 15:08:12 +00002374
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002375 // The types of the parameters from which we will perform template argument
2376 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002377 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002378 TemplateParameterList *TemplateParams
2379 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002380 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002381 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002382 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002383 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002384 TemplateDeductionResult Result =
2385 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002386 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002387 Deduced,
2388 ParamTypes,
2389 0,
2390 Info);
2391 if (Result)
2392 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002393
2394 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002395 } else {
2396 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002397 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002398 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2399 }
Mike Stump1eb44332009-09-09 15:08:12 +00002400
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002401 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002402 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002403 unsigned ArgIdx = 0;
2404 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2405 ParamIdx != NumParams; ++ParamIdx) {
2406 QualType ParamType = ParamTypes[ParamIdx];
2407
2408 const PackExpansionType *ParamExpansion
2409 = dyn_cast<PackExpansionType>(ParamType);
2410 if (!ParamExpansion) {
2411 // Simple case: matching a function parameter to a function argument.
2412 if (ArgIdx >= CheckArgs)
2413 break;
2414
2415 Expr *Arg = Args[ArgIdx++];
2416 QualType ArgType = Arg->getType();
2417 unsigned TDF = 0;
2418 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2419 ParamType, ArgType, Arg,
2420 TDF))
2421 continue;
2422
2423 if (TemplateDeductionResult Result
2424 = ::DeduceTemplateArguments(*this, TemplateParams,
2425 ParamType, ArgType, Info, Deduced,
2426 TDF))
2427 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002428
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002429 // FIXME: we need to check that the deduced A is the same as A,
2430 // modulo the various allowed differences.
2431 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002432 }
2433
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002434 // C++0x [temp.deduct.call]p1:
2435 // For a function parameter pack that occurs at the end of the
2436 // parameter-declaration-list, the type A of each remaining argument of
2437 // the call is compared with the type P of the declarator-id of the
2438 // function parameter pack. Each comparison deduces template arguments
2439 // for subsequent positions in the template parameter packs expanded by
2440 // the function parameter pack.
2441 QualType ParamPattern = ParamExpansion->getPattern();
2442 llvm::SmallVector<unsigned, 2> PackIndices;
2443 {
2444 llvm::BitVector SawIndices(TemplateParams->size());
2445 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2446 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2447 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2448 unsigned Depth, Index;
2449 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2450 if (Depth == 0 && !SawIndices[Index]) {
2451 SawIndices[Index] = true;
2452 PackIndices.push_back(Index);
2453 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002454 }
2455 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002456 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2457
2458 // Save the deduced template arguments for each parameter pack expanded
2459 // by this pack expansion, then clear out the deduction.
2460 llvm::SmallVector<DeducedTemplateArgument, 2>
2461 SavedPacks(PackIndices.size());
2462 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2463 SavedPacks[I] = Deduced[PackIndices[I]];
2464 Deduced[PackIndices[I]] = DeducedTemplateArgument();
2465 }
2466
2467 // Keep track of the deduced template arguments for each parameter pack
2468 // expanded by this pack expansion (the outer index) and for each
2469 // template argument (the inner SmallVectors).
2470 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
2471 NewlyDeducedPacks(PackIndices.size());
2472 bool HasAnyArguments = false;
2473 for (; ArgIdx < NumArgs; ++ArgIdx) {
2474 HasAnyArguments = true;
2475
2476 ParamType = ParamPattern;
2477 Expr *Arg = Args[ArgIdx];
2478 QualType ArgType = Arg->getType();
2479 unsigned TDF = 0;
2480 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2481 ParamType, ArgType, Arg,
2482 TDF)) {
2483 // We can't actually perform any deduction for this argument, so stop
2484 // deduction at this point.
2485 ++ArgIdx;
2486 break;
2487 }
2488
2489 if (TemplateDeductionResult Result
2490 = ::DeduceTemplateArguments(*this, TemplateParams,
2491 ParamType, ArgType, Info, Deduced,
2492 TDF))
2493 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002494
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002495 // Capture the deduced template arguments for each parameter pack expanded
2496 // by this pack expansion, add them to the list of arguments we've deduced
2497 // for that pack, then clear out the deduced argument.
2498 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2499 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2500 if (!DeducedArg.isNull()) {
2501 NewlyDeducedPacks[I].push_back(DeducedArg);
2502 DeducedArg = DeducedTemplateArgument();
2503 }
2504 }
2505 }
2506
2507 // Build argument packs for each of the parameter packs expanded by this
2508 // pack expansion.
2509 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2510 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
2511 // We were not able to deduce anything for this parameter pack,
2512 // so just restore the saved argument pack.
2513 Deduced[PackIndices[I]] = SavedPacks[I];
2514 continue;
2515 }
2516
2517 DeducedTemplateArgument NewPack;
2518
2519 if (NewlyDeducedPacks[I].empty()) {
2520 // If we deduced an empty argument pack, create it now.
2521 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
2522 } else {
2523 TemplateArgument *ArgumentPack
2524 = new (Context) TemplateArgument [NewlyDeducedPacks[I].size()];
2525 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
2526 ArgumentPack);
2527 NewPack
2528 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
2529 NewlyDeducedPacks[I].size()),
2530 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
2531 }
2532
2533 DeducedTemplateArgument Result
2534 = checkDeducedTemplateArguments(Context, SavedPacks[I], NewPack);
2535 if (Result.isNull()) {
2536 Info.Param
2537 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
2538 Info.FirstArg = SavedPacks[I];
2539 Info.SecondArg = NewPack;
2540 return Sema::TDK_Inconsistent;
2541 }
2542
2543 Deduced[PackIndices[I]] = Result;
2544 }
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002546 // After we've matching against a parameter pack, we're done.
2547 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002548 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002549
Mike Stump1eb44332009-09-09 15:08:12 +00002550 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002551 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002552 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002553}
2554
Douglas Gregor83314aa2009-07-08 20:55:45 +00002555/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002556/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2557/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002558///
2559/// \param FunctionTemplate the function template for which we are performing
2560/// template argument deduction.
2561///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002562/// \param ExplicitTemplateArguments the explicitly-specified template
2563/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002564///
2565/// \param ArgFunctionType the function type that will be used as the
2566/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002567/// function template's function type. This type may be NULL, if there is no
2568/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002569///
2570/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002571/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002572/// template argument deduction.
2573///
2574/// \param Info the argument will be updated to provide additional information
2575/// about template argument deduction.
2576///
2577/// \returns the result of template argument deduction.
2578Sema::TemplateDeductionResult
2579Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002580 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002581 QualType ArgFunctionType,
2582 FunctionDecl *&Specialization,
2583 TemplateDeductionInfo &Info) {
2584 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2585 TemplateParameterList *TemplateParams
2586 = FunctionTemplate->getTemplateParameters();
2587 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Douglas Gregor83314aa2009-07-08 20:55:45 +00002589 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002590 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002591 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2592 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002593 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002594 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002595 if (TemplateDeductionResult Result
2596 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002597 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002598 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002599 &FunctionType, Info))
2600 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002601
2602 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002603 }
2604
2605 // Template argument deduction for function templates in a SFINAE context.
2606 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002607 SFINAETrap Trap(*this);
2608
John McCalleff92132010-02-02 02:21:27 +00002609 Deduced.resize(TemplateParams->size());
2610
Douglas Gregor4b52e252009-12-21 23:17:24 +00002611 if (!ArgFunctionType.isNull()) {
2612 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002613 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002614 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002615 FunctionType, ArgFunctionType, Info,
2616 Deduced, 0))
2617 return Result;
2618 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002619
2620 if (TemplateDeductionResult Result
2621 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2622 NumExplicitlySpecified,
2623 Specialization, Info))
2624 return Result;
2625
2626 // If the requested function type does not match the actual type of the
2627 // specialization, template argument deduction fails.
2628 if (!ArgFunctionType.isNull() &&
2629 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2630 return TDK_NonDeducedMismatch;
2631
2632 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002633}
2634
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002635/// \brief Deduce template arguments for a templated conversion
2636/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2637/// conversion function template specialization.
2638Sema::TemplateDeductionResult
2639Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2640 QualType ToType,
2641 CXXConversionDecl *&Specialization,
2642 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002643 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002644 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2645 QualType FromType = Conv->getConversionType();
2646
2647 // Canonicalize the types for deduction.
2648 QualType P = Context.getCanonicalType(FromType);
2649 QualType A = Context.getCanonicalType(ToType);
2650
2651 // C++0x [temp.deduct.conv]p3:
2652 // If P is a reference type, the type referred to by P is used for
2653 // type deduction.
2654 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2655 P = PRef->getPointeeType();
2656
2657 // C++0x [temp.deduct.conv]p3:
2658 // If A is a reference type, the type referred to by A is used
2659 // for type deduction.
2660 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2661 A = ARef->getPointeeType();
2662 // C++ [temp.deduct.conv]p2:
2663 //
Mike Stump1eb44332009-09-09 15:08:12 +00002664 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002665 else {
2666 assert(!A->isReferenceType() && "Reference types were handled above");
2667
2668 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002669 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002670 // of P for type deduction; otherwise,
2671 if (P->isArrayType())
2672 P = Context.getArrayDecayedType(P);
2673 // - If P is a function type, the pointer type produced by the
2674 // function-to-pointer standard conversion (4.3) is used in
2675 // place of P for type deduction; otherwise,
2676 else if (P->isFunctionType())
2677 P = Context.getPointerType(P);
2678 // - If P is a cv-qualified type, the top level cv-qualifiers of
2679 // P’s type are ignored for type deduction.
2680 else
2681 P = P.getUnqualifiedType();
2682
2683 // C++0x [temp.deduct.conv]p3:
2684 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2685 // type are ignored for type deduction.
2686 A = A.getUnqualifiedType();
2687 }
2688
2689 // Template argument deduction for function templates in a SFINAE context.
2690 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002691 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002692
2693 // C++ [temp.deduct.conv]p1:
2694 // Template argument deduction is done by comparing the return
2695 // type of the template conversion function (call it P) with the
2696 // type that is required as the result of the conversion (call it
2697 // A) as described in 14.8.2.4.
2698 TemplateParameterList *TemplateParams
2699 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002700 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002701 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002702
2703 // C++0x [temp.deduct.conv]p4:
2704 // In general, the deduction process attempts to find template
2705 // argument values that will make the deduced A identical to
2706 // A. However, there are two cases that allow a difference:
2707 unsigned TDF = 0;
2708 // - If the original A is a reference type, A can be more
2709 // cv-qualified than the deduced A (i.e., the type referred to
2710 // by the reference)
2711 if (ToType->isReferenceType())
2712 TDF |= TDF_ParamWithReferenceType;
2713 // - The deduced A can be another pointer or pointer to member
2714 // type that can be converted to A via a qualification
2715 // conversion.
2716 //
2717 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2718 // both P and A are pointers or member pointers. In this case, we
2719 // just ignore cv-qualifiers completely).
2720 if ((P->isPointerType() && A->isPointerType()) ||
2721 (P->isMemberPointerType() && P->isMemberPointerType()))
2722 TDF |= TDF_IgnoreQualifiers;
2723 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002724 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002725 P, A, Info, Deduced, TDF))
2726 return Result;
2727
2728 // FIXME: we need to check that the deduced A is the same as A,
2729 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002730
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002731 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002732 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002733 FunctionDecl *Spec = 0;
2734 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002735 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2736 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002737 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2738 return Result;
2739}
2740
Douglas Gregor4b52e252009-12-21 23:17:24 +00002741/// \brief Deduce template arguments for a function template when there is
2742/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2743///
2744/// \param FunctionTemplate the function template for which we are performing
2745/// template argument deduction.
2746///
2747/// \param ExplicitTemplateArguments the explicitly-specified template
2748/// arguments.
2749///
2750/// \param Specialization if template argument deduction was successful,
2751/// this will be set to the function template specialization produced by
2752/// template argument deduction.
2753///
2754/// \param Info the argument will be updated to provide additional information
2755/// about template argument deduction.
2756///
2757/// \returns the result of template argument deduction.
2758Sema::TemplateDeductionResult
2759Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2760 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2761 FunctionDecl *&Specialization,
2762 TemplateDeductionInfo &Info) {
2763 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2764 QualType(), Specialization, Info);
2765}
2766
Douglas Gregor8a514912009-09-14 18:39:43 +00002767/// \brief Stores the result of comparing the qualifiers of two types.
2768enum DeductionQualifierComparison {
2769 NeitherMoreQualified = 0,
2770 ParamMoreQualified,
2771 ArgMoreQualified
2772};
2773
2774/// \brief Deduce the template arguments during partial ordering by comparing
2775/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2776///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002777/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002778///
2779/// \param TemplateParams the template parameters that we are deducing
2780///
2781/// \param ParamIn the parameter type
2782///
2783/// \param ArgIn the argument type
2784///
2785/// \param Info information about the template argument deduction itself
2786///
2787/// \param Deduced the deduced template arguments
2788///
2789/// \returns the result of template argument deduction so far. Note that a
2790/// "success" result means that template argument deduction has not yet failed,
2791/// but it may still fail, later, for other reasons.
2792static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002793DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002794 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002795 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002796 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002797 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2798 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002799 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2800 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002801
2802 // C++0x [temp.deduct.partial]p5:
2803 // Before the partial ordering is done, certain transformations are
2804 // performed on the types used for partial ordering:
2805 // - If P is a reference type, P is replaced by the type referred to.
2806 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002807 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002808 Param = ParamRef->getPointeeType();
2809
2810 // - If A is a reference type, A is replaced by the type referred to.
2811 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002812 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002813 Arg = ArgRef->getPointeeType();
2814
John McCalle27ec8a2009-10-23 23:03:21 +00002815 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002816 // C++0x [temp.deduct.partial]p6:
2817 // If both P and A were reference types (before being replaced with the
2818 // type referred to above), determine which of the two types (if any) is
2819 // more cv-qualified than the other; otherwise the types are considered to
2820 // be equally cv-qualified for partial ordering purposes. The result of this
2821 // determination will be used below.
2822 //
2823 // We save this information for later, using it only when deduction
2824 // succeeds in both directions.
2825 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2826 if (Param.isMoreQualifiedThan(Arg))
2827 QualifierResult = ParamMoreQualified;
2828 else if (Arg.isMoreQualifiedThan(Param))
2829 QualifierResult = ArgMoreQualified;
2830 QualifierComparisons->push_back(QualifierResult);
2831 }
2832
2833 // C++0x [temp.deduct.partial]p7:
2834 // Remove any top-level cv-qualifiers:
2835 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2836 // version of P.
2837 Param = Param.getUnqualifiedType();
2838 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2839 // version of A.
2840 Arg = Arg.getUnqualifiedType();
2841
2842 // C++0x [temp.deduct.partial]p8:
2843 // Using the resulting types P and A the deduction is then done as
2844 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2845 // from the argument template is considered to be at least as specialized
2846 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002847 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002848 Deduced, TDF_None);
2849}
2850
2851static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002852MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2853 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002854 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002855 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002856
2857/// \brief If this is a non-static member function,
2858static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2859 CXXMethodDecl *Method,
2860 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2861 if (Method->isStatic())
2862 return;
2863
2864 // C++ [over.match.funcs]p4:
2865 //
2866 // For non-static member functions, the type of the implicit
2867 // object parameter is
2868 // — "lvalue reference to cv X" for functions declared without a
2869 // ref-qualifier or with the & ref-qualifier
2870 // - "rvalue reference to cv X" for functions declared with the
2871 // && ref-qualifier
2872 //
2873 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2874 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2875 ArgTy = Context.getQualifiedType(ArgTy,
2876 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2877 ArgTy = Context.getLValueReferenceType(ArgTy);
2878 ArgTypes.push_back(ArgTy);
2879}
2880
Douglas Gregor8a514912009-09-14 18:39:43 +00002881/// \brief Determine whether the function template \p FT1 is at least as
2882/// specialized as \p FT2.
2883static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002884 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002885 FunctionTemplateDecl *FT1,
2886 FunctionTemplateDecl *FT2,
2887 TemplatePartialOrderingContext TPOC,
2888 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2889 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2890 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2891 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2892 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2893
2894 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2895 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002896 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002897 Deduced.resize(TemplateParams->size());
2898
2899 // C++0x [temp.deduct.partial]p3:
2900 // The types used to determine the ordering depend on the context in which
2901 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002902 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002903 CXXMethodDecl *Method1 = 0;
2904 CXXMethodDecl *Method2 = 0;
2905 bool IsNonStatic2 = false;
2906 bool IsNonStatic1 = false;
2907 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002908 switch (TPOC) {
2909 case TPOC_Call: {
2910 // - In the context of a function call, the function parameter types are
2911 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002912 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2913 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2914 IsNonStatic1 = Method1 && !Method1->isStatic();
2915 IsNonStatic2 = Method2 && !Method2->isStatic();
2916
2917 // C++0x [temp.func.order]p3:
2918 // [...] If only one of the function templates is a non-static
2919 // member, that function template is considered to have a new
2920 // first parameter inserted in its function parameter list. The
2921 // new parameter is of type "reference to cv A," where cv are
2922 // the cv-qualifiers of the function template (if any) and A is
2923 // the class of which the function template is a member.
2924 //
2925 // C++98/03 doesn't have this provision, so instead we drop the
2926 // first argument of the free function or static member, which
2927 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002928 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002929 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2930 IsNonStatic2 && !IsNonStatic1;
2931 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002932 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2933 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002934 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002935
2936 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002937 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2938 IsNonStatic1 && !IsNonStatic2;
2939 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002940 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2941 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002942 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002943
2944 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002945 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002946 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002947 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002948 Args2[I],
2949 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002950 Info,
2951 Deduced,
2952 QualifierComparisons))
2953 return false;
2954
2955 break;
2956 }
2957
2958 case TPOC_Conversion:
2959 // - In the context of a call to a conversion operator, the return types
2960 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002961 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002962 TemplateParams,
2963 Proto2->getResultType(),
2964 Proto1->getResultType(),
2965 Info,
2966 Deduced,
2967 QualifierComparisons))
2968 return false;
2969 break;
2970
2971 case TPOC_Other:
2972 // - In other contexts (14.6.6.2) the function template’s function type
2973 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002974 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002975 TemplateParams,
2976 FD2->getType(),
2977 FD1->getType(),
2978 Info,
2979 Deduced,
2980 QualifierComparisons))
2981 return false;
2982 break;
2983 }
2984
2985 // C++0x [temp.deduct.partial]p11:
2986 // In most cases, all template parameters must have values in order for
2987 // deduction to succeed, but for partial ordering purposes a template
2988 // parameter may remain without a value provided it is not used in the
2989 // types being used for partial ordering. [ Note: a template parameter used
2990 // in a non-deduced context is considered used. -end note]
2991 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2992 for (; ArgIdx != NumArgs; ++ArgIdx)
2993 if (Deduced[ArgIdx].isNull())
2994 break;
2995
2996 if (ArgIdx == NumArgs) {
2997 // All template arguments were deduced. FT1 is at least as specialized
2998 // as FT2.
2999 return true;
3000 }
3001
Douglas Gregore73bb602009-09-14 21:25:05 +00003002 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003003 llvm::SmallVector<bool, 4> UsedParameters;
3004 UsedParameters.resize(TemplateParams->size());
3005 switch (TPOC) {
3006 case TPOC_Call: {
3007 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003008 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3009 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3010 TemplateParams->getDepth(), UsedParameters);
3011 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003012 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3013 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003014 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003015 break;
3016 }
3017
3018 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003019 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3020 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003021 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003022 break;
3023
3024 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003025 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3026 TemplateParams->getDepth(),
3027 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003028 break;
3029 }
3030
3031 for (; ArgIdx != NumArgs; ++ArgIdx)
3032 // If this argument had no value deduced but was used in one of the types
3033 // used for partial ordering, then deduction fails.
3034 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3035 return false;
3036
3037 return true;
3038}
3039
3040
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003041/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003042/// to the rules of function template partial ordering (C++ [temp.func.order]).
3043///
3044/// \param FT1 the first function template
3045///
3046/// \param FT2 the second function template
3047///
Douglas Gregor8a514912009-09-14 18:39:43 +00003048/// \param TPOC the context in which we are performing partial ordering of
3049/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003050///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003051/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003052/// template is more specialized, returns NULL.
3053FunctionTemplateDecl *
3054Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3055 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003056 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003057 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003058 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00003059 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
3060 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00003061 &QualifierComparisons);
3062
3063 if (Better1 != Better2) // We have a clear winner
3064 return Better1? FT1 : FT2;
3065
3066 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003067 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003068
3069
3070 // C++0x [temp.deduct.partial]p10:
3071 // If for each type being considered a given template is at least as
3072 // specialized for all types and more specialized for some set of types and
3073 // the other template is not more specialized for any types or is not at
3074 // least as specialized for any types, then the given template is more
3075 // specialized than the other template. Otherwise, neither template is more
3076 // specialized than the other.
3077 Better1 = false;
3078 Better2 = false;
3079 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3080 // C++0x [temp.deduct.partial]p9:
3081 // If, for a given type, deduction succeeds in both directions (i.e., the
3082 // types are identical after the transformations above) and if the type
3083 // from the argument template is more cv-qualified than the type from the
3084 // parameter template (as described above) that type is considered to be
3085 // more specialized than the other. If neither type is more cv-qualified
3086 // than the other then neither type is more specialized than the other.
3087 switch (QualifierComparisons[I]) {
3088 case NeitherMoreQualified:
3089 break;
3090
3091 case ParamMoreQualified:
3092 Better1 = true;
3093 if (Better2)
3094 return 0;
3095 break;
3096
3097 case ArgMoreQualified:
3098 Better2 = true;
3099 if (Better1)
3100 return 0;
3101 break;
3102 }
3103 }
3104
3105 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003106 if (Better1)
3107 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003108 else if (Better2)
3109 return FT2;
3110 else
3111 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003112}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003113
Douglas Gregord5a423b2009-09-25 18:43:00 +00003114/// \brief Determine if the two templates are equivalent.
3115static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3116 if (T1 == T2)
3117 return true;
3118
3119 if (!T1 || !T2)
3120 return false;
3121
3122 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3123}
3124
3125/// \brief Retrieve the most specialized of the given function template
3126/// specializations.
3127///
John McCallc373d482010-01-27 01:50:18 +00003128/// \param SpecBegin the start iterator of the function template
3129/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003130///
John McCallc373d482010-01-27 01:50:18 +00003131/// \param SpecEnd the end iterator of the function template
3132/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003133///
3134/// \param TPOC the partial ordering context to use to compare the function
3135/// template specializations.
3136///
3137/// \param Loc the location where the ambiguity or no-specializations
3138/// diagnostic should occur.
3139///
3140/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3141/// no matching candidates.
3142///
3143/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3144/// occurs.
3145///
3146/// \param CandidateDiag partial diagnostic used for each function template
3147/// specialization that is a candidate in the ambiguous ordering. One parameter
3148/// in this diagnostic should be unbound, which will correspond to the string
3149/// describing the template arguments for the function template specialization.
3150///
3151/// \param Index if non-NULL and the result of this function is non-nULL,
3152/// receives the index corresponding to the resulting function template
3153/// specialization.
3154///
3155/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003156/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003157///
3158/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3159/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003160UnresolvedSetIterator
3161Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3162 UnresolvedSetIterator SpecEnd,
3163 TemplatePartialOrderingContext TPOC,
3164 SourceLocation Loc,
3165 const PartialDiagnostic &NoneDiag,
3166 const PartialDiagnostic &AmbigDiag,
3167 const PartialDiagnostic &CandidateDiag) {
3168 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003169 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003170 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003171 }
3172
John McCallc373d482010-01-27 01:50:18 +00003173 if (SpecBegin + 1 == SpecEnd)
3174 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003175
3176 // Find the function template that is better than all of the templates it
3177 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003178 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003179 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003180 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003181 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003182 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3183 FunctionTemplateDecl *Challenger
3184 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003185 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003186 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003187 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003188 Challenger)) {
3189 Best = I;
3190 BestTemplate = Challenger;
3191 }
3192 }
3193
3194 // Make sure that the "best" function template is more specialized than all
3195 // of the others.
3196 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003197 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3198 FunctionTemplateDecl *Challenger
3199 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003200 if (I != Best &&
3201 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003202 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003203 BestTemplate)) {
3204 Ambiguous = true;
3205 break;
3206 }
3207 }
3208
3209 if (!Ambiguous) {
3210 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003211 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003212 }
3213
3214 // Diagnose the ambiguity.
3215 Diag(Loc, AmbigDiag);
3216
3217 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003218 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3219 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003220 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003221 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3222 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003223
John McCallc373d482010-01-27 01:50:18 +00003224 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003225}
3226
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003227/// \brief Returns the more specialized class template partial specialization
3228/// according to the rules of partial ordering of class template partial
3229/// specializations (C++ [temp.class.order]).
3230///
3231/// \param PS1 the first class template partial specialization
3232///
3233/// \param PS2 the second class template partial specialization
3234///
3235/// \returns the more specialized class template partial specialization. If
3236/// neither partial specialization is more specialized, returns NULL.
3237ClassTemplatePartialSpecializationDecl *
3238Sema::getMoreSpecializedPartialSpecialization(
3239 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003240 ClassTemplatePartialSpecializationDecl *PS2,
3241 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003242 // C++ [temp.class.order]p1:
3243 // For two class template partial specializations, the first is at least as
3244 // specialized as the second if, given the following rewrite to two
3245 // function templates, the first function template is at least as
3246 // specialized as the second according to the ordering rules for function
3247 // templates (14.6.6.2):
3248 // - the first function template has the same template parameters as the
3249 // first partial specialization and has a single function parameter
3250 // whose type is a class template specialization with the template
3251 // arguments of the first partial specialization, and
3252 // - the second function template has the same template parameters as the
3253 // second partial specialization and has a single function parameter
3254 // whose type is a class template specialization with the template
3255 // arguments of the second partial specialization.
3256 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003257 // Rather than synthesize function templates, we merely perform the
3258 // equivalent partial ordering by performing deduction directly on
3259 // the template arguments of the class template partial
3260 // specializations. This computation is slightly simpler than the
3261 // general problem of function template partial ordering, because
3262 // class template partial specializations are more constrained. We
3263 // know that every template parameter is deducible from the class
3264 // template partial specialization's template arguments, for
3265 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003266 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003267 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003268
3269 QualType PT1 = PS1->getInjectedSpecializationType();
3270 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003271
3272 // Determine whether PS1 is at least as specialized as PS2
3273 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003274 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003275 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003276 PT2,
3277 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003278 Info,
3279 Deduced,
3280 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003281 if (Better1) {
3282 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3283 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003284 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3285 PS1->getTemplateArgs(),
3286 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003287 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003288
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003289 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003290 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003291 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003292 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003293 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003294 PT1,
3295 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003296 Info,
3297 Deduced,
3298 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003299 if (Better2) {
3300 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3301 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003302 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3303 PS2->getTemplateArgs(),
3304 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003305 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003306
3307 if (Better1 == Better2)
3308 return 0;
3309
3310 return Better1? PS1 : PS2;
3311}
3312
Mike Stump1eb44332009-09-09 15:08:12 +00003313static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003314MarkUsedTemplateParameters(Sema &SemaRef,
3315 const TemplateArgument &TemplateArg,
3316 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003317 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003318 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003319
Douglas Gregore73bb602009-09-14 21:25:05 +00003320/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003321/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003322static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003323MarkUsedTemplateParameters(Sema &SemaRef,
3324 const Expr *E,
3325 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003326 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003327 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003328 // We can deduce from a pack expansion.
3329 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3330 E = Expansion->getPattern();
3331
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003332 // Skip through any implicit casts we added while type-checking.
3333 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3334 E = ICE->getSubExpr();
3335
Douglas Gregore73bb602009-09-14 21:25:05 +00003336 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3337 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003338 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003339 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003340 return;
3341
Mike Stump1eb44332009-09-09 15:08:12 +00003342 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003343 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3344 if (!NTTP)
3345 return;
3346
Douglas Gregored9c0f92009-10-29 00:04:11 +00003347 if (NTTP->getDepth() == Depth)
3348 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003349}
3350
Douglas Gregore73bb602009-09-14 21:25:05 +00003351/// \brief Mark the template parameters that are used by the given
3352/// nested name specifier.
3353static void
3354MarkUsedTemplateParameters(Sema &SemaRef,
3355 NestedNameSpecifier *NNS,
3356 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003357 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003358 llvm::SmallVectorImpl<bool> &Used) {
3359 if (!NNS)
3360 return;
3361
Douglas Gregored9c0f92009-10-29 00:04:11 +00003362 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3363 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003364 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003365 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003366}
3367
3368/// \brief Mark the template parameters that are used by the given
3369/// template name.
3370static void
3371MarkUsedTemplateParameters(Sema &SemaRef,
3372 TemplateName Name,
3373 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003374 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003375 llvm::SmallVectorImpl<bool> &Used) {
3376 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3377 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003378 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3379 if (TTP->getDepth() == Depth)
3380 Used[TTP->getIndex()] = true;
3381 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003382 return;
3383 }
3384
Douglas Gregor788cd062009-11-11 01:00:40 +00003385 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3386 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3387 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003388 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003389 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3390 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003391}
3392
3393/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003394/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003395static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003396MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3397 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003398 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003399 llvm::SmallVectorImpl<bool> &Used) {
3400 if (T.isNull())
3401 return;
3402
Douglas Gregor031a5882009-06-13 00:26:55 +00003403 // Non-dependent types have nothing deducible
3404 if (!T->isDependentType())
3405 return;
3406
3407 T = SemaRef.Context.getCanonicalType(T);
3408 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003409 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003410 MarkUsedTemplateParameters(SemaRef,
3411 cast<PointerType>(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::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003418 MarkUsedTemplateParameters(SemaRef,
3419 cast<BlockPointerType>(T)->getPointeeType(),
3420 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003421 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003422 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003423 break;
3424
3425 case Type::LValueReference:
3426 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003427 MarkUsedTemplateParameters(SemaRef,
3428 cast<ReferenceType>(T)->getPointeeType(),
3429 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003430 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003431 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003432 break;
3433
3434 case Type::MemberPointer: {
3435 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003436 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003437 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003438 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003439 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003440 break;
3441 }
3442
3443 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003444 MarkUsedTemplateParameters(SemaRef,
3445 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003446 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003447 // Fall through to check the element type
3448
3449 case Type::ConstantArray:
3450 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003451 MarkUsedTemplateParameters(SemaRef,
3452 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003453 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003454 break;
3455
3456 case Type::Vector:
3457 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003458 MarkUsedTemplateParameters(SemaRef,
3459 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003460 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003461 break;
3462
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003463 case Type::DependentSizedExtVector: {
3464 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003465 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003466 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003467 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003468 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003469 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003470 break;
3471 }
3472
Douglas Gregor031a5882009-06-13 00:26:55 +00003473 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003474 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003475 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003476 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003477 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003478 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003479 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003480 break;
3481 }
3482
Douglas Gregored9c0f92009-10-29 00:04:11 +00003483 case Type::TemplateTypeParm: {
3484 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3485 if (TTP->getDepth() == Depth)
3486 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003487 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003488 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003489
John McCall31f17ec2010-04-27 00:57:59 +00003490 case Type::InjectedClassName:
3491 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3492 // fall through
3493
Douglas Gregor031a5882009-06-13 00:26:55 +00003494 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003495 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003496 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003497 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003498 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003499
3500 // C++0x [temp.deduct.type]p9:
3501 // If the template argument list of P contains a pack expansion that is not
3502 // the last template argument, the entire template argument list is a
3503 // non-deduced context.
3504 if (OnlyDeduced &&
3505 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3506 break;
3507
Douglas Gregore73bb602009-09-14 21:25:05 +00003508 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003509 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3510 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003511 break;
3512 }
3513
Douglas Gregore73bb602009-09-14 21:25:05 +00003514 case Type::Complex:
3515 if (!OnlyDeduced)
3516 MarkUsedTemplateParameters(SemaRef,
3517 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003518 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003519 break;
3520
Douglas Gregor4714c122010-03-31 17:34:00 +00003521 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003522 if (!OnlyDeduced)
3523 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003524 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003525 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003526 break;
3527
John McCall33500952010-06-11 00:33:02 +00003528 case Type::DependentTemplateSpecialization: {
3529 const DependentTemplateSpecializationType *Spec
3530 = cast<DependentTemplateSpecializationType>(T);
3531 if (!OnlyDeduced)
3532 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3533 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003534
3535 // C++0x [temp.deduct.type]p9:
3536 // If the template argument list of P contains a pack expansion that is not
3537 // the last template argument, the entire template argument list is a
3538 // non-deduced context.
3539 if (OnlyDeduced &&
3540 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3541 break;
3542
John McCall33500952010-06-11 00:33:02 +00003543 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3544 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3545 Used);
3546 break;
3547 }
3548
John McCallad5e7382010-03-01 23:49:17 +00003549 case Type::TypeOf:
3550 if (!OnlyDeduced)
3551 MarkUsedTemplateParameters(SemaRef,
3552 cast<TypeOfType>(T)->getUnderlyingType(),
3553 OnlyDeduced, Depth, Used);
3554 break;
3555
3556 case Type::TypeOfExpr:
3557 if (!OnlyDeduced)
3558 MarkUsedTemplateParameters(SemaRef,
3559 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3560 OnlyDeduced, Depth, Used);
3561 break;
3562
3563 case Type::Decltype:
3564 if (!OnlyDeduced)
3565 MarkUsedTemplateParameters(SemaRef,
3566 cast<DecltypeType>(T)->getUnderlyingExpr(),
3567 OnlyDeduced, Depth, Used);
3568 break;
3569
Douglas Gregor7536dd52010-12-20 02:24:11 +00003570 case Type::PackExpansion:
3571 MarkUsedTemplateParameters(SemaRef,
3572 cast<PackExpansionType>(T)->getPattern(),
3573 OnlyDeduced, Depth, Used);
3574 break;
3575
Douglas Gregore73bb602009-09-14 21:25:05 +00003576 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003577 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003578 case Type::VariableArray:
3579 case Type::FunctionNoProto:
3580 case Type::Record:
3581 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003582 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003583 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003584 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003585 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003586#define TYPE(Class, Base)
3587#define ABSTRACT_TYPE(Class, Base)
3588#define DEPENDENT_TYPE(Class, Base)
3589#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3590#include "clang/AST/TypeNodes.def"
3591 break;
3592 }
3593}
3594
Douglas Gregore73bb602009-09-14 21:25:05 +00003595/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003596/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003597static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003598MarkUsedTemplateParameters(Sema &SemaRef,
3599 const TemplateArgument &TemplateArg,
3600 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003601 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003602 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003603 switch (TemplateArg.getKind()) {
3604 case TemplateArgument::Null:
3605 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003606 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003607 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003608
Douglas Gregor031a5882009-06-13 00:26:55 +00003609 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003610 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003611 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003612 break;
3613
Douglas Gregor788cd062009-11-11 01:00:40 +00003614 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003615 case TemplateArgument::TemplateExpansion:
3616 MarkUsedTemplateParameters(SemaRef,
3617 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003618 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003619 break;
3620
3621 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003622 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003623 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003624 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003625
Anders Carlssond01b1da2009-06-15 17:04:53 +00003626 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003627 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3628 PEnd = TemplateArg.pack_end();
3629 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003630 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003631 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003632 }
3633}
3634
3635/// \brief Mark the template parameters can be deduced by the given
3636/// template argument list.
3637///
3638/// \param TemplateArgs the template argument list from which template
3639/// parameters will be deduced.
3640///
3641/// \param Deduced a bit vector whose elements will be set to \c true
3642/// to indicate when the corresponding template parameter will be
3643/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003644void
Douglas Gregore73bb602009-09-14 21:25:05 +00003645Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003646 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003647 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003648 // C++0x [temp.deduct.type]p9:
3649 // If the template argument list of P contains a pack expansion that is not
3650 // the last template argument, the entire template argument list is a
3651 // non-deduced context.
3652 if (OnlyDeduced &&
3653 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3654 return;
3655
Douglas Gregor031a5882009-06-13 00:26:55 +00003656 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003657 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3658 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003659}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003660
3661/// \brief Marks all of the template parameters that will be deduced by a
3662/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003663void
3664Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3665 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003666 TemplateParameterList *TemplateParams
3667 = FunctionTemplate->getTemplateParameters();
3668 Deduced.clear();
3669 Deduced.resize(TemplateParams->size());
3670
3671 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3672 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3673 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003674 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003675}