blob: 1bc24db27aa1f836b1219191fa2a698a0cf18054 [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregor20a55e22010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
Douglas Gregore02e2622010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000026
27namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregor508f1c82009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
52 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor0b9247f2009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor9d0e4412010-03-26 05:50:28 +000058/// \brief Compare two APSInts, extending and switching the sign as
59/// necessary to compare their values regardless of underlying type.
60static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
61 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000065
66 // If there is a signedness mismatch, correct it.
67 if (X.isSigned() != Y.isSigned()) {
68 // If the signed value is negative, then the values cannot be the same.
69 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
70 return false;
71
72 Y.setIsSigned(true);
73 X.setIsSigned(true);
74 }
75
76 return X == Y;
77}
78
Douglas Gregorf67875d2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000083 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000086
Douglas Gregor20a55e22010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
Douglas Gregor603cfb42011-01-05 23:12:31 +000090 QualType Param,
91 QualType Arg,
92 TemplateDeductionInfo &Info,
93 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 unsigned TDF);
95
96static Sema::TemplateDeductionResult
97DeduceTemplateArguments(Sema &S,
98 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +000099 const TemplateArgument *Params, unsigned NumParams,
100 const TemplateArgument *Args, unsigned NumArgs,
101 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000102 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
103 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000104
Douglas Gregor199d9912009-06-05 00:53:49 +0000105/// \brief If the given expression is of a form that permits the deduction
106/// of a non-type template parameter, return the declaration of that
107/// non-type template parameter.
108static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
109 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
110 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Douglas Gregor199d9912009-06-05 00:53:49 +0000112 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
113 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Douglas Gregor199d9912009-06-05 00:53:49 +0000115 return 0;
116}
117
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000118/// \brief Determine whether two declaration pointers refer to the same
119/// declaration.
120static bool isSameDeclaration(Decl *X, Decl *Y) {
121 if (!X || !Y)
122 return !X && !Y;
123
124 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
125 X = NX->getUnderlyingDecl();
126 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
127 Y = NY->getUnderlyingDecl();
128
129 return X->getCanonicalDecl() == Y->getCanonicalDecl();
130}
131
132/// \brief Verify that the given, deduced template arguments are compatible.
133///
134/// \returns The deduced template argument, or a NULL template argument if
135/// the deduced template arguments were incompatible.
136static DeducedTemplateArgument
137checkDeducedTemplateArguments(ASTContext &Context,
138 const DeducedTemplateArgument &X,
139 const DeducedTemplateArgument &Y) {
140 // We have no deduction for one or both of the arguments; they're compatible.
141 if (X.isNull())
142 return Y;
143 if (Y.isNull())
144 return X;
145
146 switch (X.getKind()) {
147 case TemplateArgument::Null:
148 llvm_unreachable("Non-deduced template arguments handled above");
149
150 case TemplateArgument::Type:
151 // If two template type arguments have the same type, they're compatible.
152 if (Y.getKind() == TemplateArgument::Type &&
153 Context.hasSameType(X.getAsType(), Y.getAsType()))
154 return X;
155
156 return DeducedTemplateArgument();
157
158 case TemplateArgument::Integral:
159 // If we deduced a constant in one case and either a dependent expression or
160 // declaration in another case, keep the integral constant.
161 // If both are integral constants with the same value, keep that value.
162 if (Y.getKind() == TemplateArgument::Expression ||
163 Y.getKind() == TemplateArgument::Declaration ||
164 (Y.getKind() == TemplateArgument::Integral &&
165 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
166 return DeducedTemplateArgument(X,
167 X.wasDeducedFromArrayBound() &&
168 Y.wasDeducedFromArrayBound());
169
170 // All other combinations are incompatible.
171 return DeducedTemplateArgument();
172
173 case TemplateArgument::Template:
174 if (Y.getKind() == TemplateArgument::Template &&
175 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
176 return X;
177
178 // All other combinations are incompatible.
179 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000180
181 case TemplateArgument::TemplateExpansion:
182 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
183 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
184 Y.getAsTemplateOrTemplatePattern()))
185 return X;
186
187 // All other combinations are incompatible.
188 return DeducedTemplateArgument();
189
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000190 case TemplateArgument::Expression:
191 // If we deduced a dependent expression in one case and either an integral
192 // constant or a declaration in another case, keep the integral constant
193 // or declaration.
194 if (Y.getKind() == TemplateArgument::Integral ||
195 Y.getKind() == TemplateArgument::Declaration)
196 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
197 Y.wasDeducedFromArrayBound());
198
199 if (Y.getKind() == TemplateArgument::Expression) {
200 // Compare the expressions for equality
201 llvm::FoldingSetNodeID ID1, ID2;
202 X.getAsExpr()->Profile(ID1, Context, true);
203 Y.getAsExpr()->Profile(ID2, Context, true);
204 if (ID1 == ID2)
205 return X;
206 }
207
208 // All other combinations are incompatible.
209 return DeducedTemplateArgument();
210
211 case TemplateArgument::Declaration:
212 // If we deduced a declaration and a dependent expression, keep the
213 // declaration.
214 if (Y.getKind() == TemplateArgument::Expression)
215 return X;
216
217 // If we deduced a declaration and an integral constant, keep the
218 // integral constant.
219 if (Y.getKind() == TemplateArgument::Integral)
220 return Y;
221
222 // If we deduced two declarations, make sure they they refer to the
223 // same declaration.
224 if (Y.getKind() == TemplateArgument::Declaration &&
225 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
226 return X;
227
228 // All other combinations are incompatible.
229 return DeducedTemplateArgument();
230
231 case TemplateArgument::Pack:
232 if (Y.getKind() != TemplateArgument::Pack ||
233 X.pack_size() != Y.pack_size())
234 return DeducedTemplateArgument();
235
236 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
237 XAEnd = X.pack_end(),
238 YA = Y.pack_begin();
239 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000240 if (checkDeducedTemplateArguments(Context,
241 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
242 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
243 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000244 return DeducedTemplateArgument();
245 }
246
247 return X;
248 }
249
250 return DeducedTemplateArgument();
251}
252
Mike Stump1eb44332009-09-09 15:08:12 +0000253/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000254/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000255static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000256DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000257 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000258 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000259 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000260 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000261 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000262 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000263 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000265 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
266 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
267 Deduced[NTTP->getIndex()],
268 NewDeduced);
269 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000270 Info.Param = NTTP;
271 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000272 Info.SecondArg = NewDeduced;
273 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000274 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000275
276 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000277 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000281/// from the given type- or value-dependent expression.
282///
283/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000284static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000285DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000286 NonTypeTemplateParmDecl *NTTP,
287 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000288 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000289 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000290 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000291 "Cannot deduce non-type template argument with depth > 0");
292 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
293 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000295 DeducedTemplateArgument NewDeduced(Value);
296 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
297 Deduced[NTTP->getIndex()],
298 NewDeduced);
299
300 if (Result.isNull()) {
301 Info.Param = NTTP;
302 Info.FirstArg = Deduced[NTTP->getIndex()];
303 Info.SecondArg = NewDeduced;
304 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000305 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000306
307 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000308 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000309}
310
Douglas Gregor15755cb2009-11-13 23:45:44 +0000311/// \brief Deduce the value of the given non-type template parameter
312/// from the given declaration.
313///
314/// \returns true if deduction succeeded, false otherwise.
315static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000316DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000317 NonTypeTemplateParmDecl *NTTP,
318 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000319 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000320 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000321 assert(NTTP->getDepth() == 0 &&
322 "Cannot deduce non-type template argument with depth > 0");
323
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000324 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
325 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
326 Deduced[NTTP->getIndex()],
327 NewDeduced);
328 if (Result.isNull()) {
329 Info.Param = NTTP;
330 Info.FirstArg = Deduced[NTTP->getIndex()];
331 Info.SecondArg = NewDeduced;
332 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000333 }
334
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000335 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000336 return Sema::TDK_Success;
337}
338
Douglas Gregorf67875d2009-06-12 18:26:56 +0000339static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000340DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000341 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000342 TemplateName Param,
343 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000344 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000345 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000346 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000347 if (!ParamDecl) {
348 // The parameter type is dependent and is not a template template parameter,
349 // so there is nothing that we can deduce.
350 return Sema::TDK_Success;
351 }
352
353 if (TemplateTemplateParmDecl *TempParam
354 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000355 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
356 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
357 Deduced[TempParam->getIndex()],
358 NewDeduced);
359 if (Result.isNull()) {
360 Info.Param = TempParam;
361 Info.FirstArg = Deduced[TempParam->getIndex()];
362 Info.SecondArg = NewDeduced;
363 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000364 }
365
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000366 Deduced[TempParam->getIndex()] = Result;
367 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000368 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000369
370 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000371 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000372 return Sema::TDK_Success;
373
374 // Mismatch of non-dependent template parameter to argument.
375 Info.FirstArg = TemplateArgument(Param);
376 Info.SecondArg = TemplateArgument(Arg);
377 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000378}
379
Mike Stump1eb44332009-09-09 15:08:12 +0000380/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000381/// type (which is a template-id) with the template argument type.
382///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000383/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000384///
385/// \param TemplateParams the template parameters that we are deducing
386///
387/// \param Param the parameter type
388///
389/// \param Arg the argument type
390///
391/// \param Info information about the template argument deduction itself
392///
393/// \param Deduced the deduced template arguments
394///
395/// \returns the result of template argument deduction so far. Note that a
396/// "success" result means that template argument deduction has not yet failed,
397/// but it may still fail, later, for other reasons.
398static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000399DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000400 TemplateParameterList *TemplateParams,
401 const TemplateSpecializationType *Param,
402 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000403 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000404 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000405 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000407 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000408 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000409 = dyn_cast<TemplateSpecializationType>(Arg)) {
410 // Perform template argument deduction for the template name.
411 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000412 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000413 Param->getTemplateName(),
414 SpecArg->getTemplateName(),
415 Info, Deduced))
416 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000419 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000420 // argument. Ignore any missing/extra arguments, since they could be
421 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000422 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000423 Param->getArgs(), Param->getNumArgs(),
424 SpecArg->getArgs(), SpecArg->getNumArgs(),
425 Info, Deduced,
426 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000429 // If the argument type is a class template specialization, we
430 // perform template argument deduction using its template
431 // arguments.
432 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
433 if (!RecordArg)
434 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
436 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000437 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
438 if (!SpecArg)
439 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000441 // Perform template argument deduction for the template name.
442 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000443 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000444 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000445 Param->getTemplateName(),
446 TemplateName(SpecArg->getSpecializedTemplate()),
447 Info, Deduced))
448 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Douglas Gregor20a55e22010-12-22 18:17:10 +0000450 // Perform template argument deduction for the template arguments.
451 return DeduceTemplateArguments(S, TemplateParams,
452 Param->getArgs(), Param->getNumArgs(),
453 SpecArg->getTemplateArgs().data(),
454 SpecArg->getTemplateArgs().size(),
455 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000456}
457
John McCallcd05e812010-08-28 22:14:41 +0000458/// \brief Determines whether the given type is an opaque type that
459/// might be more qualified when instantiated.
460static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
461 switch (T->getTypeClass()) {
462 case Type::TypeOfExpr:
463 case Type::TypeOf:
464 case Type::DependentName:
465 case Type::Decltype:
466 case Type::UnresolvedUsing:
467 return true;
468
469 case Type::ConstantArray:
470 case Type::IncompleteArray:
471 case Type::VariableArray:
472 case Type::DependentSizedArray:
473 return IsPossiblyOpaquelyQualifiedType(
474 cast<ArrayType>(T)->getElementType());
475
476 default:
477 return false;
478 }
479}
480
Douglas Gregord3731192011-01-10 07:32:04 +0000481/// \brief Retrieve the depth and index of a template parameter.
Douglas Gregor603cfb42011-01-05 23:12:31 +0000482static std::pair<unsigned, unsigned>
Douglas Gregord3731192011-01-10 07:32:04 +0000483getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor603cfb42011-01-05 23:12:31 +0000484 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
485 return std::make_pair(TTP->getDepth(), TTP->getIndex());
486
487 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
488 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
489
490 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
491 return std::make_pair(TTP->getDepth(), TTP->getIndex());
492}
493
Douglas Gregord3731192011-01-10 07:32:04 +0000494/// \brief Retrieve the depth and index of an unexpanded parameter pack.
495static std::pair<unsigned, unsigned>
496getDepthAndIndex(UnexpandedParameterPack UPP) {
497 if (const TemplateTypeParmType *TTP
498 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
499 return std::make_pair(TTP->getDepth(), TTP->getIndex());
500
501 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
502}
503
Douglas Gregor603cfb42011-01-05 23:12:31 +0000504/// \brief Helper function to build a TemplateParameter when we don't
505/// know its type statically.
506static TemplateParameter makeTemplateParameter(Decl *D) {
507 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
508 return TemplateParameter(TTP);
509 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
510 return TemplateParameter(NTTP);
511
512 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
513}
514
Douglas Gregor54293852011-01-10 17:35:05 +0000515/// \brief Prepare to perform template argument deduction for all of the
516/// arguments in a set of argument packs.
517static void PrepareArgumentPackDeduction(Sema &S,
518 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
519 const llvm::SmallVectorImpl<unsigned> &PackIndices,
520 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
521 llvm::SmallVectorImpl<
522 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks) {
523 // Save the deduced template arguments for each parameter pack expanded
524 // by this pack expansion, then clear out the deduction.
525 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
526 // Save the previously-deduced argument pack, then clear it out so that we
527 // can deduce a new argument pack.
528 SavedPacks[I] = Deduced[PackIndices[I]];
529 Deduced[PackIndices[I]] = TemplateArgument();
530
531 // If the template arugment pack was explicitly specified, add that to
532 // the set of deduced arguments.
533 const TemplateArgument *ExplicitArgs;
534 unsigned NumExplicitArgs;
535 if (NamedDecl *PartiallySubstitutedPack
536 = S.CurrentInstantiationScope->getPartiallySubstitutedPack(
537 &ExplicitArgs,
538 &NumExplicitArgs)) {
539 if (getDepthAndIndex(PartiallySubstitutedPack).second == PackIndices[I])
540 NewlyDeducedPacks[I].append(ExplicitArgs,
541 ExplicitArgs + NumExplicitArgs);
542 }
543 }
544}
545
Douglas Gregor0216f812011-01-10 17:53:52 +0000546/// \brief Finish template argument deduction for a set of argument packs,
547/// producing the argument packs and checking for consistency with prior
548/// deductions.
549static Sema::TemplateDeductionResult
550FinishArgumentPackDeduction(Sema &S,
551 TemplateParameterList *TemplateParams,
552 bool HasAnyArguments,
553 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
554 const llvm::SmallVectorImpl<unsigned> &PackIndices,
555 llvm::SmallVectorImpl<DeducedTemplateArgument> &SavedPacks,
556 llvm::SmallVectorImpl<
557 llvm::SmallVector<DeducedTemplateArgument, 4> > &NewlyDeducedPacks,
558 TemplateDeductionInfo &Info) {
559 // Build argument packs for each of the parameter packs expanded by this
560 // pack expansion.
561 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
562 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
563 // We were not able to deduce anything for this parameter pack,
564 // so just restore the saved argument pack.
565 Deduced[PackIndices[I]] = SavedPacks[I];
566 continue;
567 }
568
569 DeducedTemplateArgument NewPack;
570
571 if (NewlyDeducedPacks[I].empty()) {
572 // If we deduced an empty argument pack, create it now.
573 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
574 } else {
575 TemplateArgument *ArgumentPack
576 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
577 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
578 ArgumentPack);
579 NewPack
580 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
581 NewlyDeducedPacks[I].size()),
582 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
583 }
584
585 DeducedTemplateArgument Result
586 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
587 if (Result.isNull()) {
588 Info.Param
589 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
590 Info.FirstArg = SavedPacks[I];
591 Info.SecondArg = NewPack;
592 return Sema::TDK_Inconsistent;
593 }
594
595 Deduced[PackIndices[I]] = Result;
596 }
597
598 return Sema::TDK_Success;
599}
600
Douglas Gregor603cfb42011-01-05 23:12:31 +0000601/// \brief Deduce the template arguments by comparing the list of parameter
602/// types to the list of argument types, as in the parameter-type-lists of
603/// function types (C++ [temp.deduct.type]p10).
604///
605/// \param S The semantic analysis object within which we are deducing
606///
607/// \param TemplateParams The template parameters that we are deducing
608///
609/// \param Params The list of parameter types
610///
611/// \param NumParams The number of types in \c Params
612///
613/// \param Args The list of argument types
614///
615/// \param NumArgs The number of types in \c Args
616///
617/// \param Info information about the template argument deduction itself
618///
619/// \param Deduced the deduced template arguments
620///
621/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
622/// how template argument deduction is performed.
623///
624/// \returns the result of template argument deduction so far. Note that a
625/// "success" result means that template argument deduction has not yet failed,
626/// but it may still fail, later, for other reasons.
627static Sema::TemplateDeductionResult
628DeduceTemplateArguments(Sema &S,
629 TemplateParameterList *TemplateParams,
630 const QualType *Params, unsigned NumParams,
631 const QualType *Args, unsigned NumArgs,
632 TemplateDeductionInfo &Info,
633 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
634 unsigned TDF) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000635 // Fast-path check to see if we have too many/too few arguments.
636 if (NumParams != NumArgs &&
637 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
638 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000639 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000640
641 // C++0x [temp.deduct.type]p10:
642 // Similarly, if P has a form that contains (T), then each parameter type
643 // Pi of the respective parameter-type- list of P is compared with the
644 // corresponding parameter type Ai of the corresponding parameter-type-list
645 // of A. [...]
646 unsigned ArgIdx = 0, ParamIdx = 0;
647 for (; ParamIdx != NumParams; ++ParamIdx) {
648 // Check argument types.
649 const PackExpansionType *Expansion
650 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
651 if (!Expansion) {
652 // Simple case: compare the parameter and argument types at this point.
653
654 // Make sure we have an argument.
655 if (ArgIdx >= NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000656 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000657
658 if (Sema::TemplateDeductionResult Result
659 = DeduceTemplateArguments(S, TemplateParams,
660 Params[ParamIdx],
661 Args[ArgIdx],
662 Info, Deduced, TDF))
663 return Result;
664
665 ++ArgIdx;
666 continue;
667 }
668
Douglas Gregor7d5c0c12011-01-11 01:52:23 +0000669 // C++0x [temp.deduct.type]p5:
670 // The non-deduced contexts are:
671 // - A function parameter pack that does not occur at the end of the
672 // parameter-declaration-clause.
673 if (ParamIdx + 1 < NumParams)
674 return Sema::TDK_Success;
675
Douglas Gregor603cfb42011-01-05 23:12:31 +0000676 // C++0x [temp.deduct.type]p10:
677 // If the parameter-declaration corresponding to Pi is a function
678 // parameter pack, then the type of its declarator- id is compared with
679 // each remaining parameter type in the parameter-type-list of A. Each
680 // comparison deduces template arguments for subsequent positions in the
681 // template parameter packs expanded by the function parameter pack.
682
683 // Compute the set of template parameter indices that correspond to
684 // parameter packs expanded by the pack expansion.
685 llvm::SmallVector<unsigned, 2> PackIndices;
686 QualType Pattern = Expansion->getPattern();
687 {
688 llvm::BitVector SawIndices(TemplateParams->size());
689 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
690 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
691 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
692 unsigned Depth, Index;
693 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
694 if (Depth == 0 && !SawIndices[Index]) {
695 SawIndices[Index] = true;
696 PackIndices.push_back(Index);
697 }
698 }
699 }
700 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
701
Douglas Gregord3731192011-01-10 07:32:04 +0000702 // Keep track of the deduced template arguments for each parameter pack
703 // expanded by this pack expansion (the outer index) and for each
704 // template argument (the inner SmallVectors).
705 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
706 NewlyDeducedPacks(PackIndices.size());
Douglas Gregor603cfb42011-01-05 23:12:31 +0000707 llvm::SmallVector<DeducedTemplateArgument, 2>
Douglas Gregor54293852011-01-10 17:35:05 +0000708 SavedPacks(PackIndices.size());
709 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
710 NewlyDeducedPacks);
Douglas Gregor603cfb42011-01-05 23:12:31 +0000711
Douglas Gregor603cfb42011-01-05 23:12:31 +0000712 bool HasAnyArguments = false;
713 for (; ArgIdx < NumArgs; ++ArgIdx) {
714 HasAnyArguments = true;
715
716 // Deduce template arguments from the pattern.
717 if (Sema::TemplateDeductionResult Result
718 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
719 Info, Deduced))
720 return Result;
721
722 // Capture the deduced template arguments for each parameter pack expanded
723 // by this pack expansion, add them to the list of arguments we've deduced
724 // for that pack, then clear out the deduced argument.
725 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
726 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
727 if (!DeducedArg.isNull()) {
728 NewlyDeducedPacks[I].push_back(DeducedArg);
729 DeducedArg = DeducedTemplateArgument();
730 }
731 }
732 }
733
734 // Build argument packs for each of the parameter packs expanded by this
735 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +0000736 if (Sema::TemplateDeductionResult Result
737 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
738 Deduced, PackIndices, SavedPacks,
739 NewlyDeducedPacks, Info))
740 return Result;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000741 }
742
743 // Make sure we don't have any extra arguments.
744 if (ArgIdx < NumArgs)
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000745 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000746
747 return Sema::TDK_Success;
748}
749
Douglas Gregor500d3312009-06-26 18:27:22 +0000750/// \brief Deduce the template arguments by comparing the parameter type and
751/// the argument type (C++ [temp.deduct.type]).
752///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000753/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000754///
755/// \param TemplateParams the template parameters that we are deducing
756///
757/// \param ParamIn the parameter type
758///
759/// \param ArgIn the argument type
760///
761/// \param Info information about the template argument deduction itself
762///
763/// \param Deduced the deduced template arguments
764///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000765/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000766/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000767///
768/// \returns the result of template argument deduction so far. Note that a
769/// "success" result means that template argument deduction has not yet failed,
770/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000771static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000772DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000773 TemplateParameterList *TemplateParams,
774 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000775 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000776 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000777 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000778 // We only want to look at the canonical types, since typedefs and
779 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000780 QualType Param = S.Context.getCanonicalType(ParamIn);
781 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000782
Douglas Gregor500d3312009-06-26 18:27:22 +0000783 // C++0x [temp.deduct.call]p4 bullet 1:
784 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000785 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000786 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000787 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000788 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000789 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000790 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
791 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000792 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000793 }
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000795 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000796 if (!Param->isDependentType()) {
Douglas Gregor3cae5c92011-01-10 20:53:55 +0000797 if (!(TDF & TDF_SkipNonDependent) && Param != Arg)
Douglas Gregor12820292009-09-14 20:00:47 +0000798 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor12820292009-09-14 20:00:47 +0000799
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000800 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000801 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000802
Douglas Gregor199d9912009-06-05 00:53:49 +0000803 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000804 // A template type argument T, a template template argument TT or a
805 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000806 // the following forms:
807 //
808 // T
809 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000810 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000811 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000812 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000813 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000815 // If the argument type is an array type, move the qualifiers up to the
816 // top level, so they can be matched with the qualifiers on the parameter.
817 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000818 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000819 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000820 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000821 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000822 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000823 RecanonicalizeArg = true;
824 }
825 }
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000827 // The argument type can not be less qualified than the parameter
828 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000829 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000830 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000831 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000832 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000833 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000834 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000835
836 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000837 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000838 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000839
840 // local manipulation is okay because it's canonical
841 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000842 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000843 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000845 DeducedTemplateArgument NewDeduced(DeducedType);
846 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
847 Deduced[Index],
848 NewDeduced);
849 if (Result.isNull()) {
850 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
851 Info.FirstArg = Deduced[Index];
852 Info.SecondArg = NewDeduced;
853 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000854 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000855
856 Deduced[Index] = Result;
857 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000858 }
859
Douglas Gregorf67875d2009-06-12 18:26:56 +0000860 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000861 Info.FirstArg = TemplateArgument(ParamIn);
862 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000863
Douglas Gregor508f1c82009-06-26 23:10:12 +0000864 // Check the cv-qualifiers on the parameter and argument types.
865 if (!(TDF & TDF_IgnoreQualifiers)) {
866 if (TDF & TDF_ParamWithReferenceType) {
867 if (Param.isMoreQualifiedThan(Arg))
868 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000869 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000870 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000871 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000872 }
873 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000874
Douglas Gregord560d502009-06-04 00:21:18 +0000875 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000876 // No deduction possible for these types
877 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000878 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Douglas Gregor199d9912009-06-05 00:53:49 +0000880 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000881 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000882 QualType PointeeType;
883 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
884 PointeeType = PointerArg->getPointeeType();
885 } else if (const ObjCObjectPointerType *PointerArg
886 = Arg->getAs<ObjCObjectPointerType>()) {
887 PointeeType = PointerArg->getPointeeType();
888 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000889 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000890 }
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Douglas Gregor41128772009-06-26 23:27:24 +0000892 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000893 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000894 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000895 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000896 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000897 }
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Douglas Gregor199d9912009-06-05 00:53:49 +0000899 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000900 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000901 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000902 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000903 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000905 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000906 cast<LValueReferenceType>(Param)->getPointeeType(),
907 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000908 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000909 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000910
Douglas Gregor199d9912009-06-05 00:53:49 +0000911 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000912 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000913 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000914 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000915 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000917 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000918 cast<RValueReferenceType>(Param)->getPointeeType(),
919 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000920 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregor199d9912009-06-05 00:53:49 +0000923 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000924 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000925 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000926 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000927 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000928 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000929
John McCalle4f26e52010-08-19 00:20:19 +0000930 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000931 return DeduceTemplateArguments(S, TemplateParams,
932 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000933 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000934 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000935 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000936
937 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000938 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000939 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000940 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000941 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000942 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000943
944 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000945 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000946 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000947 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000948
John McCalle4f26e52010-08-19 00:20:19 +0000949 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000950 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000951 ConstantArrayParm->getElementType(),
952 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000953 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000954 }
955
Douglas Gregor199d9912009-06-05 00:53:49 +0000956 // type [i]
957 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000958 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000959 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000960 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000961
John McCalle4f26e52010-08-19 00:20:19 +0000962 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
963
Douglas Gregor199d9912009-06-05 00:53:49 +0000964 // Check the element type of the arrays
965 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000966 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000967 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000968 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000969 DependentArrayParm->getElementType(),
970 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000971 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000972 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Douglas Gregor199d9912009-06-05 00:53:49 +0000974 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000975 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000976 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
977 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000978 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000979
980 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000981 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000982 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000983 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000984 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000985 = dyn_cast<ConstantArrayType>(ArrayArg)) {
986 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000987 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
988 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000989 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000990 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000991 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000992 if (const DependentSizedArrayType *DependentArrayArg
993 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000994 if (DependentArrayArg->getSizeExpr())
995 return DeduceNonTypeTemplateArgument(S, NTTP,
996 DependentArrayArg->getSizeExpr(),
997 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Douglas Gregor199d9912009-06-05 00:53:49 +0000999 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +00001000 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001001 }
Mike Stump1eb44332009-09-09 15:08:12 +00001002
1003 // type(*)(T)
1004 // T(*)()
1005 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +00001006 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +00001007 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +00001008 dyn_cast<FunctionProtoType>(Arg);
1009 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001010 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001011
1012 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +00001013 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001014
Mike Stump1eb44332009-09-09 15:08:12 +00001015 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001016 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001017 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001019 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +00001020 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +00001021
Anders Carlssona27fad52009-06-08 15:19:08 +00001022 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001023 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001024 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001025 FunctionProtoParam->getResultType(),
1026 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001027 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001028 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Douglas Gregor603cfb42011-01-05 23:12:31 +00001030 return DeduceTemplateArguments(S, TemplateParams,
1031 FunctionProtoParam->arg_type_begin(),
1032 FunctionProtoParam->getNumArgs(),
1033 FunctionProtoArg->arg_type_begin(),
1034 FunctionProtoArg->getNumArgs(),
1035 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +00001036 }
Mike Stump1eb44332009-09-09 15:08:12 +00001037
John McCall3cb0ebd2010-03-10 03:28:59 +00001038 case Type::InjectedClassName: {
1039 // Treat a template's injected-class-name as if the template
1040 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +00001041 Param = cast<InjectedClassNameType>(Param)
1042 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00001043 assert(isa<TemplateSpecializationType>(Param) &&
1044 "injected class name is not a template specialization type");
1045 // fall through
1046 }
1047
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001048 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +00001049 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001050 // TT<T>
1051 // TT<i>
1052 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +00001053 case Type::TemplateSpecialization: {
1054 const TemplateSpecializationType *SpecParam
1055 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001057 // Try to deduce template arguments from the template-id.
1058 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001059 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001060 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001062 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001063 // C++ [temp.deduct.call]p3b3:
1064 // If P is a class, and P has the form template-id, then A can be a
1065 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001066 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001067 // class pointed to by the deduced A.
1068 //
1069 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001070 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001071 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001072 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1073 // We cannot inspect base classes as part of deduction when the type
1074 // is incomplete, so either instantiate any templates necessary to
1075 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001076 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001077 return Result;
1078
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001079 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001080 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001081 // ToVisit is our stack of records that we still need to visit.
1082 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1083 llvm::SmallVector<const RecordType *, 8> ToVisit;
1084 ToVisit.push_back(RecordT);
1085 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001086 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1087 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001088 while (!ToVisit.empty()) {
1089 // Retrieve the next class in the inheritance hierarchy.
1090 const RecordType *NextT = ToVisit.back();
1091 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001093 // If we have already seen this type, skip it.
1094 if (!Visited.insert(NextT))
1095 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001097 // If this is a base class, try to perform template argument
1098 // deduction from it.
1099 if (NextT != RecordT) {
1100 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001101 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001102 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001104 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001105 // note that we had some success. Otherwise, ignore any deductions
1106 // from this base class.
1107 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001108 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001109 DeducedOrig = Deduced;
1110 }
1111 else
1112 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001113 }
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001115 // Visit base classes
1116 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1117 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1118 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001119 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001120 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001121 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001122 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001123 }
1124 }
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001126 if (Successful)
1127 return Sema::TDK_Success;
1128 }
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001130 }
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001132 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001133 }
1134
Douglas Gregor637a4092009-06-10 23:47:09 +00001135 // T type::*
1136 // T T::*
1137 // T (type::*)()
1138 // type (T::*)()
1139 // type (type::*)(T)
1140 // type (T::*)(T)
1141 // T (type::*)(T)
1142 // T (T::*)()
1143 // T (T::*)(T)
1144 case Type::MemberPointer: {
1145 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1146 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1147 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001148 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001149
Douglas Gregorf67875d2009-06-12 18:26:56 +00001150 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001151 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001152 MemPtrParam->getPointeeType(),
1153 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001154 Info, Deduced,
1155 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001156 return Result;
1157
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001158 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001159 QualType(MemPtrParam->getClass(), 0),
1160 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001161 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001162 }
1163
Anders Carlsson9a917e42009-06-12 22:56:54 +00001164 // (clang extension)
1165 //
Mike Stump1eb44332009-09-09 15:08:12 +00001166 // type(^)(T)
1167 // T(^)()
1168 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001169 case Type::BlockPointer: {
1170 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1171 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Anders Carlsson859ba502009-06-12 16:23:10 +00001173 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001174 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001176 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001177 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001178 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001179 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001180 }
1181
Douglas Gregor637a4092009-06-10 23:47:09 +00001182 case Type::TypeOfExpr:
1183 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001184 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001185 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001186 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001187
Douglas Gregord560d502009-06-04 00:21:18 +00001188 default:
1189 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001190 }
1191
1192 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001193 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001194}
1195
Douglas Gregorf67875d2009-06-12 18:26:56 +00001196static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001197DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001198 TemplateParameterList *TemplateParams,
1199 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001200 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001201 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001202 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001203 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001204 case TemplateArgument::Null:
1205 assert(false && "Null template argument in parameter list");
1206 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001207
1208 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001209 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001210 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001211 Arg.getAsType(), Info, Deduced, 0);
1212 Info.FirstArg = Param;
1213 Info.SecondArg = Arg;
1214 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001215
Douglas Gregor788cd062009-11-11 01:00:40 +00001216 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001217 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001218 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001219 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001220 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001221 Info.FirstArg = Param;
1222 Info.SecondArg = Arg;
1223 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001224
1225 case TemplateArgument::TemplateExpansion:
1226 llvm_unreachable("caller should handle pack expansions");
1227 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001228
Douglas Gregor199d9912009-06-05 00:53:49 +00001229 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001230 if (Arg.getKind() == TemplateArgument::Declaration &&
1231 Param.getAsDecl()->getCanonicalDecl() ==
1232 Arg.getAsDecl()->getCanonicalDecl())
1233 return Sema::TDK_Success;
1234
Douglas Gregorf67875d2009-06-12 18:26:56 +00001235 Info.FirstArg = Param;
1236 Info.SecondArg = Arg;
1237 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Douglas Gregor199d9912009-06-05 00:53:49 +00001239 case TemplateArgument::Integral:
1240 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001241 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001242 return Sema::TDK_Success;
1243
1244 Info.FirstArg = Param;
1245 Info.SecondArg = Arg;
1246 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001247 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001248
1249 if (Arg.getKind() == TemplateArgument::Expression) {
1250 Info.FirstArg = Param;
1251 Info.SecondArg = Arg;
1252 return Sema::TDK_NonDeducedMismatch;
1253 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001254
Douglas Gregorf67875d2009-06-12 18:26:56 +00001255 Info.FirstArg = Param;
1256 Info.SecondArg = Arg;
1257 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Douglas Gregor199d9912009-06-05 00:53:49 +00001259 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001260 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001261 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1262 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001263 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001264 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001265 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001266 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001267 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001268 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001269 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001270 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001271 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001272 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001273 Info, Deduced);
1274
Douglas Gregorf67875d2009-06-12 18:26:56 +00001275 Info.FirstArg = Param;
1276 Info.SecondArg = Arg;
1277 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001278 }
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Douglas Gregor199d9912009-06-05 00:53:49 +00001280 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001281 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001282 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001283 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001284 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001285 }
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Douglas Gregorf67875d2009-06-12 18:26:56 +00001287 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001288}
1289
Douglas Gregor20a55e22010-12-22 18:17:10 +00001290/// \brief Determine whether there is a template argument to be used for
1291/// deduction.
1292///
1293/// This routine "expands" argument packs in-place, overriding its input
1294/// parameters so that \c Args[ArgIdx] will be the available template argument.
1295///
1296/// \returns true if there is another template argument (which will be at
1297/// \c Args[ArgIdx]), false otherwise.
1298static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1299 unsigned &ArgIdx,
1300 unsigned &NumArgs) {
1301 if (ArgIdx == NumArgs)
1302 return false;
1303
1304 const TemplateArgument &Arg = Args[ArgIdx];
1305 if (Arg.getKind() != TemplateArgument::Pack)
1306 return true;
1307
1308 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1309 Args = Arg.pack_begin();
1310 NumArgs = Arg.pack_size();
1311 ArgIdx = 0;
1312 return ArgIdx < NumArgs;
1313}
1314
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001315/// \brief Determine whether the given set of template arguments has a pack
1316/// expansion that is not the last template argument.
1317static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1318 unsigned NumArgs) {
1319 unsigned ArgIdx = 0;
1320 while (ArgIdx < NumArgs) {
1321 const TemplateArgument &Arg = Args[ArgIdx];
1322
1323 // Unwrap argument packs.
1324 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1325 Args = Arg.pack_begin();
1326 NumArgs = Arg.pack_size();
1327 ArgIdx = 0;
1328 continue;
1329 }
1330
1331 ++ArgIdx;
1332 if (ArgIdx == NumArgs)
1333 return false;
1334
1335 if (Arg.isPackExpansion())
1336 return true;
1337 }
1338
1339 return false;
1340}
1341
Douglas Gregor20a55e22010-12-22 18:17:10 +00001342static Sema::TemplateDeductionResult
1343DeduceTemplateArguments(Sema &S,
1344 TemplateParameterList *TemplateParams,
1345 const TemplateArgument *Params, unsigned NumParams,
1346 const TemplateArgument *Args, unsigned NumArgs,
1347 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001348 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1349 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001350 // C++0x [temp.deduct.type]p9:
1351 // If the template argument list of P contains a pack expansion that is not
1352 // the last template argument, the entire template argument list is a
1353 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001354 if (hasPackExpansionBeforeEnd(Params, NumParams))
1355 return Sema::TDK_Success;
1356
Douglas Gregore02e2622010-12-22 21:19:48 +00001357 // C++0x [temp.deduct.type]p9:
1358 // If P has a form that contains <T> or <i>, then each argument Pi of the
1359 // respective template argument list P is compared with the corresponding
1360 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001361 unsigned ArgIdx = 0, ParamIdx = 0;
1362 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1363 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001364 // FIXME: Variadic templates.
1365 // What do we do if the argument is a pack expansion?
1366
Douglas Gregor20a55e22010-12-22 18:17:10 +00001367 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001368 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001369
1370 // Check whether we have enough arguments.
1371 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001372 return NumberOfArgumentsMustMatch? Sema::TDK_NonDeducedMismatch
Douglas Gregor0972c862010-12-22 18:55:49 +00001373 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001374
Douglas Gregore02e2622010-12-22 21:19:48 +00001375 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001376 if (Sema::TemplateDeductionResult Result
1377 = DeduceTemplateArguments(S, TemplateParams,
1378 Params[ParamIdx], Args[ArgIdx],
1379 Info, Deduced))
1380 return Result;
1381
1382 // Move to the next argument.
1383 ++ArgIdx;
1384 continue;
1385 }
1386
Douglas Gregore02e2622010-12-22 21:19:48 +00001387 // The parameter is a pack expansion.
1388
1389 // C++0x [temp.deduct.type]p9:
1390 // If Pi is a pack expansion, then the pattern of Pi is compared with
1391 // each remaining argument in the template argument list of A. Each
1392 // comparison deduces template arguments for subsequent positions in the
1393 // template parameter packs expanded by Pi.
1394 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1395
1396 // Compute the set of template parameter indices that correspond to
1397 // parameter packs expanded by the pack expansion.
1398 llvm::SmallVector<unsigned, 2> PackIndices;
1399 {
1400 llvm::BitVector SawIndices(TemplateParams->size());
1401 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1402 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1403 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1404 unsigned Depth, Index;
1405 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1406 if (Depth == 0 && !SawIndices[Index]) {
1407 SawIndices[Index] = true;
1408 PackIndices.push_back(Index);
1409 }
1410 }
1411 }
1412 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1413
1414 // FIXME: If there are no remaining arguments, we can bail out early
1415 // and set any deduced parameter packs to an empty argument pack.
1416 // The latter part of this is a (minor) correctness issue.
1417
1418 // Save the deduced template arguments for each parameter pack expanded
1419 // by this pack expansion, then clear out the deduction.
1420 llvm::SmallVector<DeducedTemplateArgument, 2>
1421 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00001422 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1423 NewlyDeducedPacks(PackIndices.size());
1424 PrepareArgumentPackDeduction(S, Deduced, PackIndices, SavedPacks,
1425 NewlyDeducedPacks);
Douglas Gregore02e2622010-12-22 21:19:48 +00001426
1427 // Keep track of the deduced template arguments for each parameter pack
1428 // expanded by this pack expansion (the outer index) and for each
1429 // template argument (the inner SmallVectors).
Douglas Gregore02e2622010-12-22 21:19:48 +00001430 bool HasAnyArguments = false;
1431 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1432 HasAnyArguments = true;
1433
1434 // Deduce template arguments from the pattern.
1435 if (Sema::TemplateDeductionResult Result
1436 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1437 Info, Deduced))
1438 return Result;
1439
1440 // Capture the deduced template arguments for each parameter pack expanded
1441 // by this pack expansion, add them to the list of arguments we've deduced
1442 // for that pack, then clear out the deduced argument.
1443 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1444 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1445 if (!DeducedArg.isNull()) {
1446 NewlyDeducedPacks[I].push_back(DeducedArg);
1447 DeducedArg = DeducedTemplateArgument();
1448 }
1449 }
1450
1451 ++ArgIdx;
1452 }
1453
1454 // Build argument packs for each of the parameter packs expanded by this
1455 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00001456 if (Sema::TemplateDeductionResult Result
1457 = FinishArgumentPackDeduction(S, TemplateParams, HasAnyArguments,
1458 Deduced, PackIndices, SavedPacks,
1459 NewlyDeducedPacks, Info))
1460 return Result;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001461 }
1462
1463 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001464 if (NumberOfArgumentsMustMatch &&
1465 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor3cae5c92011-01-10 20:53:55 +00001466 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001467
1468 return Sema::TDK_Success;
1469}
1470
Mike Stump1eb44332009-09-09 15:08:12 +00001471static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001472DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001473 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001474 const TemplateArgumentList &ParamList,
1475 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001476 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001477 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001478 return DeduceTemplateArguments(S, TemplateParams,
1479 ParamList.data(), ParamList.size(),
1480 ArgList.data(), ArgList.size(),
1481 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001482}
1483
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001484/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001485static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001486 const TemplateArgument &X,
1487 const TemplateArgument &Y) {
1488 if (X.getKind() != Y.getKind())
1489 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001491 switch (X.getKind()) {
1492 case TemplateArgument::Null:
1493 assert(false && "Comparing NULL template argument");
1494 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001496 case TemplateArgument::Type:
1497 return Context.getCanonicalType(X.getAsType()) ==
1498 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001500 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001501 return X.getAsDecl()->getCanonicalDecl() ==
1502 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Douglas Gregor788cd062009-11-11 01:00:40 +00001504 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001505 case TemplateArgument::TemplateExpansion:
1506 return Context.getCanonicalTemplateName(
1507 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1508 Context.getCanonicalTemplateName(
1509 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001510
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001511 case TemplateArgument::Integral:
1512 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Douglas Gregor788cd062009-11-11 01:00:40 +00001514 case TemplateArgument::Expression: {
1515 llvm::FoldingSetNodeID XID, YID;
1516 X.getAsExpr()->Profile(XID, Context, true);
1517 Y.getAsExpr()->Profile(YID, Context, true);
1518 return XID == YID;
1519 }
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001521 case TemplateArgument::Pack:
1522 if (X.pack_size() != Y.pack_size())
1523 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001524
1525 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1526 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001527 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001528 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001529 if (!isSameTemplateArg(Context, *XP, *YP))
1530 return false;
1531
1532 return true;
1533 }
1534
1535 return false;
1536}
1537
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001538/// \brief Allocate a TemplateArgumentLoc where all locations have
1539/// been initialized to the given location.
1540///
1541/// \param S The semantic analysis object.
1542///
1543/// \param The template argument we are producing template argument
1544/// location information for.
1545///
1546/// \param NTTPType For a declaration template argument, the type of
1547/// the non-type template parameter that corresponds to this template
1548/// argument.
1549///
1550/// \param Loc The source location to use for the resulting template
1551/// argument.
1552static TemplateArgumentLoc
1553getTrivialTemplateArgumentLoc(Sema &S,
1554 const TemplateArgument &Arg,
1555 QualType NTTPType,
1556 SourceLocation Loc) {
1557 switch (Arg.getKind()) {
1558 case TemplateArgument::Null:
1559 llvm_unreachable("Can't get a NULL template argument here");
1560 break;
1561
1562 case TemplateArgument::Type:
1563 return TemplateArgumentLoc(Arg,
1564 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1565
1566 case TemplateArgument::Declaration: {
1567 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001568 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001569 .takeAs<Expr>();
1570 return TemplateArgumentLoc(TemplateArgument(E), E);
1571 }
1572
1573 case TemplateArgument::Integral: {
1574 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001575 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001576 return TemplateArgumentLoc(TemplateArgument(E), E);
1577 }
1578
1579 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001580 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1581
1582 case TemplateArgument::TemplateExpansion:
1583 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1584
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001585 case TemplateArgument::Expression:
1586 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1587
1588 case TemplateArgument::Pack:
1589 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1590 }
1591
1592 return TemplateArgumentLoc();
1593}
1594
1595
1596/// \brief Convert the given deduced template argument and add it to the set of
1597/// fully-converted template arguments.
1598static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1599 DeducedTemplateArgument Arg,
1600 NamedDecl *Template,
1601 QualType NTTPType,
1602 TemplateDeductionInfo &Info,
1603 bool InFunctionTemplate,
1604 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1605 if (Arg.getKind() == TemplateArgument::Pack) {
1606 // This is a template argument pack, so check each of its arguments against
1607 // the template parameter.
1608 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1609 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001610 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001611 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001612 // When converting the deduced template argument, append it to the
1613 // general output list. We need to do this so that the template argument
1614 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001615 DeducedTemplateArgument InnerArg(*PA);
1616 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1617 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1618 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001619 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001620 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001621
1622 // Move the converted template argument into our argument pack.
1623 PackedArgsBuilder.push_back(Output.back());
1624 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001625 }
1626
1627 // Create the resulting argument pack.
1628 TemplateArgument *PackedArgs = 0;
1629 if (!PackedArgsBuilder.empty()) {
1630 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1631 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1632 }
1633 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1634 return false;
1635 }
1636
1637 // Convert the deduced template argument into a template
1638 // argument that we can check, almost as if the user had written
1639 // the template argument explicitly.
1640 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1641 Info.getLocation());
1642
1643 // Check the template argument, converting it as necessary.
1644 return S.CheckTemplateArgument(Param, ArgLoc,
1645 Template,
1646 Template->getLocation(),
1647 Template->getSourceRange().getEnd(),
1648 Output,
1649 InFunctionTemplate
1650 ? (Arg.wasDeducedFromArrayBound()
1651 ? Sema::CTAK_DeducedFromArrayBound
1652 : Sema::CTAK_Deduced)
1653 : Sema::CTAK_Specified);
1654}
1655
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001656/// Complete template argument deduction for a class template partial
1657/// specialization.
1658static Sema::TemplateDeductionResult
1659FinishTemplateArgumentDeduction(Sema &S,
1660 ClassTemplatePartialSpecializationDecl *Partial,
1661 const TemplateArgumentList &TemplateArgs,
1662 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001663 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001664 // Trap errors.
1665 Sema::SFINAETrap Trap(S);
1666
1667 Sema::ContextRAII SavedContext(S, Partial);
1668
1669 // C++ [temp.deduct.type]p2:
1670 // [...] or if any template argument remains neither deduced nor
1671 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001672 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001673 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1674 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001675 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001676 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001677 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001678 return Sema::TDK_Incomplete;
1679 }
1680
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001681 // We have deduced this argument, so it still needs to be
1682 // checked and converted.
1683
1684 // First, for a non-type template parameter type that is
1685 // initialized by a declaration, we need the type of the
1686 // corresponding non-type template parameter.
1687 QualType NTTPType;
1688 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001689 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001690 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001691 if (NTTPType->isDependentType()) {
1692 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1693 Builder.data(), Builder.size());
1694 NTTPType = S.SubstType(NTTPType,
1695 MultiLevelTemplateArgumentList(TemplateArgs),
1696 NTTP->getLocation(),
1697 NTTP->getDeclName());
1698 if (NTTPType.isNull()) {
1699 Info.Param = makeTemplateParameter(Param);
1700 // FIXME: These template arguments are temporary. Free them!
1701 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1702 Builder.data(),
1703 Builder.size()));
1704 return Sema::TDK_SubstitutionFailure;
1705 }
1706 }
1707 }
1708
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001709 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1710 Partial, NTTPType, Info, false,
1711 Builder)) {
1712 Info.Param = makeTemplateParameter(Param);
1713 // FIXME: These template arguments are temporary. Free them!
1714 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1715 Builder.size()));
1716 return Sema::TDK_SubstitutionFailure;
1717 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001718 }
1719
1720 // Form the template argument list from the deduced template arguments.
1721 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001722 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1723 Builder.size());
1724
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001725 Info.reset(DeducedArgumentList);
1726
1727 // Substitute the deduced template arguments into the template
1728 // arguments of the class template partial specialization, and
1729 // verify that the instantiated template arguments are both valid
1730 // and are equivalent to the template arguments originally provided
1731 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001732 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001733 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1734 const TemplateArgumentLoc *PartialTemplateArgs
1735 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001736
1737 // Note that we don't provide the langle and rangle locations.
1738 TemplateArgumentListInfo InstArgs;
1739
Douglas Gregore02e2622010-12-22 21:19:48 +00001740 if (S.Subst(PartialTemplateArgs,
1741 Partial->getNumTemplateArgsAsWritten(),
1742 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1743 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1744 if (ParamIdx >= Partial->getTemplateParameters()->size())
1745 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1746
1747 Decl *Param
1748 = const_cast<NamedDecl *>(
1749 Partial->getTemplateParameters()->getParam(ParamIdx));
1750 Info.Param = makeTemplateParameter(Param);
1751 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1752 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001753 }
1754
Douglas Gregor910f8002010-11-07 23:05:16 +00001755 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001756 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001757 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001758 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001759
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001760 TemplateParameterList *TemplateParams
1761 = ClassTemplate->getTemplateParameters();
1762 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001763 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001764 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001765 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001766 Info.FirstArg = TemplateArgs[I];
1767 Info.SecondArg = InstArg;
1768 return Sema::TDK_NonDeducedMismatch;
1769 }
1770 }
1771
1772 if (Trap.hasErrorOccurred())
1773 return Sema::TDK_SubstitutionFailure;
1774
1775 return Sema::TDK_Success;
1776}
1777
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001778/// \brief Perform template argument deduction to determine whether
1779/// the given template arguments match the given class template
1780/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001781Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001782Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001783 const TemplateArgumentList &TemplateArgs,
1784 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001785 // C++ [temp.class.spec.match]p2:
1786 // A partial specialization matches a given actual template
1787 // argument list if the template arguments of the partial
1788 // specialization can be deduced from the actual template argument
1789 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001790 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001791 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001792 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001793 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001794 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001795 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001796 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001797 TemplateArgs, Info, Deduced))
1798 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001799
Douglas Gregor637a4092009-06-10 23:47:09 +00001800 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001801 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001802 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001803 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001804
Douglas Gregorbb260412009-06-14 08:02:22 +00001805 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001806 return Sema::TDK_SubstitutionFailure;
1807
1808 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1809 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001810}
Douglas Gregor031a5882009-06-13 00:26:55 +00001811
Douglas Gregor41128772009-06-26 23:27:24 +00001812/// \brief Determine whether the given type T is a simple-template-id type.
1813static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001814 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001815 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001816 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Douglas Gregor41128772009-06-26 23:27:24 +00001818 return false;
1819}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001820
1821/// \brief Substitute the explicitly-provided template arguments into the
1822/// given function template according to C++ [temp.arg.explicit].
1823///
1824/// \param FunctionTemplate the function template into which the explicit
1825/// template arguments will be substituted.
1826///
Mike Stump1eb44332009-09-09 15:08:12 +00001827/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001828/// arguments.
1829///
Mike Stump1eb44332009-09-09 15:08:12 +00001830/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001831/// with the converted and checked explicit template arguments.
1832///
Mike Stump1eb44332009-09-09 15:08:12 +00001833/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001834/// parameters.
1835///
1836/// \param FunctionType if non-NULL, the result type of the function template
1837/// will also be instantiated and the pointed-to value will be updated with
1838/// the instantiated function type.
1839///
1840/// \param Info if substitution fails for any reason, this object will be
1841/// populated with more information about the failure.
1842///
1843/// \returns TDK_Success if substitution was successful, or some failure
1844/// condition.
1845Sema::TemplateDeductionResult
1846Sema::SubstituteExplicitTemplateArguments(
1847 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001848 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001849 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001850 llvm::SmallVectorImpl<QualType> &ParamTypes,
1851 QualType *FunctionType,
1852 TemplateDeductionInfo &Info) {
1853 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1854 TemplateParameterList *TemplateParams
1855 = FunctionTemplate->getTemplateParameters();
1856
John McCalld5532b62009-11-23 01:53:49 +00001857 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001858 // No arguments to substitute; just copy over the parameter types and
1859 // fill in the function type.
1860 for (FunctionDecl::param_iterator P = Function->param_begin(),
1861 PEnd = Function->param_end();
1862 P != PEnd;
1863 ++P)
1864 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Douglas Gregor83314aa2009-07-08 20:55:45 +00001866 if (FunctionType)
1867 *FunctionType = Function->getType();
1868 return TDK_Success;
1869 }
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Douglas Gregor83314aa2009-07-08 20:55:45 +00001871 // Substitution of the explicit template arguments into a function template
1872 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001873 SFINAETrap Trap(*this);
1874
Douglas Gregor83314aa2009-07-08 20:55:45 +00001875 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001876 // Template arguments that are present shall be specified in the
1877 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001878 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001879 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001880 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001881
1882 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001883 // explicitly-specified template arguments against this function template,
1884 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001885 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001886 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001887 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1888 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001889 if (Inst)
1890 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001891
Douglas Gregor83314aa2009-07-08 20:55:45 +00001892 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001893 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001894 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001895 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001896 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001897 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001898 if (Index >= TemplateParams->size())
1899 Index = TemplateParams->size() - 1;
1900 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001901 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001902 }
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Douglas Gregor83314aa2009-07-08 20:55:45 +00001904 // Form the template argument list from the explicitly-specified
1905 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001906 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001907 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001908 Info.reset(ExplicitArgumentList);
Douglas Gregord3731192011-01-10 07:32:04 +00001909
John McCalldf41f182010-10-12 19:40:14 +00001910 // Template argument deduction and the final substitution should be
1911 // done in the context of the templated declaration. Explicit
1912 // argument substitution, on the other hand, needs to happen in the
1913 // calling context.
1914 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1915
Douglas Gregord3731192011-01-10 07:32:04 +00001916 // If we deduced template arguments for a template parameter pack,
1917 // note that the template argument pack is partially substituted and record
1918 // the explicit template arguments. They'll be used as part of deduction
1919 // for this template parameter pack.
1920 bool HasPartiallySubstitutedPack = false;
1921 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
1922 const TemplateArgument &Arg = Builder[I];
1923 if (Arg.getKind() == TemplateArgument::Pack) {
1924 HasPartiallySubstitutedPack = true;
1925 CurrentInstantiationScope->SetPartiallySubstitutedPack(
1926 TemplateParams->getParam(I),
1927 Arg.pack_begin(),
1928 Arg.pack_size());
1929 break;
1930 }
1931 }
1932
Douglas Gregor83314aa2009-07-08 20:55:45 +00001933 // Instantiate the types of each of the function parameters given the
1934 // explicitly-specified template arguments.
Douglas Gregora009b592011-01-07 00:20:55 +00001935 if (SubstParmTypes(Function->getLocation(),
1936 Function->param_begin(), Function->getNumParams(),
1937 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1938 ParamTypes))
1939 return TDK_SubstitutionFailure;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001940
1941 // If the caller wants a full function type back, instantiate the return
1942 // type and form that function type.
1943 if (FunctionType) {
1944 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001945 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001946 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001947 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001948
1949 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001950 = SubstType(Proto->getResultType(),
1951 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1952 Function->getTypeSpecStartLoc(),
1953 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001954 if (ResultType.isNull() || Trap.hasErrorOccurred())
1955 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001956
1957 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001958 ParamTypes.data(), ParamTypes.size(),
1959 Proto->isVariadic(),
1960 Proto->getTypeQuals(),
1961 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001962 Function->getDeclName(),
1963 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001964 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1965 return TDK_SubstitutionFailure;
1966 }
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Douglas Gregor83314aa2009-07-08 20:55:45 +00001968 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001969 // Trailing template arguments that can be deduced (14.8.2) may be
1970 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001971 // template arguments can be deduced, they may all be omitted; in this
1972 // case, the empty template argument list <> itself may also be omitted.
1973 //
Douglas Gregord3731192011-01-10 07:32:04 +00001974 // Take all of the explicitly-specified arguments and put them into
1975 // the set of deduced template arguments. Explicitly-specified
1976 // parameter packs, however, will be set to NULL since the deduction
1977 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001978 Deduced.reserve(TemplateParams->size());
Douglas Gregord3731192011-01-10 07:32:04 +00001979 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
1980 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
1981 if (Arg.getKind() == TemplateArgument::Pack)
1982 Deduced.push_back(DeducedTemplateArgument());
1983 else
1984 Deduced.push_back(Arg);
1985 }
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Douglas Gregor83314aa2009-07-08 20:55:45 +00001987 return TDK_Success;
1988}
1989
Mike Stump1eb44332009-09-09 15:08:12 +00001990/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001991/// checking the deduced template arguments for completeness and forming
1992/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001993Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001994Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001995 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1996 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001997 FunctionDecl *&Specialization,
1998 TemplateDeductionInfo &Info) {
1999 TemplateParameterList *TemplateParams
2000 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Douglas Gregor83314aa2009-07-08 20:55:45 +00002002 // Template argument deduction for function templates in a SFINAE context.
2003 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002004 SFINAETrap Trap(*this);
2005
Douglas Gregor83314aa2009-07-08 20:55:45 +00002006 // Enter a new template instantiation context while we instantiate the
2007 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002008 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00002009 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00002010 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2011 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00002012 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00002013 return TDK_InstantiationDepth;
2014
John McCall96db3102010-04-29 01:18:58 +00002015 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00002016
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002017 // C++ [temp.deduct.type]p2:
2018 // [...] or if any template argument remains neither deduced nor
2019 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00002020 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002021 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2022 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002023
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002024 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002025 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00002026 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00002027 // argument, because it was explicitly-specified. Just record the
2028 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00002029 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00002030 continue;
2031 }
2032
2033 // We have deduced this argument, so it still needs to be
2034 // checked and converted.
2035
2036 // First, for a non-type template parameter type that is
2037 // initialized by a declaration, we need the type of the
2038 // corresponding non-type template parameter.
2039 QualType NTTPType;
2040 if (NonTypeTemplateParmDecl *NTTP
2041 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002042 NTTPType = NTTP->getType();
2043 if (NTTPType->isDependentType()) {
2044 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2045 Builder.data(), Builder.size());
2046 NTTPType = SubstType(NTTPType,
2047 MultiLevelTemplateArgumentList(TemplateArgs),
2048 NTTP->getLocation(),
2049 NTTP->getDeclName());
2050 if (NTTPType.isNull()) {
2051 Info.Param = makeTemplateParameter(Param);
2052 // FIXME: These template arguments are temporary. Free them!
2053 Info.reset(TemplateArgumentList::CreateCopy(Context,
2054 Builder.data(),
2055 Builder.size()));
2056 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002057 }
2058 }
2059 }
2060
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002061 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2062 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002063 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002064 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002065 // FIXME: These template arguments are temporary. Free them!
2066 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002067 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002068 return TDK_SubstitutionFailure;
2069 }
2070
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002071 continue;
2072 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002073
2074 // C++0x [temp.arg.explicit]p3:
2075 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2076 // be deduced to an empty sequence of template arguments.
2077 // FIXME: Where did the word "trailing" come from?
2078 if (Param->isTemplateParameterPack()) {
Douglas Gregord3731192011-01-10 07:32:04 +00002079 // We may have had explicitly-specified template arguments for this
2080 // template parameter pack. If so, our empty deduction extends the
2081 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2082 const TemplateArgument *ExplicitArgs;
2083 unsigned NumExplicitArgs;
2084 if (CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
2085 &NumExplicitArgs)
2086 == Param)
2087 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
2088 else
2089 Builder.push_back(TemplateArgument(0, 0));
2090
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002091 continue;
2092 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002093
2094 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002095 TemplateArgumentLoc DefArg
2096 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2097 FunctionTemplate->getLocation(),
2098 FunctionTemplate->getSourceRange().getEnd(),
2099 Param,
2100 Builder);
2101
2102 // If there was no default argument, deduction is incomplete.
2103 if (DefArg.getArgument().isNull()) {
2104 Info.Param = makeTemplateParameter(
2105 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2106 return TDK_Incomplete;
2107 }
2108
2109 // Check whether we can actually use the default argument.
2110 if (CheckTemplateArgument(Param, DefArg,
2111 FunctionTemplate,
2112 FunctionTemplate->getLocation(),
2113 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002114 Builder,
2115 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002116 Info.Param = makeTemplateParameter(
2117 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002118 // FIXME: These template arguments are temporary. Free them!
2119 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2120 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002121 return TDK_SubstitutionFailure;
2122 }
2123
2124 // If we get here, we successfully used the default template argument.
2125 }
2126
2127 // Form the template argument list from the deduced template arguments.
2128 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002129 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002130 Info.reset(DeducedArgumentList);
2131
Mike Stump1eb44332009-09-09 15:08:12 +00002132 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002133 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002134 DeclContext *Owner = FunctionTemplate->getDeclContext();
2135 if (FunctionTemplate->getFriendObjectKind())
2136 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002137 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002138 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002139 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002140 if (!Specialization)
2141 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Douglas Gregorf8825742009-09-15 18:26:13 +00002143 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2144 FunctionTemplate->getCanonicalDecl());
2145
Mike Stump1eb44332009-09-09 15:08:12 +00002146 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002147 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002148 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2149 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002150 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Douglas Gregor83314aa2009-07-08 20:55:45 +00002152 // There may have been an error that did not prevent us from constructing a
2153 // declaration. Mark the declaration invalid and return with a substitution
2154 // failure.
2155 if (Trap.hasErrorOccurred()) {
2156 Specialization->setInvalidDecl(true);
2157 return TDK_SubstitutionFailure;
2158 }
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Douglas Gregor9b623632010-10-12 23:32:35 +00002160 // If we suppressed any diagnostics while performing template argument
2161 // deduction, and if we haven't already instantiated this declaration,
2162 // keep track of these diagnostics. They'll be emitted if this specialization
2163 // is actually used.
2164 if (Info.diag_begin() != Info.diag_end()) {
2165 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2166 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2167 if (Pos == SuppressedDiagnostics.end())
2168 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2169 .append(Info.diag_begin(), Info.diag_end());
2170 }
2171
Mike Stump1eb44332009-09-09 15:08:12 +00002172 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002173}
2174
John McCall9c72c602010-08-27 09:08:28 +00002175/// Gets the type of a function for template-argument-deducton
2176/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002177static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002178 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002179 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002180 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002181 if (Method->isInstance()) {
2182 // An instance method that's referenced in a form that doesn't
2183 // look like a member pointer is just invalid.
2184 if (!R.HasFormOfMemberPointer) return QualType();
2185
John McCalleff92132010-02-02 02:21:27 +00002186 return Context.getMemberPointerType(Fn->getType(),
2187 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002188 }
2189
2190 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002191 return Context.getPointerType(Fn->getType());
2192}
2193
2194/// Apply the deduction rules for overload sets.
2195///
2196/// \return the null type if this argument should be treated as an
2197/// undeduced context
2198static QualType
2199ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002200 Expr *Arg, QualType ParamType,
2201 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002202
2203 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002204
John McCall9c72c602010-08-27 09:08:28 +00002205 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002206
Douglas Gregor75f21af2010-08-30 21:04:23 +00002207 // C++0x [temp.deduct.call]p4
2208 unsigned TDF = 0;
2209 if (ParamWasReference)
2210 TDF |= TDF_ParamWithReferenceType;
2211 if (R.IsAddressOfOperand)
2212 TDF |= TDF_IgnoreQualifiers;
2213
John McCalleff92132010-02-02 02:21:27 +00002214 // If there were explicit template arguments, we can only find
2215 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2216 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002217 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002218 // But we can still look for an explicit specialization.
2219 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002220 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002221 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002222 return QualType();
2223 }
2224
2225 // C++0x [temp.deduct.call]p6:
2226 // When P is a function type, pointer to function type, or pointer
2227 // to member function type:
2228
2229 if (!ParamType->isFunctionType() &&
2230 !ParamType->isFunctionPointerType() &&
2231 !ParamType->isMemberFunctionPointerType())
2232 return QualType();
2233
2234 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002235 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2236 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002237 NamedDecl *D = (*I)->getUnderlyingDecl();
2238
2239 // - If the argument is an overload set containing one or more
2240 // function templates, the parameter is treated as a
2241 // non-deduced context.
2242 if (isa<FunctionTemplateDecl>(D))
2243 return QualType();
2244
2245 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002246 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2247 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002248
Douglas Gregor75f21af2010-08-30 21:04:23 +00002249 // Function-to-pointer conversion.
2250 if (!ParamWasReference && ParamType->isPointerType() &&
2251 ArgType->isFunctionType())
2252 ArgType = S.Context.getPointerType(ArgType);
2253
John McCalleff92132010-02-02 02:21:27 +00002254 // - If the argument is an overload set (not containing function
2255 // templates), trial argument deduction is attempted using each
2256 // of the members of the set. If deduction succeeds for only one
2257 // of the overload set members, that member is used as the
2258 // argument value for the deduction. If deduction succeeds for
2259 // more than one member of the overload set the parameter is
2260 // treated as a non-deduced context.
2261
2262 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2263 // Type deduction is done independently for each P/A pair, and
2264 // the deduced template argument values are then combined.
2265 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002266 llvm::SmallVector<DeducedTemplateArgument, 8>
2267 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002268 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002269 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002270 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002271 ParamType, ArgType,
2272 Info, Deduced, TDF);
2273 if (Result) continue;
2274 if (!Match.isNull()) return QualType();
2275 Match = ArgType;
2276 }
2277
2278 return Match;
2279}
2280
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002281/// \brief Perform the adjustments to the parameter and argument types
2282/// described in C++ [temp.deduct.call].
2283///
2284/// \returns true if the caller should not attempt to perform any template
2285/// argument deduction based on this P/A pair.
2286static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
2287 TemplateParameterList *TemplateParams,
2288 QualType &ParamType,
2289 QualType &ArgType,
2290 Expr *Arg,
2291 unsigned &TDF) {
2292 // C++0x [temp.deduct.call]p3:
2293 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2294 // are ignored for type deduction.
2295 if (ParamType.getCVRQualifiers())
2296 ParamType = ParamType.getLocalUnqualifiedType();
2297 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2298 if (ParamRefType) {
2299 // [...] If P is a reference type, the type referred to by P is used
2300 // for type deduction.
2301 ParamType = ParamRefType->getPointeeType();
2302 }
2303
2304 // Overload sets usually make this parameter an undeduced
2305 // context, but there are sometimes special circumstances.
2306 if (ArgType == S.Context.OverloadTy) {
2307 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
2308 Arg, ParamType,
2309 ParamRefType != 0);
2310 if (ArgType.isNull())
2311 return true;
2312 }
2313
2314 if (ParamRefType) {
2315 // C++0x [temp.deduct.call]p3:
2316 // [...] If P is of the form T&&, where T is a template parameter, and
2317 // the argument is an lvalue, the type A& is used in place of A for
2318 // type deduction.
2319 if (ParamRefType->isRValueReferenceType() &&
2320 ParamRefType->getAs<TemplateTypeParmType>() &&
2321 Arg->isLValue())
2322 ArgType = S.Context.getLValueReferenceType(ArgType);
2323 } else {
2324 // C++ [temp.deduct.call]p2:
2325 // If P is not a reference type:
2326 // - If A is an array type, the pointer type produced by the
2327 // array-to-pointer standard conversion (4.2) is used in place of
2328 // A for type deduction; otherwise,
2329 if (ArgType->isArrayType())
2330 ArgType = S.Context.getArrayDecayedType(ArgType);
2331 // - If A is a function type, the pointer type produced by the
2332 // function-to-pointer standard conversion (4.3) is used in place
2333 // of A for type deduction; otherwise,
2334 else if (ArgType->isFunctionType())
2335 ArgType = S.Context.getPointerType(ArgType);
2336 else {
2337 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2338 // type are ignored for type deduction.
2339 QualType CanonArgType = S.Context.getCanonicalType(ArgType);
2340 if (ArgType.getCVRQualifiers())
2341 ArgType = ArgType.getUnqualifiedType();
2342 }
2343 }
2344
2345 // C++0x [temp.deduct.call]p4:
2346 // In general, the deduction process attempts to find template argument
2347 // values that will make the deduced A identical to A (after the type A
2348 // is transformed as described above). [...]
2349 TDF = TDF_SkipNonDependent;
2350
2351 // - If the original P is a reference type, the deduced A (i.e., the
2352 // type referred to by the reference) can be more cv-qualified than
2353 // the transformed A.
2354 if (ParamRefType)
2355 TDF |= TDF_ParamWithReferenceType;
2356 // - The transformed A can be another pointer or pointer to member
2357 // type that can be converted to the deduced A via a qualification
2358 // conversion (4.4).
2359 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2360 ArgType->isObjCObjectPointerType())
2361 TDF |= TDF_IgnoreQualifiers;
2362 // - If P is a class and P has the form simple-template-id, then the
2363 // transformed A can be a derived class of the deduced A. Likewise,
2364 // if P is a pointer to a class of the form simple-template-id, the
2365 // transformed A can be a pointer to a derived class pointed to by
2366 // the deduced A.
2367 if (isSimpleTemplateIdType(ParamType) ||
2368 (isa<PointerType>(ParamType) &&
2369 isSimpleTemplateIdType(
2370 ParamType->getAs<PointerType>()->getPointeeType())))
2371 TDF |= TDF_DerivedClass;
2372
2373 return false;
2374}
2375
Douglas Gregore53060f2009-06-25 22:08:12 +00002376/// \brief Perform template argument deduction from a function call
2377/// (C++ [temp.deduct.call]).
2378///
2379/// \param FunctionTemplate the function template for which we are performing
2380/// template argument deduction.
2381///
Douglas Gregor48026d22010-01-11 18:40:55 +00002382/// \param ExplicitTemplateArguments the explicit template arguments provided
2383/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002384///
Douglas Gregore53060f2009-06-25 22:08:12 +00002385/// \param Args the function call arguments
2386///
2387/// \param NumArgs the number of arguments in Args
2388///
Douglas Gregor48026d22010-01-11 18:40:55 +00002389/// \param Name the name of the function being called. This is only significant
2390/// when the function template is a conversion function template, in which
2391/// case this routine will also perform template argument deduction based on
2392/// the function to which
2393///
Douglas Gregore53060f2009-06-25 22:08:12 +00002394/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002395/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002396/// template argument deduction.
2397///
2398/// \param Info the argument will be updated to provide additional information
2399/// about template argument deduction.
2400///
2401/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002402Sema::TemplateDeductionResult
2403Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002404 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002405 Expr **Args, unsigned NumArgs,
2406 FunctionDecl *&Specialization,
2407 TemplateDeductionInfo &Info) {
2408 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002409
Douglas Gregore53060f2009-06-25 22:08:12 +00002410 // C++ [temp.deduct.call]p1:
2411 // Template argument deduction is done by comparing each function template
2412 // parameter type (call it P) with the type of the corresponding argument
2413 // of the call (call it A) as described below.
2414 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002415 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002416 return TDK_TooFewArguments;
2417 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002418 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002419 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002420 if (Proto->isTemplateVariadic())
2421 /* Do nothing */;
2422 else if (Proto->isVariadic())
2423 CheckArgs = Function->getNumParams();
2424 else
Douglas Gregore53060f2009-06-25 22:08:12 +00002425 return TDK_TooManyArguments;
Douglas Gregore53060f2009-06-25 22:08:12 +00002426 }
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002428 // The types of the parameters from which we will perform template argument
2429 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002430 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002431 TemplateParameterList *TemplateParams
2432 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002433 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002434 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002435 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002436 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002437 TemplateDeductionResult Result =
2438 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002439 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002440 Deduced,
2441 ParamTypes,
2442 0,
2443 Info);
2444 if (Result)
2445 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002446
2447 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002448 } else {
2449 // Just fill in the parameter types from the function declaration.
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002450 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002451 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2452 }
Mike Stump1eb44332009-09-09 15:08:12 +00002453
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002454 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002455 Deduced.resize(TemplateParams->size());
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002456 unsigned ArgIdx = 0;
2457 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
2458 ParamIdx != NumParams; ++ParamIdx) {
2459 QualType ParamType = ParamTypes[ParamIdx];
2460
2461 const PackExpansionType *ParamExpansion
2462 = dyn_cast<PackExpansionType>(ParamType);
2463 if (!ParamExpansion) {
2464 // Simple case: matching a function parameter to a function argument.
2465 if (ArgIdx >= CheckArgs)
2466 break;
2467
2468 Expr *Arg = Args[ArgIdx++];
2469 QualType ArgType = Arg->getType();
2470 unsigned TDF = 0;
2471 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2472 ParamType, ArgType, Arg,
2473 TDF))
2474 continue;
2475
2476 if (TemplateDeductionResult Result
2477 = ::DeduceTemplateArguments(*this, TemplateParams,
2478 ParamType, ArgType, Info, Deduced,
2479 TDF))
2480 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002482 // FIXME: we need to check that the deduced A is the same as A,
2483 // modulo the various allowed differences.
2484 continue;
Douglas Gregor75f21af2010-08-30 21:04:23 +00002485 }
2486
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002487 // C++0x [temp.deduct.call]p1:
2488 // For a function parameter pack that occurs at the end of the
2489 // parameter-declaration-list, the type A of each remaining argument of
2490 // the call is compared with the type P of the declarator-id of the
2491 // function parameter pack. Each comparison deduces template arguments
2492 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor7d5c0c12011-01-11 01:52:23 +00002493 // the function parameter pack. For a function parameter pack that does
2494 // not occur at the end of the parameter-declaration-list, the type of
2495 // the parameter pack is a non-deduced context.
2496 if (ParamIdx + 1 < NumParams)
2497 break;
2498
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002499 QualType ParamPattern = ParamExpansion->getPattern();
2500 llvm::SmallVector<unsigned, 2> PackIndices;
2501 {
2502 llvm::BitVector SawIndices(TemplateParams->size());
2503 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2504 collectUnexpandedParameterPacks(ParamPattern, Unexpanded);
2505 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
2506 unsigned Depth, Index;
2507 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
2508 if (Depth == 0 && !SawIndices[Index]) {
2509 SawIndices[Index] = true;
2510 PackIndices.push_back(Index);
2511 }
Douglas Gregore53060f2009-06-25 22:08:12 +00002512 }
2513 }
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002514 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
2515
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002516 // Keep track of the deduced template arguments for each parameter pack
2517 // expanded by this pack expansion (the outer index) and for each
2518 // template argument (the inner SmallVectors).
2519 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
Douglas Gregord3731192011-01-10 07:32:04 +00002520 NewlyDeducedPacks(PackIndices.size());
Douglas Gregord3731192011-01-10 07:32:04 +00002521 llvm::SmallVector<DeducedTemplateArgument, 2>
2522 SavedPacks(PackIndices.size());
Douglas Gregor54293852011-01-10 17:35:05 +00002523 PrepareArgumentPackDeduction(*this, Deduced, PackIndices, SavedPacks,
2524 NewlyDeducedPacks);
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002525 bool HasAnyArguments = false;
2526 for (; ArgIdx < NumArgs; ++ArgIdx) {
2527 HasAnyArguments = true;
2528
2529 ParamType = ParamPattern;
2530 Expr *Arg = Args[ArgIdx];
2531 QualType ArgType = Arg->getType();
2532 unsigned TDF = 0;
2533 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
2534 ParamType, ArgType, Arg,
2535 TDF)) {
2536 // We can't actually perform any deduction for this argument, so stop
2537 // deduction at this point.
2538 ++ArgIdx;
2539 break;
2540 }
2541
2542 if (TemplateDeductionResult Result
2543 = ::DeduceTemplateArguments(*this, TemplateParams,
2544 ParamType, ArgType, Info, Deduced,
2545 TDF))
2546 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002547
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002548 // Capture the deduced template arguments for each parameter pack expanded
2549 // by this pack expansion, add them to the list of arguments we've deduced
2550 // for that pack, then clear out the deduced argument.
2551 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
2552 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
2553 if (!DeducedArg.isNull()) {
2554 NewlyDeducedPacks[I].push_back(DeducedArg);
2555 DeducedArg = DeducedTemplateArgument();
2556 }
2557 }
2558 }
2559
2560 // Build argument packs for each of the parameter packs expanded by this
2561 // pack expansion.
Douglas Gregor0216f812011-01-10 17:53:52 +00002562 if (Sema::TemplateDeductionResult Result
2563 = FinishArgumentPackDeduction(*this, TemplateParams, HasAnyArguments,
2564 Deduced, PackIndices, SavedPacks,
2565 NewlyDeducedPacks, Info))
2566 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00002568 // After we've matching against a parameter pack, we're done.
2569 break;
Douglas Gregore53060f2009-06-25 22:08:12 +00002570 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002571
Mike Stump1eb44332009-09-09 15:08:12 +00002572 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002573 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002574 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002575}
2576
Douglas Gregor83314aa2009-07-08 20:55:45 +00002577/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002578/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2579/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002580///
2581/// \param FunctionTemplate the function template for which we are performing
2582/// template argument deduction.
2583///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002584/// \param ExplicitTemplateArguments the explicitly-specified template
2585/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002586///
2587/// \param ArgFunctionType the function type that will be used as the
2588/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002589/// function template's function type. This type may be NULL, if there is no
2590/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002591///
2592/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002593/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002594/// template argument deduction.
2595///
2596/// \param Info the argument will be updated to provide additional information
2597/// about template argument deduction.
2598///
2599/// \returns the result of template argument deduction.
2600Sema::TemplateDeductionResult
2601Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002602 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002603 QualType ArgFunctionType,
2604 FunctionDecl *&Specialization,
2605 TemplateDeductionInfo &Info) {
2606 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2607 TemplateParameterList *TemplateParams
2608 = FunctionTemplate->getTemplateParameters();
2609 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Douglas Gregor83314aa2009-07-08 20:55:45 +00002611 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002612 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002613 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2614 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002615 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002616 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002617 if (TemplateDeductionResult Result
2618 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002619 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002620 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002621 &FunctionType, Info))
2622 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002623
2624 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002625 }
2626
2627 // Template argument deduction for function templates in a SFINAE context.
2628 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002629 SFINAETrap Trap(*this);
2630
John McCalleff92132010-02-02 02:21:27 +00002631 Deduced.resize(TemplateParams->size());
2632
Douglas Gregor4b52e252009-12-21 23:17:24 +00002633 if (!ArgFunctionType.isNull()) {
2634 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002635 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002636 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002637 FunctionType, ArgFunctionType, Info,
2638 Deduced, 0))
2639 return Result;
2640 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002641
2642 if (TemplateDeductionResult Result
2643 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2644 NumExplicitlySpecified,
2645 Specialization, Info))
2646 return Result;
2647
2648 // If the requested function type does not match the actual type of the
2649 // specialization, template argument deduction fails.
2650 if (!ArgFunctionType.isNull() &&
2651 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2652 return TDK_NonDeducedMismatch;
2653
2654 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002655}
2656
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002657/// \brief Deduce template arguments for a templated conversion
2658/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2659/// conversion function template specialization.
2660Sema::TemplateDeductionResult
2661Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2662 QualType ToType,
2663 CXXConversionDecl *&Specialization,
2664 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002665 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002666 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2667 QualType FromType = Conv->getConversionType();
2668
2669 // Canonicalize the types for deduction.
2670 QualType P = Context.getCanonicalType(FromType);
2671 QualType A = Context.getCanonicalType(ToType);
2672
2673 // C++0x [temp.deduct.conv]p3:
2674 // If P is a reference type, the type referred to by P is used for
2675 // type deduction.
2676 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2677 P = PRef->getPointeeType();
2678
2679 // C++0x [temp.deduct.conv]p3:
2680 // If A is a reference type, the type referred to by A is used
2681 // for type deduction.
2682 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2683 A = ARef->getPointeeType();
2684 // C++ [temp.deduct.conv]p2:
2685 //
Mike Stump1eb44332009-09-09 15:08:12 +00002686 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002687 else {
2688 assert(!A->isReferenceType() && "Reference types were handled above");
2689
2690 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002691 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002692 // of P for type deduction; otherwise,
2693 if (P->isArrayType())
2694 P = Context.getArrayDecayedType(P);
2695 // - If P is a function type, the pointer type produced by the
2696 // function-to-pointer standard conversion (4.3) is used in
2697 // place of P for type deduction; otherwise,
2698 else if (P->isFunctionType())
2699 P = Context.getPointerType(P);
2700 // - If P is a cv-qualified type, the top level cv-qualifiers of
2701 // P’s type are ignored for type deduction.
2702 else
2703 P = P.getUnqualifiedType();
2704
2705 // C++0x [temp.deduct.conv]p3:
2706 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2707 // type are ignored for type deduction.
2708 A = A.getUnqualifiedType();
2709 }
2710
2711 // Template argument deduction for function templates in a SFINAE context.
2712 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002713 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002714
2715 // C++ [temp.deduct.conv]p1:
2716 // Template argument deduction is done by comparing the return
2717 // type of the template conversion function (call it P) with the
2718 // type that is required as the result of the conversion (call it
2719 // A) as described in 14.8.2.4.
2720 TemplateParameterList *TemplateParams
2721 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002722 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002723 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002724
2725 // C++0x [temp.deduct.conv]p4:
2726 // In general, the deduction process attempts to find template
2727 // argument values that will make the deduced A identical to
2728 // A. However, there are two cases that allow a difference:
2729 unsigned TDF = 0;
2730 // - If the original A is a reference type, A can be more
2731 // cv-qualified than the deduced A (i.e., the type referred to
2732 // by the reference)
2733 if (ToType->isReferenceType())
2734 TDF |= TDF_ParamWithReferenceType;
2735 // - The deduced A can be another pointer or pointer to member
2736 // type that can be converted to A via a qualification
2737 // conversion.
2738 //
2739 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2740 // both P and A are pointers or member pointers. In this case, we
2741 // just ignore cv-qualifiers completely).
2742 if ((P->isPointerType() && A->isPointerType()) ||
2743 (P->isMemberPointerType() && P->isMemberPointerType()))
2744 TDF |= TDF_IgnoreQualifiers;
2745 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002746 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002747 P, A, Info, Deduced, TDF))
2748 return Result;
2749
2750 // FIXME: we need to check that the deduced A is the same as A,
2751 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002752
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002753 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002754 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002755 FunctionDecl *Spec = 0;
2756 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002757 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2758 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002759 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2760 return Result;
2761}
2762
Douglas Gregor4b52e252009-12-21 23:17:24 +00002763/// \brief Deduce template arguments for a function template when there is
2764/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2765///
2766/// \param FunctionTemplate the function template for which we are performing
2767/// template argument deduction.
2768///
2769/// \param ExplicitTemplateArguments the explicitly-specified template
2770/// arguments.
2771///
2772/// \param Specialization if template argument deduction was successful,
2773/// this will be set to the function template specialization produced by
2774/// template argument deduction.
2775///
2776/// \param Info the argument will be updated to provide additional information
2777/// about template argument deduction.
2778///
2779/// \returns the result of template argument deduction.
2780Sema::TemplateDeductionResult
2781Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2782 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2783 FunctionDecl *&Specialization,
2784 TemplateDeductionInfo &Info) {
2785 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2786 QualType(), Specialization, Info);
2787}
2788
Douglas Gregor8a514912009-09-14 18:39:43 +00002789/// \brief Stores the result of comparing the qualifiers of two types.
2790enum DeductionQualifierComparison {
2791 NeitherMoreQualified = 0,
2792 ParamMoreQualified,
2793 ArgMoreQualified
2794};
2795
2796/// \brief Deduce the template arguments during partial ordering by comparing
2797/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2798///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002799/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002800///
2801/// \param TemplateParams the template parameters that we are deducing
2802///
2803/// \param ParamIn the parameter type
2804///
2805/// \param ArgIn the argument type
2806///
2807/// \param Info information about the template argument deduction itself
2808///
2809/// \param Deduced the deduced template arguments
2810///
2811/// \returns the result of template argument deduction so far. Note that a
2812/// "success" result means that template argument deduction has not yet failed,
2813/// but it may still fail, later, for other reasons.
2814static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002815DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002816 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002817 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002818 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002819 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2820 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002821 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2822 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002823
2824 // C++0x [temp.deduct.partial]p5:
2825 // Before the partial ordering is done, certain transformations are
2826 // performed on the types used for partial ordering:
2827 // - If P is a reference type, P is replaced by the type referred to.
2828 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002829 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002830 Param = ParamRef->getPointeeType();
2831
2832 // - If A is a reference type, A is replaced by the type referred to.
2833 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002834 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002835 Arg = ArgRef->getPointeeType();
2836
John McCalle27ec8a2009-10-23 23:03:21 +00002837 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002838 // C++0x [temp.deduct.partial]p6:
2839 // If both P and A were reference types (before being replaced with the
2840 // type referred to above), determine which of the two types (if any) is
2841 // more cv-qualified than the other; otherwise the types are considered to
2842 // be equally cv-qualified for partial ordering purposes. The result of this
2843 // determination will be used below.
2844 //
2845 // We save this information for later, using it only when deduction
2846 // succeeds in both directions.
2847 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2848 if (Param.isMoreQualifiedThan(Arg))
2849 QualifierResult = ParamMoreQualified;
2850 else if (Arg.isMoreQualifiedThan(Param))
2851 QualifierResult = ArgMoreQualified;
2852 QualifierComparisons->push_back(QualifierResult);
2853 }
2854
2855 // C++0x [temp.deduct.partial]p7:
2856 // Remove any top-level cv-qualifiers:
2857 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2858 // version of P.
2859 Param = Param.getUnqualifiedType();
2860 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2861 // version of A.
2862 Arg = Arg.getUnqualifiedType();
2863
2864 // C++0x [temp.deduct.partial]p8:
2865 // Using the resulting types P and A the deduction is then done as
2866 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2867 // from the argument template is considered to be at least as specialized
2868 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002869 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002870 Deduced, TDF_None);
2871}
2872
2873static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002874MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2875 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002876 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002877 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002878
2879/// \brief If this is a non-static member function,
2880static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2881 CXXMethodDecl *Method,
2882 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2883 if (Method->isStatic())
2884 return;
2885
2886 // C++ [over.match.funcs]p4:
2887 //
2888 // For non-static member functions, the type of the implicit
2889 // object parameter is
2890 // — "lvalue reference to cv X" for functions declared without a
2891 // ref-qualifier or with the & ref-qualifier
2892 // - "rvalue reference to cv X" for functions declared with the
2893 // && ref-qualifier
2894 //
2895 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2896 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2897 ArgTy = Context.getQualifiedType(ArgTy,
2898 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2899 ArgTy = Context.getLValueReferenceType(ArgTy);
2900 ArgTypes.push_back(ArgTy);
2901}
2902
Douglas Gregor8a514912009-09-14 18:39:43 +00002903/// \brief Determine whether the function template \p FT1 is at least as
2904/// specialized as \p FT2.
2905static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002906 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002907 FunctionTemplateDecl *FT1,
2908 FunctionTemplateDecl *FT2,
2909 TemplatePartialOrderingContext TPOC,
2910 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2911 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2912 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2913 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2914 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2915
2916 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2917 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002918 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002919 Deduced.resize(TemplateParams->size());
2920
2921 // C++0x [temp.deduct.partial]p3:
2922 // The types used to determine the ordering depend on the context in which
2923 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002924 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002925 CXXMethodDecl *Method1 = 0;
2926 CXXMethodDecl *Method2 = 0;
2927 bool IsNonStatic2 = false;
2928 bool IsNonStatic1 = false;
2929 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002930 switch (TPOC) {
2931 case TPOC_Call: {
2932 // - In the context of a function call, the function parameter types are
2933 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002934 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2935 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2936 IsNonStatic1 = Method1 && !Method1->isStatic();
2937 IsNonStatic2 = Method2 && !Method2->isStatic();
2938
2939 // C++0x [temp.func.order]p3:
2940 // [...] If only one of the function templates is a non-static
2941 // member, that function template is considered to have a new
2942 // first parameter inserted in its function parameter list. The
2943 // new parameter is of type "reference to cv A," where cv are
2944 // the cv-qualifiers of the function template (if any) and A is
2945 // the class of which the function template is a member.
2946 //
2947 // C++98/03 doesn't have this provision, so instead we drop the
2948 // first argument of the free function or static member, which
2949 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002950 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002951 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2952 IsNonStatic2 && !IsNonStatic1;
2953 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002954 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2955 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002956 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002957
2958 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002959 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2960 IsNonStatic1 && !IsNonStatic2;
2961 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002962 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2963 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002964 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002965
2966 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002967 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002968 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002969 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002970 Args2[I],
2971 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002972 Info,
2973 Deduced,
2974 QualifierComparisons))
2975 return false;
2976
2977 break;
2978 }
2979
2980 case TPOC_Conversion:
2981 // - In the context of a call to a conversion operator, the return types
2982 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002983 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002984 TemplateParams,
2985 Proto2->getResultType(),
2986 Proto1->getResultType(),
2987 Info,
2988 Deduced,
2989 QualifierComparisons))
2990 return false;
2991 break;
2992
2993 case TPOC_Other:
2994 // - In other contexts (14.6.6.2) the function template’s function type
2995 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002996 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002997 TemplateParams,
2998 FD2->getType(),
2999 FD1->getType(),
3000 Info,
3001 Deduced,
3002 QualifierComparisons))
3003 return false;
3004 break;
3005 }
3006
3007 // C++0x [temp.deduct.partial]p11:
3008 // In most cases, all template parameters must have values in order for
3009 // deduction to succeed, but for partial ordering purposes a template
3010 // parameter may remain without a value provided it is not used in the
3011 // types being used for partial ordering. [ Note: a template parameter used
3012 // in a non-deduced context is considered used. -end note]
3013 unsigned ArgIdx = 0, NumArgs = Deduced.size();
3014 for (; ArgIdx != NumArgs; ++ArgIdx)
3015 if (Deduced[ArgIdx].isNull())
3016 break;
3017
3018 if (ArgIdx == NumArgs) {
3019 // All template arguments were deduced. FT1 is at least as specialized
3020 // as FT2.
3021 return true;
3022 }
3023
Douglas Gregore73bb602009-09-14 21:25:05 +00003024 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00003025 llvm::SmallVector<bool, 4> UsedParameters;
3026 UsedParameters.resize(TemplateParams->size());
3027 switch (TPOC) {
3028 case TPOC_Call: {
3029 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00003030 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
3031 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
3032 TemplateParams->getDepth(), UsedParameters);
3033 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003034 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
3035 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003036 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003037 break;
3038 }
3039
3040 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003041 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
3042 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003043 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003044 break;
3045
3046 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00003047 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
3048 TemplateParams->getDepth(),
3049 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00003050 break;
3051 }
3052
3053 for (; ArgIdx != NumArgs; ++ArgIdx)
3054 // If this argument had no value deduced but was used in one of the types
3055 // used for partial ordering, then deduction fails.
3056 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
3057 return false;
3058
3059 return true;
3060}
3061
3062
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003063/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003064/// to the rules of function template partial ordering (C++ [temp.func.order]).
3065///
3066/// \param FT1 the first function template
3067///
3068/// \param FT2 the second function template
3069///
Douglas Gregor8a514912009-09-14 18:39:43 +00003070/// \param TPOC the context in which we are performing partial ordering of
3071/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00003072///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003073/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003074/// template is more specialized, returns NULL.
3075FunctionTemplateDecl *
3076Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
3077 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00003078 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00003079 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00003080 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00003081 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
3082 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00003083 &QualifierComparisons);
3084
3085 if (Better1 != Better2) // We have a clear winner
3086 return Better1? FT1 : FT2;
3087
3088 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003089 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00003090
3091
3092 // C++0x [temp.deduct.partial]p10:
3093 // If for each type being considered a given template is at least as
3094 // specialized for all types and more specialized for some set of types and
3095 // the other template is not more specialized for any types or is not at
3096 // least as specialized for any types, then the given template is more
3097 // specialized than the other template. Otherwise, neither template is more
3098 // specialized than the other.
3099 Better1 = false;
3100 Better2 = false;
3101 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
3102 // C++0x [temp.deduct.partial]p9:
3103 // If, for a given type, deduction succeeds in both directions (i.e., the
3104 // types are identical after the transformations above) and if the type
3105 // from the argument template is more cv-qualified than the type from the
3106 // parameter template (as described above) that type is considered to be
3107 // more specialized than the other. If neither type is more cv-qualified
3108 // than the other then neither type is more specialized than the other.
3109 switch (QualifierComparisons[I]) {
3110 case NeitherMoreQualified:
3111 break;
3112
3113 case ParamMoreQualified:
3114 Better1 = true;
3115 if (Better2)
3116 return 0;
3117 break;
3118
3119 case ArgMoreQualified:
3120 Better2 = true;
3121 if (Better1)
3122 return 0;
3123 break;
3124 }
3125 }
3126
3127 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003128 if (Better1)
3129 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00003130 else if (Better2)
3131 return FT2;
3132 else
3133 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003134}
Douglas Gregor83314aa2009-07-08 20:55:45 +00003135
Douglas Gregord5a423b2009-09-25 18:43:00 +00003136/// \brief Determine if the two templates are equivalent.
3137static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
3138 if (T1 == T2)
3139 return true;
3140
3141 if (!T1 || !T2)
3142 return false;
3143
3144 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
3145}
3146
3147/// \brief Retrieve the most specialized of the given function template
3148/// specializations.
3149///
John McCallc373d482010-01-27 01:50:18 +00003150/// \param SpecBegin the start iterator of the function template
3151/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003152///
John McCallc373d482010-01-27 01:50:18 +00003153/// \param SpecEnd the end iterator of the function template
3154/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003155///
3156/// \param TPOC the partial ordering context to use to compare the function
3157/// template specializations.
3158///
3159/// \param Loc the location where the ambiguity or no-specializations
3160/// diagnostic should occur.
3161///
3162/// \param NoneDiag partial diagnostic used to diagnose cases where there are
3163/// no matching candidates.
3164///
3165/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
3166/// occurs.
3167///
3168/// \param CandidateDiag partial diagnostic used for each function template
3169/// specialization that is a candidate in the ambiguous ordering. One parameter
3170/// in this diagnostic should be unbound, which will correspond to the string
3171/// describing the template arguments for the function template specialization.
3172///
3173/// \param Index if non-NULL and the result of this function is non-nULL,
3174/// receives the index corresponding to the resulting function template
3175/// specialization.
3176///
3177/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003178/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003179///
3180/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3181/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003182UnresolvedSetIterator
3183Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3184 UnresolvedSetIterator SpecEnd,
3185 TemplatePartialOrderingContext TPOC,
3186 SourceLocation Loc,
3187 const PartialDiagnostic &NoneDiag,
3188 const PartialDiagnostic &AmbigDiag,
3189 const PartialDiagnostic &CandidateDiag) {
3190 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003191 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003192 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003193 }
3194
John McCallc373d482010-01-27 01:50:18 +00003195 if (SpecBegin + 1 == SpecEnd)
3196 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003197
3198 // Find the function template that is better than all of the templates it
3199 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003200 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003201 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003202 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003203 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003204 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3205 FunctionTemplateDecl *Challenger
3206 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003207 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003208 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003209 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003210 Challenger)) {
3211 Best = I;
3212 BestTemplate = Challenger;
3213 }
3214 }
3215
3216 // Make sure that the "best" function template is more specialized than all
3217 // of the others.
3218 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003219 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3220 FunctionTemplateDecl *Challenger
3221 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003222 if (I != Best &&
3223 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003224 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003225 BestTemplate)) {
3226 Ambiguous = true;
3227 break;
3228 }
3229 }
3230
3231 if (!Ambiguous) {
3232 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003233 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003234 }
3235
3236 // Diagnose the ambiguity.
3237 Diag(Loc, AmbigDiag);
3238
3239 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003240 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3241 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003242 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003243 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3244 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003245
John McCallc373d482010-01-27 01:50:18 +00003246 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003247}
3248
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003249/// \brief Returns the more specialized class template partial specialization
3250/// according to the rules of partial ordering of class template partial
3251/// specializations (C++ [temp.class.order]).
3252///
3253/// \param PS1 the first class template partial specialization
3254///
3255/// \param PS2 the second class template partial specialization
3256///
3257/// \returns the more specialized class template partial specialization. If
3258/// neither partial specialization is more specialized, returns NULL.
3259ClassTemplatePartialSpecializationDecl *
3260Sema::getMoreSpecializedPartialSpecialization(
3261 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003262 ClassTemplatePartialSpecializationDecl *PS2,
3263 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003264 // C++ [temp.class.order]p1:
3265 // For two class template partial specializations, the first is at least as
3266 // specialized as the second if, given the following rewrite to two
3267 // function templates, the first function template is at least as
3268 // specialized as the second according to the ordering rules for function
3269 // templates (14.6.6.2):
3270 // - the first function template has the same template parameters as the
3271 // first partial specialization and has a single function parameter
3272 // whose type is a class template specialization with the template
3273 // arguments of the first partial specialization, and
3274 // - the second function template has the same template parameters as the
3275 // second partial specialization and has a single function parameter
3276 // whose type is a class template specialization with the template
3277 // arguments of the second partial specialization.
3278 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003279 // Rather than synthesize function templates, we merely perform the
3280 // equivalent partial ordering by performing deduction directly on
3281 // the template arguments of the class template partial
3282 // specializations. This computation is slightly simpler than the
3283 // general problem of function template partial ordering, because
3284 // class template partial specializations are more constrained. We
3285 // know that every template parameter is deducible from the class
3286 // template partial specialization's template arguments, for
3287 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003288 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003289 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003290
3291 QualType PT1 = PS1->getInjectedSpecializationType();
3292 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003293
3294 // Determine whether PS1 is at least as specialized as PS2
3295 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003296 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003297 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003298 PT2,
3299 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003300 Info,
3301 Deduced,
3302 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003303 if (Better1) {
3304 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3305 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003306 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3307 PS1->getTemplateArgs(),
3308 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003309 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003310
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003311 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003312 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003313 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003314 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003315 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003316 PT1,
3317 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003318 Info,
3319 Deduced,
3320 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003321 if (Better2) {
3322 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3323 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003324 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3325 PS2->getTemplateArgs(),
3326 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003327 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003328
3329 if (Better1 == Better2)
3330 return 0;
3331
3332 return Better1? PS1 : PS2;
3333}
3334
Mike Stump1eb44332009-09-09 15:08:12 +00003335static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003336MarkUsedTemplateParameters(Sema &SemaRef,
3337 const TemplateArgument &TemplateArg,
3338 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003339 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003340 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003341
Douglas Gregore73bb602009-09-14 21:25:05 +00003342/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003343/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003344static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003345MarkUsedTemplateParameters(Sema &SemaRef,
3346 const Expr *E,
3347 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003348 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003349 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003350 // We can deduce from a pack expansion.
3351 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3352 E = Expansion->getPattern();
3353
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003354 // Skip through any implicit casts we added while type-checking.
3355 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3356 E = ICE->getSubExpr();
3357
Douglas Gregore73bb602009-09-14 21:25:05 +00003358 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3359 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003360 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003361 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003362 return;
3363
Mike Stump1eb44332009-09-09 15:08:12 +00003364 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003365 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3366 if (!NTTP)
3367 return;
3368
Douglas Gregored9c0f92009-10-29 00:04:11 +00003369 if (NTTP->getDepth() == Depth)
3370 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003371}
3372
Douglas Gregore73bb602009-09-14 21:25:05 +00003373/// \brief Mark the template parameters that are used by the given
3374/// nested name specifier.
3375static void
3376MarkUsedTemplateParameters(Sema &SemaRef,
3377 NestedNameSpecifier *NNS,
3378 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003379 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003380 llvm::SmallVectorImpl<bool> &Used) {
3381 if (!NNS)
3382 return;
3383
Douglas Gregored9c0f92009-10-29 00:04:11 +00003384 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3385 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003386 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003387 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003388}
3389
3390/// \brief Mark the template parameters that are used by the given
3391/// template name.
3392static void
3393MarkUsedTemplateParameters(Sema &SemaRef,
3394 TemplateName Name,
3395 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003396 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003397 llvm::SmallVectorImpl<bool> &Used) {
3398 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3399 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003400 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3401 if (TTP->getDepth() == Depth)
3402 Used[TTP->getIndex()] = true;
3403 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003404 return;
3405 }
3406
Douglas Gregor788cd062009-11-11 01:00:40 +00003407 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3408 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3409 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003410 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003411 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3412 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003413}
3414
3415/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003416/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003417static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003418MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3419 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003420 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003421 llvm::SmallVectorImpl<bool> &Used) {
3422 if (T.isNull())
3423 return;
3424
Douglas Gregor031a5882009-06-13 00:26:55 +00003425 // Non-dependent types have nothing deducible
3426 if (!T->isDependentType())
3427 return;
3428
3429 T = SemaRef.Context.getCanonicalType(T);
3430 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003431 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003432 MarkUsedTemplateParameters(SemaRef,
3433 cast<PointerType>(T)->getPointeeType(),
3434 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003435 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003436 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003437 break;
3438
3439 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003440 MarkUsedTemplateParameters(SemaRef,
3441 cast<BlockPointerType>(T)->getPointeeType(),
3442 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003443 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003444 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003445 break;
3446
3447 case Type::LValueReference:
3448 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003449 MarkUsedTemplateParameters(SemaRef,
3450 cast<ReferenceType>(T)->getPointeeType(),
3451 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003452 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003453 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003454 break;
3455
3456 case Type::MemberPointer: {
3457 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003458 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003459 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003460 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003461 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003462 break;
3463 }
3464
3465 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003466 MarkUsedTemplateParameters(SemaRef,
3467 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003468 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003469 // Fall through to check the element type
3470
3471 case Type::ConstantArray:
3472 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003473 MarkUsedTemplateParameters(SemaRef,
3474 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003475 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003476 break;
3477
3478 case Type::Vector:
3479 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003480 MarkUsedTemplateParameters(SemaRef,
3481 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003482 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003483 break;
3484
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003485 case Type::DependentSizedExtVector: {
3486 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003487 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003488 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003489 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003490 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003491 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003492 break;
3493 }
3494
Douglas Gregor031a5882009-06-13 00:26:55 +00003495 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003496 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003497 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003498 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003499 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003500 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003501 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003502 break;
3503 }
3504
Douglas Gregored9c0f92009-10-29 00:04:11 +00003505 case Type::TemplateTypeParm: {
3506 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3507 if (TTP->getDepth() == Depth)
3508 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003509 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003510 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003511
John McCall31f17ec2010-04-27 00:57:59 +00003512 case Type::InjectedClassName:
3513 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3514 // fall through
3515
Douglas Gregor031a5882009-06-13 00:26:55 +00003516 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003517 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003518 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003519 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003520 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003521
3522 // C++0x [temp.deduct.type]p9:
3523 // If the template argument list of P contains a pack expansion that is not
3524 // the last template argument, the entire template argument list is a
3525 // non-deduced context.
3526 if (OnlyDeduced &&
3527 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3528 break;
3529
Douglas Gregore73bb602009-09-14 21:25:05 +00003530 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003531 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3532 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003533 break;
3534 }
3535
Douglas Gregore73bb602009-09-14 21:25:05 +00003536 case Type::Complex:
3537 if (!OnlyDeduced)
3538 MarkUsedTemplateParameters(SemaRef,
3539 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003540 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003541 break;
3542
Douglas Gregor4714c122010-03-31 17:34:00 +00003543 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003544 if (!OnlyDeduced)
3545 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003546 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003547 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003548 break;
3549
John McCall33500952010-06-11 00:33:02 +00003550 case Type::DependentTemplateSpecialization: {
3551 const DependentTemplateSpecializationType *Spec
3552 = cast<DependentTemplateSpecializationType>(T);
3553 if (!OnlyDeduced)
3554 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3555 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003556
3557 // C++0x [temp.deduct.type]p9:
3558 // If the template argument list of P contains a pack expansion that is not
3559 // the last template argument, the entire template argument list is a
3560 // non-deduced context.
3561 if (OnlyDeduced &&
3562 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3563 break;
3564
John McCall33500952010-06-11 00:33:02 +00003565 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3566 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3567 Used);
3568 break;
3569 }
3570
John McCallad5e7382010-03-01 23:49:17 +00003571 case Type::TypeOf:
3572 if (!OnlyDeduced)
3573 MarkUsedTemplateParameters(SemaRef,
3574 cast<TypeOfType>(T)->getUnderlyingType(),
3575 OnlyDeduced, Depth, Used);
3576 break;
3577
3578 case Type::TypeOfExpr:
3579 if (!OnlyDeduced)
3580 MarkUsedTemplateParameters(SemaRef,
3581 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3582 OnlyDeduced, Depth, Used);
3583 break;
3584
3585 case Type::Decltype:
3586 if (!OnlyDeduced)
3587 MarkUsedTemplateParameters(SemaRef,
3588 cast<DecltypeType>(T)->getUnderlyingExpr(),
3589 OnlyDeduced, Depth, Used);
3590 break;
3591
Douglas Gregor7536dd52010-12-20 02:24:11 +00003592 case Type::PackExpansion:
3593 MarkUsedTemplateParameters(SemaRef,
3594 cast<PackExpansionType>(T)->getPattern(),
3595 OnlyDeduced, Depth, Used);
3596 break;
3597
Douglas Gregore73bb602009-09-14 21:25:05 +00003598 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003599 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003600 case Type::VariableArray:
3601 case Type::FunctionNoProto:
3602 case Type::Record:
3603 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003604 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003605 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003606 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003607 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003608#define TYPE(Class, Base)
3609#define ABSTRACT_TYPE(Class, Base)
3610#define DEPENDENT_TYPE(Class, Base)
3611#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3612#include "clang/AST/TypeNodes.def"
3613 break;
3614 }
3615}
3616
Douglas Gregore73bb602009-09-14 21:25:05 +00003617/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003618/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003619static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003620MarkUsedTemplateParameters(Sema &SemaRef,
3621 const TemplateArgument &TemplateArg,
3622 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003623 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003624 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003625 switch (TemplateArg.getKind()) {
3626 case TemplateArgument::Null:
3627 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003628 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003629 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003630
Douglas Gregor031a5882009-06-13 00:26:55 +00003631 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003632 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003633 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003634 break;
3635
Douglas Gregor788cd062009-11-11 01:00:40 +00003636 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003637 case TemplateArgument::TemplateExpansion:
3638 MarkUsedTemplateParameters(SemaRef,
3639 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003640 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003641 break;
3642
3643 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003644 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003645 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003646 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003647
Anders Carlssond01b1da2009-06-15 17:04:53 +00003648 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003649 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3650 PEnd = TemplateArg.pack_end();
3651 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003652 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003653 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003654 }
3655}
3656
3657/// \brief Mark the template parameters can be deduced by the given
3658/// template argument list.
3659///
3660/// \param TemplateArgs the template argument list from which template
3661/// parameters will be deduced.
3662///
3663/// \param Deduced a bit vector whose elements will be set to \c true
3664/// to indicate when the corresponding template parameter will be
3665/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003666void
Douglas Gregore73bb602009-09-14 21:25:05 +00003667Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003668 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003669 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003670 // C++0x [temp.deduct.type]p9:
3671 // If the template argument list of P contains a pack expansion that is not
3672 // the last template argument, the entire template argument list is a
3673 // non-deduced context.
3674 if (OnlyDeduced &&
3675 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3676 return;
3677
Douglas Gregor031a5882009-06-13 00:26:55 +00003678 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003679 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3680 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003681}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003682
3683/// \brief Marks all of the template parameters that will be deduced by a
3684/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003685void
3686Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3687 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003688 TemplateParameterList *TemplateParams
3689 = FunctionTemplate->getTemplateParameters();
3690 Deduced.clear();
3691 Deduced.resize(TemplateParams->size());
3692
3693 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3694 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3695 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003696 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003697}