blob: 603a7efea5f100126ac74d42703a53fc4b0d10e6 [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregor20a55e22010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCall7cd088e2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000020#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
Douglas Gregore02e2622010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000026
27namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregor508f1c82009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
52 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor0b9247f2009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor9d0e4412010-03-26 05:50:28 +000058/// \brief Compare two APSInts, extending and switching the sign as
59/// necessary to compare their values regardless of underlying type.
60static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
61 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000065
66 // If there is a signedness mismatch, correct it.
67 if (X.isSigned() != Y.isSigned()) {
68 // If the signed value is negative, then the values cannot be the same.
69 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
70 return false;
71
72 Y.setIsSigned(true);
73 X.setIsSigned(true);
74 }
75
76 return X == Y;
77}
78
Douglas Gregorf67875d2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000083 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000086
Douglas Gregor20a55e22010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
Douglas Gregor603cfb42011-01-05 23:12:31 +000090 QualType Param,
91 QualType Arg,
92 TemplateDeductionInfo &Info,
93 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 unsigned TDF);
95
96static Sema::TemplateDeductionResult
97DeduceTemplateArguments(Sema &S,
98 TemplateParameterList *TemplateParams,
Douglas Gregor20a55e22010-12-22 18:17:10 +000099 const TemplateArgument *Params, unsigned NumParams,
100 const TemplateArgument *Args, unsigned NumArgs,
101 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +0000102 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
103 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor20a55e22010-12-22 18:17:10 +0000104
Douglas Gregor199d9912009-06-05 00:53:49 +0000105/// \brief If the given expression is of a form that permits the deduction
106/// of a non-type template parameter, return the declaration of that
107/// non-type template parameter.
108static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
109 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
110 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Douglas Gregor199d9912009-06-05 00:53:49 +0000112 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
113 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Douglas Gregor199d9912009-06-05 00:53:49 +0000115 return 0;
116}
117
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000118/// \brief Determine whether two declaration pointers refer to the same
119/// declaration.
120static bool isSameDeclaration(Decl *X, Decl *Y) {
121 if (!X || !Y)
122 return !X && !Y;
123
124 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
125 X = NX->getUnderlyingDecl();
126 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
127 Y = NY->getUnderlyingDecl();
128
129 return X->getCanonicalDecl() == Y->getCanonicalDecl();
130}
131
132/// \brief Verify that the given, deduced template arguments are compatible.
133///
134/// \returns The deduced template argument, or a NULL template argument if
135/// the deduced template arguments were incompatible.
136static DeducedTemplateArgument
137checkDeducedTemplateArguments(ASTContext &Context,
138 const DeducedTemplateArgument &X,
139 const DeducedTemplateArgument &Y) {
140 // We have no deduction for one or both of the arguments; they're compatible.
141 if (X.isNull())
142 return Y;
143 if (Y.isNull())
144 return X;
145
146 switch (X.getKind()) {
147 case TemplateArgument::Null:
148 llvm_unreachable("Non-deduced template arguments handled above");
149
150 case TemplateArgument::Type:
151 // If two template type arguments have the same type, they're compatible.
152 if (Y.getKind() == TemplateArgument::Type &&
153 Context.hasSameType(X.getAsType(), Y.getAsType()))
154 return X;
155
156 return DeducedTemplateArgument();
157
158 case TemplateArgument::Integral:
159 // If we deduced a constant in one case and either a dependent expression or
160 // declaration in another case, keep the integral constant.
161 // If both are integral constants with the same value, keep that value.
162 if (Y.getKind() == TemplateArgument::Expression ||
163 Y.getKind() == TemplateArgument::Declaration ||
164 (Y.getKind() == TemplateArgument::Integral &&
165 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
166 return DeducedTemplateArgument(X,
167 X.wasDeducedFromArrayBound() &&
168 Y.wasDeducedFromArrayBound());
169
170 // All other combinations are incompatible.
171 return DeducedTemplateArgument();
172
173 case TemplateArgument::Template:
174 if (Y.getKind() == TemplateArgument::Template &&
175 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
176 return X;
177
178 // All other combinations are incompatible.
179 return DeducedTemplateArgument();
Douglas Gregora7fc9012011-01-05 18:58:31 +0000180
181 case TemplateArgument::TemplateExpansion:
182 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
183 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
184 Y.getAsTemplateOrTemplatePattern()))
185 return X;
186
187 // All other combinations are incompatible.
188 return DeducedTemplateArgument();
189
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000190 case TemplateArgument::Expression:
191 // If we deduced a dependent expression in one case and either an integral
192 // constant or a declaration in another case, keep the integral constant
193 // or declaration.
194 if (Y.getKind() == TemplateArgument::Integral ||
195 Y.getKind() == TemplateArgument::Declaration)
196 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
197 Y.wasDeducedFromArrayBound());
198
199 if (Y.getKind() == TemplateArgument::Expression) {
200 // Compare the expressions for equality
201 llvm::FoldingSetNodeID ID1, ID2;
202 X.getAsExpr()->Profile(ID1, Context, true);
203 Y.getAsExpr()->Profile(ID2, Context, true);
204 if (ID1 == ID2)
205 return X;
206 }
207
208 // All other combinations are incompatible.
209 return DeducedTemplateArgument();
210
211 case TemplateArgument::Declaration:
212 // If we deduced a declaration and a dependent expression, keep the
213 // declaration.
214 if (Y.getKind() == TemplateArgument::Expression)
215 return X;
216
217 // If we deduced a declaration and an integral constant, keep the
218 // integral constant.
219 if (Y.getKind() == TemplateArgument::Integral)
220 return Y;
221
222 // If we deduced two declarations, make sure they they refer to the
223 // same declaration.
224 if (Y.getKind() == TemplateArgument::Declaration &&
225 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
226 return X;
227
228 // All other combinations are incompatible.
229 return DeducedTemplateArgument();
230
231 case TemplateArgument::Pack:
232 if (Y.getKind() != TemplateArgument::Pack ||
233 X.pack_size() != Y.pack_size())
234 return DeducedTemplateArgument();
235
236 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
237 XAEnd = X.pack_end(),
238 YA = Y.pack_begin();
239 XA != XAEnd; ++XA, ++YA) {
Douglas Gregor135ffa72011-01-05 21:00:53 +0000240 if (checkDeducedTemplateArguments(Context,
241 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
242 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
243 .isNull())
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000244 return DeducedTemplateArgument();
245 }
246
247 return X;
248 }
249
250 return DeducedTemplateArgument();
251}
252
Mike Stump1eb44332009-09-09 15:08:12 +0000253/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000254/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000255static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000256DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000257 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000258 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000259 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000260 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000261 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000262 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000263 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000265 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
266 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
267 Deduced[NTTP->getIndex()],
268 NewDeduced);
269 if (Result.isNull()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000270 Info.Param = NTTP;
271 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000272 Info.SecondArg = NewDeduced;
273 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000274 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000275
276 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000277 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000278}
279
Mike Stump1eb44332009-09-09 15:08:12 +0000280/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000281/// from the given type- or value-dependent expression.
282///
283/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000284static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000285DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000286 NonTypeTemplateParmDecl *NTTP,
287 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000288 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000289 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000290 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000291 "Cannot deduce non-type template argument with depth > 0");
292 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
293 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000295 DeducedTemplateArgument NewDeduced(Value);
296 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
297 Deduced[NTTP->getIndex()],
298 NewDeduced);
299
300 if (Result.isNull()) {
301 Info.Param = NTTP;
302 Info.FirstArg = Deduced[NTTP->getIndex()];
303 Info.SecondArg = NewDeduced;
304 return Sema::TDK_Inconsistent;
Douglas Gregor199d9912009-06-05 00:53:49 +0000305 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000306
307 Deduced[NTTP->getIndex()] = Result;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000308 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000309}
310
Douglas Gregor15755cb2009-11-13 23:45:44 +0000311/// \brief Deduce the value of the given non-type template parameter
312/// from the given declaration.
313///
314/// \returns true if deduction succeeded, false otherwise.
315static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000316DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000317 NonTypeTemplateParmDecl *NTTP,
318 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000319 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000320 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000321 assert(NTTP->getDepth() == 0 &&
322 "Cannot deduce non-type template argument with depth > 0");
323
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000324 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
325 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
326 Deduced[NTTP->getIndex()],
327 NewDeduced);
328 if (Result.isNull()) {
329 Info.Param = NTTP;
330 Info.FirstArg = Deduced[NTTP->getIndex()];
331 Info.SecondArg = NewDeduced;
332 return Sema::TDK_Inconsistent;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000333 }
334
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000335 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor15755cb2009-11-13 23:45:44 +0000336 return Sema::TDK_Success;
337}
338
Douglas Gregorf67875d2009-06-12 18:26:56 +0000339static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000340DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000341 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000342 TemplateName Param,
343 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000344 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000345 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000346 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000347 if (!ParamDecl) {
348 // The parameter type is dependent and is not a template template parameter,
349 // so there is nothing that we can deduce.
350 return Sema::TDK_Success;
351 }
352
353 if (TemplateTemplateParmDecl *TempParam
354 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000355 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
356 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
357 Deduced[TempParam->getIndex()],
358 NewDeduced);
359 if (Result.isNull()) {
360 Info.Param = TempParam;
361 Info.FirstArg = Deduced[TempParam->getIndex()];
362 Info.SecondArg = NewDeduced;
363 return Sema::TDK_Inconsistent;
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000364 }
365
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000366 Deduced[TempParam->getIndex()] = Result;
367 return Sema::TDK_Success;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000368 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000369
370 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000371 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000372 return Sema::TDK_Success;
373
374 // Mismatch of non-dependent template parameter to argument.
375 Info.FirstArg = TemplateArgument(Param);
376 Info.SecondArg = TemplateArgument(Arg);
377 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000378}
379
Mike Stump1eb44332009-09-09 15:08:12 +0000380/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000381/// type (which is a template-id) with the template argument type.
382///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000383/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000384///
385/// \param TemplateParams the template parameters that we are deducing
386///
387/// \param Param the parameter type
388///
389/// \param Arg the argument type
390///
391/// \param Info information about the template argument deduction itself
392///
393/// \param Deduced the deduced template arguments
394///
395/// \returns the result of template argument deduction so far. Note that a
396/// "success" result means that template argument deduction has not yet failed,
397/// but it may still fail, later, for other reasons.
398static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000399DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000400 TemplateParameterList *TemplateParams,
401 const TemplateSpecializationType *Param,
402 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000403 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000404 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000405 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000407 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000408 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000409 = dyn_cast<TemplateSpecializationType>(Arg)) {
410 // Perform template argument deduction for the template name.
411 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000412 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000413 Param->getTemplateName(),
414 SpecArg->getTemplateName(),
415 Info, Deduced))
416 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000419 // Perform template argument deduction on each template
Douglas Gregor0972c862010-12-22 18:55:49 +0000420 // argument. Ignore any missing/extra arguments, since they could be
421 // filled in by default arguments.
Douglas Gregor20a55e22010-12-22 18:17:10 +0000422 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor0972c862010-12-22 18:55:49 +0000423 Param->getArgs(), Param->getNumArgs(),
424 SpecArg->getArgs(), SpecArg->getNumArgs(),
425 Info, Deduced,
426 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000427 }
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000429 // If the argument type is a class template specialization, we
430 // perform template argument deduction using its template
431 // arguments.
432 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
433 if (!RecordArg)
434 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
436 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000437 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
438 if (!SpecArg)
439 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000441 // Perform template argument deduction for the template name.
442 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000443 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000444 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000445 Param->getTemplateName(),
446 TemplateName(SpecArg->getSpecializedTemplate()),
447 Info, Deduced))
448 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Douglas Gregor20a55e22010-12-22 18:17:10 +0000450 // Perform template argument deduction for the template arguments.
451 return DeduceTemplateArguments(S, TemplateParams,
452 Param->getArgs(), Param->getNumArgs(),
453 SpecArg->getTemplateArgs().data(),
454 SpecArg->getTemplateArgs().size(),
455 Info, Deduced);
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000456}
457
John McCallcd05e812010-08-28 22:14:41 +0000458/// \brief Determines whether the given type is an opaque type that
459/// might be more qualified when instantiated.
460static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
461 switch (T->getTypeClass()) {
462 case Type::TypeOfExpr:
463 case Type::TypeOf:
464 case Type::DependentName:
465 case Type::Decltype:
466 case Type::UnresolvedUsing:
467 return true;
468
469 case Type::ConstantArray:
470 case Type::IncompleteArray:
471 case Type::VariableArray:
472 case Type::DependentSizedArray:
473 return IsPossiblyOpaquelyQualifiedType(
474 cast<ArrayType>(T)->getElementType());
475
476 default:
477 return false;
478 }
479}
480
Douglas Gregor603cfb42011-01-05 23:12:31 +0000481/// \brief Retrieve the depth and index of an unexpanded parameter pack.
482static std::pair<unsigned, unsigned>
483getDepthAndIndex(UnexpandedParameterPack UPP) {
484 if (const TemplateTypeParmType *TTP
485 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
486 return std::make_pair(TTP->getDepth(), TTP->getIndex());
487
488 NamedDecl *ND = UPP.first.get<NamedDecl *>();
489 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
490 return std::make_pair(TTP->getDepth(), TTP->getIndex());
491
492 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
493 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
494
495 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
496 return std::make_pair(TTP->getDepth(), TTP->getIndex());
497}
498
499/// \brief Helper function to build a TemplateParameter when we don't
500/// know its type statically.
501static TemplateParameter makeTemplateParameter(Decl *D) {
502 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
503 return TemplateParameter(TTP);
504 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
505 return TemplateParameter(NTTP);
506
507 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
508}
509
510/// \brief Deduce the template arguments by comparing the list of parameter
511/// types to the list of argument types, as in the parameter-type-lists of
512/// function types (C++ [temp.deduct.type]p10).
513///
514/// \param S The semantic analysis object within which we are deducing
515///
516/// \param TemplateParams The template parameters that we are deducing
517///
518/// \param Params The list of parameter types
519///
520/// \param NumParams The number of types in \c Params
521///
522/// \param Args The list of argument types
523///
524/// \param NumArgs The number of types in \c Args
525///
526/// \param Info information about the template argument deduction itself
527///
528/// \param Deduced the deduced template arguments
529///
530/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
531/// how template argument deduction is performed.
532///
533/// \returns the result of template argument deduction so far. Note that a
534/// "success" result means that template argument deduction has not yet failed,
535/// but it may still fail, later, for other reasons.
536static Sema::TemplateDeductionResult
537DeduceTemplateArguments(Sema &S,
538 TemplateParameterList *TemplateParams,
539 const QualType *Params, unsigned NumParams,
540 const QualType *Args, unsigned NumArgs,
541 TemplateDeductionInfo &Info,
542 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
543 unsigned TDF) {
Douglas Gregor0bbacf82011-01-05 23:23:17 +0000544 // Fast-path check to see if we have too many/too few arguments.
545 if (NumParams != NumArgs &&
546 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
547 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
548 return NumArgs < NumParams ? Sema::TDK_TooFewArguments
549 : Sema::TDK_TooManyArguments;
Douglas Gregor603cfb42011-01-05 23:12:31 +0000550
551 // C++0x [temp.deduct.type]p10:
552 // Similarly, if P has a form that contains (T), then each parameter type
553 // Pi of the respective parameter-type- list of P is compared with the
554 // corresponding parameter type Ai of the corresponding parameter-type-list
555 // of A. [...]
556 unsigned ArgIdx = 0, ParamIdx = 0;
557 for (; ParamIdx != NumParams; ++ParamIdx) {
558 // Check argument types.
559 const PackExpansionType *Expansion
560 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
561 if (!Expansion) {
562 // Simple case: compare the parameter and argument types at this point.
563
564 // Make sure we have an argument.
565 if (ArgIdx >= NumArgs)
566 return Sema::TDK_TooFewArguments;
567
568 if (Sema::TemplateDeductionResult Result
569 = DeduceTemplateArguments(S, TemplateParams,
570 Params[ParamIdx],
571 Args[ArgIdx],
572 Info, Deduced, TDF))
573 return Result;
574
575 ++ArgIdx;
576 continue;
577 }
578
579 // C++0x [temp.deduct.type]p10:
580 // If the parameter-declaration corresponding to Pi is a function
581 // parameter pack, then the type of its declarator- id is compared with
582 // each remaining parameter type in the parameter-type-list of A. Each
583 // comparison deduces template arguments for subsequent positions in the
584 // template parameter packs expanded by the function parameter pack.
585
586 // Compute the set of template parameter indices that correspond to
587 // parameter packs expanded by the pack expansion.
588 llvm::SmallVector<unsigned, 2> PackIndices;
589 QualType Pattern = Expansion->getPattern();
590 {
591 llvm::BitVector SawIndices(TemplateParams->size());
592 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
593 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
594 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
595 unsigned Depth, Index;
596 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
597 if (Depth == 0 && !SawIndices[Index]) {
598 SawIndices[Index] = true;
599 PackIndices.push_back(Index);
600 }
601 }
602 }
603 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
604
605 // Save the deduced template arguments for each parameter pack expanded
606 // by this pack expansion, then clear out the deduction.
607 llvm::SmallVector<DeducedTemplateArgument, 2>
608 SavedPacks(PackIndices.size());
609 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
610 SavedPacks[I] = Deduced[PackIndices[I]];
611 Deduced[PackIndices[I]] = DeducedTemplateArgument();
612 }
613
614 // Keep track of the deduced template arguments for each parameter pack
615 // expanded by this pack expansion (the outer index) and for each
616 // template argument (the inner SmallVectors).
617 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
618 NewlyDeducedPacks(PackIndices.size());
619 bool HasAnyArguments = false;
620 for (; ArgIdx < NumArgs; ++ArgIdx) {
621 HasAnyArguments = true;
622
623 // Deduce template arguments from the pattern.
624 if (Sema::TemplateDeductionResult Result
625 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
626 Info, Deduced))
627 return Result;
628
629 // Capture the deduced template arguments for each parameter pack expanded
630 // by this pack expansion, add them to the list of arguments we've deduced
631 // for that pack, then clear out the deduced argument.
632 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
633 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
634 if (!DeducedArg.isNull()) {
635 NewlyDeducedPacks[I].push_back(DeducedArg);
636 DeducedArg = DeducedTemplateArgument();
637 }
638 }
639 }
640
641 // Build argument packs for each of the parameter packs expanded by this
642 // pack expansion.
643 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
644 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
645 // We were not able to deduce anything for this parameter pack,
646 // so just restore the saved argument pack.
647 Deduced[PackIndices[I]] = SavedPacks[I];
648 continue;
649 }
650
651 DeducedTemplateArgument NewPack;
652
653 if (NewlyDeducedPacks[I].empty()) {
654 // If we deduced an empty argument pack, create it now.
655 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
656 } else {
657 TemplateArgument *ArgumentPack
658 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
659 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
660 ArgumentPack);
661 NewPack
662 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
663 NewlyDeducedPacks[I].size()),
664 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
665 }
666
667 DeducedTemplateArgument Result
668 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
669 if (Result.isNull()) {
670 Info.Param
671 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
672 Info.FirstArg = SavedPacks[I];
673 Info.SecondArg = NewPack;
674 return Sema::TDK_Inconsistent;
675 }
676
677 Deduced[PackIndices[I]] = Result;
678 }
679 }
680
681 // Make sure we don't have any extra arguments.
682 if (ArgIdx < NumArgs)
683 return Sema::TDK_TooManyArguments;
684
685 return Sema::TDK_Success;
686}
687
Douglas Gregor500d3312009-06-26 18:27:22 +0000688/// \brief Deduce the template arguments by comparing the parameter type and
689/// the argument type (C++ [temp.deduct.type]).
690///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000691/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000692///
693/// \param TemplateParams the template parameters that we are deducing
694///
695/// \param ParamIn the parameter type
696///
697/// \param ArgIn the argument type
698///
699/// \param Info information about the template argument deduction itself
700///
701/// \param Deduced the deduced template arguments
702///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000703/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000704/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000705///
706/// \returns the result of template argument deduction so far. Note that a
707/// "success" result means that template argument deduction has not yet failed,
708/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000709static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000710DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000711 TemplateParameterList *TemplateParams,
712 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000713 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000714 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000715 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000716 // We only want to look at the canonical types, since typedefs and
717 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000718 QualType Param = S.Context.getCanonicalType(ParamIn);
719 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000720
Douglas Gregor500d3312009-06-26 18:27:22 +0000721 // C++0x [temp.deduct.call]p4 bullet 1:
722 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000723 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000724 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000725 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000726 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000727 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000728 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
729 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000730 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000731 }
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000733 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000734 if (!Param->isDependentType()) {
735 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
736
737 return Sema::TDK_NonDeducedMismatch;
738 }
739
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000740 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000741 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000742
Douglas Gregor199d9912009-06-05 00:53:49 +0000743 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000744 // A template type argument T, a template template argument TT or a
745 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000746 // the following forms:
747 //
748 // T
749 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000750 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000751 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000752 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000753 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000755 // If the argument type is an array type, move the qualifiers up to the
756 // top level, so they can be matched with the qualifiers on the parameter.
757 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000758 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000759 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000760 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000761 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000762 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000763 RecanonicalizeArg = true;
764 }
765 }
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000767 // The argument type can not be less qualified than the parameter
768 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000769 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000770 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000771 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000772 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000773 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000774 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000775
776 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000777 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000778 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000779
780 // local manipulation is okay because it's canonical
781 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000782 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000783 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000785 DeducedTemplateArgument NewDeduced(DeducedType);
786 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
787 Deduced[Index],
788 NewDeduced);
789 if (Result.isNull()) {
790 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
791 Info.FirstArg = Deduced[Index];
792 Info.SecondArg = NewDeduced;
793 return Sema::TDK_Inconsistent;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000794 }
Douglas Gregor0d80abc2010-12-22 23:09:49 +0000795
796 Deduced[Index] = Result;
797 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000798 }
799
Douglas Gregorf67875d2009-06-12 18:26:56 +0000800 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000801 Info.FirstArg = TemplateArgument(ParamIn);
802 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000803
Douglas Gregor508f1c82009-06-26 23:10:12 +0000804 // Check the cv-qualifiers on the parameter and argument types.
805 if (!(TDF & TDF_IgnoreQualifiers)) {
806 if (TDF & TDF_ParamWithReferenceType) {
807 if (Param.isMoreQualifiedThan(Arg))
808 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000809 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000810 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000811 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000812 }
813 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000814
Douglas Gregord560d502009-06-04 00:21:18 +0000815 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000816 // No deduction possible for these types
817 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000818 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Douglas Gregor199d9912009-06-05 00:53:49 +0000820 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000821 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000822 QualType PointeeType;
823 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
824 PointeeType = PointerArg->getPointeeType();
825 } else if (const ObjCObjectPointerType *PointerArg
826 = Arg->getAs<ObjCObjectPointerType>()) {
827 PointeeType = PointerArg->getPointeeType();
828 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000829 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Douglas Gregor41128772009-06-26 23:27:24 +0000832 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000833 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000834 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000835 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000836 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Douglas Gregor199d9912009-06-05 00:53:49 +0000839 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000840 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000841 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000842 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000843 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000845 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000846 cast<LValueReferenceType>(Param)->getPointeeType(),
847 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000848 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000849 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000850
Douglas Gregor199d9912009-06-05 00:53:49 +0000851 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000852 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000853 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000854 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000855 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000857 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000858 cast<RValueReferenceType>(Param)->getPointeeType(),
859 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000860 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregor199d9912009-06-05 00:53:49 +0000863 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000864 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000865 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000866 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000867 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000868 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000869
John McCalle4f26e52010-08-19 00:20:19 +0000870 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000871 return DeduceTemplateArguments(S, TemplateParams,
872 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000873 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000874 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000875 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000876
877 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000878 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000879 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000880 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000881 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000882 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000883
884 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000885 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000886 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000887 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
John McCalle4f26e52010-08-19 00:20:19 +0000889 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000890 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000891 ConstantArrayParm->getElementType(),
892 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000893 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000894 }
895
Douglas Gregor199d9912009-06-05 00:53:49 +0000896 // type [i]
897 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000898 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000899 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000900 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000901
John McCalle4f26e52010-08-19 00:20:19 +0000902 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
903
Douglas Gregor199d9912009-06-05 00:53:49 +0000904 // Check the element type of the arrays
905 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000906 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000907 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000908 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000909 DependentArrayParm->getElementType(),
910 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000911 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000912 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Douglas Gregor199d9912009-06-05 00:53:49 +0000914 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000915 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000916 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
917 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000918 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
920 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000921 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000922 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000923 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000924 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000925 = dyn_cast<ConstantArrayType>(ArrayArg)) {
926 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000927 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
928 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000929 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000930 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000931 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000932 if (const DependentSizedArrayType *DependentArrayArg
933 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor34c2f8c2010-12-22 23:15:38 +0000934 if (DependentArrayArg->getSizeExpr())
935 return DeduceNonTypeTemplateArgument(S, NTTP,
936 DependentArrayArg->getSizeExpr(),
937 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Douglas Gregor199d9912009-06-05 00:53:49 +0000939 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000940 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
943 // type(*)(T)
944 // T(*)()
945 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000946 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000947 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000948 dyn_cast<FunctionProtoType>(Arg);
949 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000950 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
952 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000953 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000954
Mike Stump1eb44332009-09-09 15:08:12 +0000955 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000956 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000957 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000959 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000960 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000961
Anders Carlssona27fad52009-06-08 15:19:08 +0000962 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000963 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000964 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000965 FunctionProtoParam->getResultType(),
966 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000967 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000968 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Douglas Gregor603cfb42011-01-05 23:12:31 +0000970 return DeduceTemplateArguments(S, TemplateParams,
971 FunctionProtoParam->arg_type_begin(),
972 FunctionProtoParam->getNumArgs(),
973 FunctionProtoArg->arg_type_begin(),
974 FunctionProtoArg->getNumArgs(),
975 Info, Deduced, 0);
Anders Carlssona27fad52009-06-08 15:19:08 +0000976 }
Mike Stump1eb44332009-09-09 15:08:12 +0000977
John McCall3cb0ebd2010-03-10 03:28:59 +0000978 case Type::InjectedClassName: {
979 // Treat a template's injected-class-name as if the template
980 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000981 Param = cast<InjectedClassNameType>(Param)
982 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000983 assert(isa<TemplateSpecializationType>(Param) &&
984 "injected class name is not a template specialization type");
985 // fall through
986 }
987
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000988 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000989 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000990 // TT<T>
991 // TT<i>
992 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000993 case Type::TemplateSpecialization: {
994 const TemplateSpecializationType *SpecParam
995 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000997 // Try to deduce template arguments from the template-id.
998 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000999 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001000 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Douglas Gregor4a5c15f2009-09-30 22:13:51 +00001002 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001003 // C++ [temp.deduct.call]p3b3:
1004 // If P is a class, and P has the form template-id, then A can be a
1005 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +00001006 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001007 // class pointed to by the deduced A.
1008 //
1009 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +00001010 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001011 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001012 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1013 // We cannot inspect base classes as part of deduction when the type
1014 // is incomplete, so either instantiate any templates necessary to
1015 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +00001016 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001017 return Result;
1018
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001019 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +00001020 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001021 // ToVisit is our stack of records that we still need to visit.
1022 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1023 llvm::SmallVector<const RecordType *, 8> ToVisit;
1024 ToVisit.push_back(RecordT);
1025 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +00001026 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
1027 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001028 while (!ToVisit.empty()) {
1029 // Retrieve the next class in the inheritance hierarchy.
1030 const RecordType *NextT = ToVisit.back();
1031 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001033 // If we have already seen this type, skip it.
1034 if (!Visited.insert(NextT))
1035 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001037 // If this is a base class, try to perform template argument
1038 // deduction from it.
1039 if (NextT != RecordT) {
1040 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001041 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001042 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001044 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +00001045 // note that we had some success. Otherwise, ignore any deductions
1046 // from this base class.
1047 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001048 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +00001049 DeducedOrig = Deduced;
1050 }
1051 else
1052 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001053 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001055 // Visit base classes
1056 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1057 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
1058 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +00001059 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +00001060 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001061 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +00001062 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001063 }
1064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001066 if (Successful)
1067 return Sema::TDK_Success;
1068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001070 }
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Douglas Gregorde0cb8b2009-07-07 23:09:34 +00001072 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +00001073 }
1074
Douglas Gregor637a4092009-06-10 23:47:09 +00001075 // T type::*
1076 // T T::*
1077 // T (type::*)()
1078 // type (T::*)()
1079 // type (type::*)(T)
1080 // type (T::*)(T)
1081 // T (type::*)(T)
1082 // T (T::*)()
1083 // T (T::*)(T)
1084 case Type::MemberPointer: {
1085 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1086 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1087 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001088 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +00001089
Douglas Gregorf67875d2009-06-12 18:26:56 +00001090 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001091 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001092 MemPtrParam->getPointeeType(),
1093 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001094 Info, Deduced,
1095 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001096 return Result;
1097
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001098 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001099 QualType(MemPtrParam->getClass(), 0),
1100 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +00001101 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +00001102 }
1103
Anders Carlsson9a917e42009-06-12 22:56:54 +00001104 // (clang extension)
1105 //
Mike Stump1eb44332009-09-09 15:08:12 +00001106 // type(^)(T)
1107 // T(^)()
1108 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +00001109 case Type::BlockPointer: {
1110 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1111 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Anders Carlsson859ba502009-06-12 16:23:10 +00001113 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001114 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001116 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +00001117 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001118 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001119 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +00001120 }
1121
Douglas Gregor637a4092009-06-10 23:47:09 +00001122 case Type::TypeOfExpr:
1123 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +00001124 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +00001125 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +00001126 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +00001127
Douglas Gregord560d502009-06-04 00:21:18 +00001128 default:
1129 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001130 }
1131
1132 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001133 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001134}
1135
Douglas Gregorf67875d2009-06-12 18:26:56 +00001136static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001137DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001138 TemplateParameterList *TemplateParams,
1139 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001140 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +00001141 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001142 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001143 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +00001144 case TemplateArgument::Null:
1145 assert(false && "Null template argument in parameter list");
1146 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001147
1148 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +00001149 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001150 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +00001151 Arg.getAsType(), Info, Deduced, 0);
1152 Info.FirstArg = Param;
1153 Info.SecondArg = Arg;
1154 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001155
Douglas Gregor788cd062009-11-11 01:00:40 +00001156 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001157 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001158 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +00001159 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +00001160 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +00001161 Info.FirstArg = Param;
1162 Info.SecondArg = Arg;
1163 return Sema::TDK_NonDeducedMismatch;
Douglas Gregora7fc9012011-01-05 18:58:31 +00001164
1165 case TemplateArgument::TemplateExpansion:
1166 llvm_unreachable("caller should handle pack expansions");
1167 break;
Douglas Gregor788cd062009-11-11 01:00:40 +00001168
Douglas Gregor199d9912009-06-05 00:53:49 +00001169 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +00001170 if (Arg.getKind() == TemplateArgument::Declaration &&
1171 Param.getAsDecl()->getCanonicalDecl() ==
1172 Arg.getAsDecl()->getCanonicalDecl())
1173 return Sema::TDK_Success;
1174
Douglas Gregorf67875d2009-06-12 18:26:56 +00001175 Info.FirstArg = Param;
1176 Info.SecondArg = Arg;
1177 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Douglas Gregor199d9912009-06-05 00:53:49 +00001179 case TemplateArgument::Integral:
1180 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001181 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +00001182 return Sema::TDK_Success;
1183
1184 Info.FirstArg = Param;
1185 Info.SecondArg = Arg;
1186 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001187 }
Douglas Gregorf67875d2009-06-12 18:26:56 +00001188
1189 if (Arg.getKind() == TemplateArgument::Expression) {
1190 Info.FirstArg = Param;
1191 Info.SecondArg = Arg;
1192 return Sema::TDK_NonDeducedMismatch;
1193 }
Douglas Gregor199d9912009-06-05 00:53:49 +00001194
Douglas Gregorf67875d2009-06-12 18:26:56 +00001195 Info.FirstArg = Param;
1196 Info.SecondArg = Arg;
1197 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Douglas Gregor199d9912009-06-05 00:53:49 +00001199 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +00001200 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +00001201 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1202 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001203 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +00001204 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +00001205 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001206 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001207 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +00001208 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001209 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001210 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +00001211 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001212 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +00001213 Info, Deduced);
1214
Douglas Gregorf67875d2009-06-12 18:26:56 +00001215 Info.FirstArg = Param;
1216 Info.SecondArg = Arg;
1217 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +00001218 }
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Douglas Gregor199d9912009-06-05 00:53:49 +00001220 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +00001221 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001222 }
Anders Carlssond01b1da2009-06-15 17:04:53 +00001223 case TemplateArgument::Pack:
Douglas Gregor20a55e22010-12-22 18:17:10 +00001224 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregor199d9912009-06-05 00:53:49 +00001225 }
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Douglas Gregorf67875d2009-06-12 18:26:56 +00001227 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001228}
1229
Douglas Gregor20a55e22010-12-22 18:17:10 +00001230/// \brief Determine whether there is a template argument to be used for
1231/// deduction.
1232///
1233/// This routine "expands" argument packs in-place, overriding its input
1234/// parameters so that \c Args[ArgIdx] will be the available template argument.
1235///
1236/// \returns true if there is another template argument (which will be at
1237/// \c Args[ArgIdx]), false otherwise.
1238static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1239 unsigned &ArgIdx,
1240 unsigned &NumArgs) {
1241 if (ArgIdx == NumArgs)
1242 return false;
1243
1244 const TemplateArgument &Arg = Args[ArgIdx];
1245 if (Arg.getKind() != TemplateArgument::Pack)
1246 return true;
1247
1248 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1249 Args = Arg.pack_begin();
1250 NumArgs = Arg.pack_size();
1251 ArgIdx = 0;
1252 return ArgIdx < NumArgs;
1253}
1254
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001255/// \brief Determine whether the given set of template arguments has a pack
1256/// expansion that is not the last template argument.
1257static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1258 unsigned NumArgs) {
1259 unsigned ArgIdx = 0;
1260 while (ArgIdx < NumArgs) {
1261 const TemplateArgument &Arg = Args[ArgIdx];
1262
1263 // Unwrap argument packs.
1264 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1265 Args = Arg.pack_begin();
1266 NumArgs = Arg.pack_size();
1267 ArgIdx = 0;
1268 continue;
1269 }
1270
1271 ++ArgIdx;
1272 if (ArgIdx == NumArgs)
1273 return false;
1274
1275 if (Arg.isPackExpansion())
1276 return true;
1277 }
1278
1279 return false;
1280}
1281
Douglas Gregor20a55e22010-12-22 18:17:10 +00001282static Sema::TemplateDeductionResult
1283DeduceTemplateArguments(Sema &S,
1284 TemplateParameterList *TemplateParams,
1285 const TemplateArgument *Params, unsigned NumParams,
1286 const TemplateArgument *Args, unsigned NumArgs,
1287 TemplateDeductionInfo &Info,
Douglas Gregor0972c862010-12-22 18:55:49 +00001288 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1289 bool NumberOfArgumentsMustMatch) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001290 // C++0x [temp.deduct.type]p9:
1291 // If the template argument list of P contains a pack expansion that is not
1292 // the last template argument, the entire template argument list is a
1293 // non-deduced context.
Douglas Gregor7b976ec2010-12-23 01:24:45 +00001294 if (hasPackExpansionBeforeEnd(Params, NumParams))
1295 return Sema::TDK_Success;
1296
Douglas Gregore02e2622010-12-22 21:19:48 +00001297 // C++0x [temp.deduct.type]p9:
1298 // If P has a form that contains <T> or <i>, then each argument Pi of the
1299 // respective template argument list P is compared with the corresponding
1300 // argument Ai of the corresponding template argument list of A.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001301 unsigned ArgIdx = 0, ParamIdx = 0;
1302 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1303 ++ParamIdx) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001304 // FIXME: Variadic templates.
1305 // What do we do if the argument is a pack expansion?
1306
Douglas Gregor20a55e22010-12-22 18:17:10 +00001307 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregore02e2622010-12-22 21:19:48 +00001308 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001309
1310 // Check whether we have enough arguments.
1311 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor0972c862010-12-22 18:55:49 +00001312 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1313 : Sema::TDK_Success;
Douglas Gregor20a55e22010-12-22 18:17:10 +00001314
Douglas Gregore02e2622010-12-22 21:19:48 +00001315 // Perform deduction for this Pi/Ai pair.
Douglas Gregor20a55e22010-12-22 18:17:10 +00001316 if (Sema::TemplateDeductionResult Result
1317 = DeduceTemplateArguments(S, TemplateParams,
1318 Params[ParamIdx], Args[ArgIdx],
1319 Info, Deduced))
1320 return Result;
1321
1322 // Move to the next argument.
1323 ++ArgIdx;
1324 continue;
1325 }
1326
Douglas Gregore02e2622010-12-22 21:19:48 +00001327 // The parameter is a pack expansion.
1328
1329 // C++0x [temp.deduct.type]p9:
1330 // If Pi is a pack expansion, then the pattern of Pi is compared with
1331 // each remaining argument in the template argument list of A. Each
1332 // comparison deduces template arguments for subsequent positions in the
1333 // template parameter packs expanded by Pi.
1334 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1335
1336 // Compute the set of template parameter indices that correspond to
1337 // parameter packs expanded by the pack expansion.
1338 llvm::SmallVector<unsigned, 2> PackIndices;
1339 {
1340 llvm::BitVector SawIndices(TemplateParams->size());
1341 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1342 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1343 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1344 unsigned Depth, Index;
1345 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1346 if (Depth == 0 && !SawIndices[Index]) {
1347 SawIndices[Index] = true;
1348 PackIndices.push_back(Index);
1349 }
1350 }
1351 }
1352 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1353
1354 // FIXME: If there are no remaining arguments, we can bail out early
1355 // and set any deduced parameter packs to an empty argument pack.
1356 // The latter part of this is a (minor) correctness issue.
1357
1358 // Save the deduced template arguments for each parameter pack expanded
1359 // by this pack expansion, then clear out the deduction.
1360 llvm::SmallVector<DeducedTemplateArgument, 2>
1361 SavedPacks(PackIndices.size());
1362 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1363 SavedPacks[I] = Deduced[PackIndices[I]];
1364 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1365 }
1366
1367 // Keep track of the deduced template arguments for each parameter pack
1368 // expanded by this pack expansion (the outer index) and for each
1369 // template argument (the inner SmallVectors).
1370 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1371 NewlyDeducedPacks(PackIndices.size());
1372 bool HasAnyArguments = false;
1373 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1374 HasAnyArguments = true;
1375
1376 // Deduce template arguments from the pattern.
1377 if (Sema::TemplateDeductionResult Result
1378 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1379 Info, Deduced))
1380 return Result;
1381
1382 // Capture the deduced template arguments for each parameter pack expanded
1383 // by this pack expansion, add them to the list of arguments we've deduced
1384 // for that pack, then clear out the deduced argument.
1385 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1386 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1387 if (!DeducedArg.isNull()) {
1388 NewlyDeducedPacks[I].push_back(DeducedArg);
1389 DeducedArg = DeducedTemplateArgument();
1390 }
1391 }
1392
1393 ++ArgIdx;
1394 }
1395
1396 // Build argument packs for each of the parameter packs expanded by this
1397 // pack expansion.
1398 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1399 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1400 // We were not able to deduce anything for this parameter pack,
1401 // so just restore the saved argument pack.
1402 Deduced[PackIndices[I]] = SavedPacks[I];
1403 continue;
1404 }
1405
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001406 DeducedTemplateArgument NewPack;
Douglas Gregore02e2622010-12-22 21:19:48 +00001407
1408 if (NewlyDeducedPacks[I].empty()) {
1409 // If we deduced an empty argument pack, create it now.
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001410 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1411 } else {
1412 TemplateArgument *ArgumentPack
1413 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1414 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1415 ArgumentPack);
1416 NewPack
1417 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregore02e2622010-12-22 21:19:48 +00001418 NewlyDeducedPacks[I].size()),
Douglas Gregor0d80abc2010-12-22 23:09:49 +00001419 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1420 }
1421
1422 DeducedTemplateArgument Result
1423 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1424 if (Result.isNull()) {
1425 Info.Param
1426 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1427 Info.FirstArg = SavedPacks[I];
1428 Info.SecondArg = NewPack;
1429 return Sema::TDK_Inconsistent;
1430 }
1431
1432 Deduced[PackIndices[I]] = Result;
Douglas Gregore02e2622010-12-22 21:19:48 +00001433 }
Douglas Gregor20a55e22010-12-22 18:17:10 +00001434 }
1435
1436 // If there is an argument remaining, then we had too many arguments.
Douglas Gregor0972c862010-12-22 18:55:49 +00001437 if (NumberOfArgumentsMustMatch &&
1438 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor20a55e22010-12-22 18:17:10 +00001439 return Sema::TDK_TooManyArguments;
1440
1441 return Sema::TDK_Success;
1442}
1443
Mike Stump1eb44332009-09-09 15:08:12 +00001444static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001445DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001446 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001447 const TemplateArgumentList &ParamList,
1448 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +00001449 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00001450 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor20a55e22010-12-22 18:17:10 +00001451 return DeduceTemplateArguments(S, TemplateParams,
1452 ParamList.data(), ParamList.size(),
1453 ArgList.data(), ArgList.size(),
1454 Info, Deduced);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001455}
1456
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001457/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +00001458static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001459 const TemplateArgument &X,
1460 const TemplateArgument &Y) {
1461 if (X.getKind() != Y.getKind())
1462 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001464 switch (X.getKind()) {
1465 case TemplateArgument::Null:
1466 assert(false && "Comparing NULL template argument");
1467 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001469 case TemplateArgument::Type:
1470 return Context.getCanonicalType(X.getAsType()) ==
1471 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001473 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001474 return X.getAsDecl()->getCanonicalDecl() ==
1475 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Douglas Gregor788cd062009-11-11 01:00:40 +00001477 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001478 case TemplateArgument::TemplateExpansion:
1479 return Context.getCanonicalTemplateName(
1480 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1481 Context.getCanonicalTemplateName(
1482 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
Douglas Gregor788cd062009-11-11 01:00:40 +00001483
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001484 case TemplateArgument::Integral:
1485 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Douglas Gregor788cd062009-11-11 01:00:40 +00001487 case TemplateArgument::Expression: {
1488 llvm::FoldingSetNodeID XID, YID;
1489 X.getAsExpr()->Profile(XID, Context, true);
1490 Y.getAsExpr()->Profile(YID, Context, true);
1491 return XID == YID;
1492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001494 case TemplateArgument::Pack:
1495 if (X.pack_size() != Y.pack_size())
1496 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001497
1498 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1499 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001500 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +00001501 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001502 if (!isSameTemplateArg(Context, *XP, *YP))
1503 return false;
1504
1505 return true;
1506 }
1507
1508 return false;
1509}
1510
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001511/// \brief Allocate a TemplateArgumentLoc where all locations have
1512/// been initialized to the given location.
1513///
1514/// \param S The semantic analysis object.
1515///
1516/// \param The template argument we are producing template argument
1517/// location information for.
1518///
1519/// \param NTTPType For a declaration template argument, the type of
1520/// the non-type template parameter that corresponds to this template
1521/// argument.
1522///
1523/// \param Loc The source location to use for the resulting template
1524/// argument.
1525static TemplateArgumentLoc
1526getTrivialTemplateArgumentLoc(Sema &S,
1527 const TemplateArgument &Arg,
1528 QualType NTTPType,
1529 SourceLocation Loc) {
1530 switch (Arg.getKind()) {
1531 case TemplateArgument::Null:
1532 llvm_unreachable("Can't get a NULL template argument here");
1533 break;
1534
1535 case TemplateArgument::Type:
1536 return TemplateArgumentLoc(Arg,
1537 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1538
1539 case TemplateArgument::Declaration: {
1540 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001541 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001542 .takeAs<Expr>();
1543 return TemplateArgumentLoc(TemplateArgument(E), E);
1544 }
1545
1546 case TemplateArgument::Integral: {
1547 Expr *E
Douglas Gregorba68eca2011-01-05 17:40:24 +00001548 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001549 return TemplateArgumentLoc(TemplateArgument(E), E);
1550 }
1551
1552 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00001553 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1554
1555 case TemplateArgument::TemplateExpansion:
1556 return TemplateArgumentLoc(Arg, SourceRange(), Loc, Loc);
1557
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001558 case TemplateArgument::Expression:
1559 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1560
1561 case TemplateArgument::Pack:
1562 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
1563 }
1564
1565 return TemplateArgumentLoc();
1566}
1567
1568
1569/// \brief Convert the given deduced template argument and add it to the set of
1570/// fully-converted template arguments.
1571static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
1572 DeducedTemplateArgument Arg,
1573 NamedDecl *Template,
1574 QualType NTTPType,
1575 TemplateDeductionInfo &Info,
1576 bool InFunctionTemplate,
1577 llvm::SmallVectorImpl<TemplateArgument> &Output) {
1578 if (Arg.getKind() == TemplateArgument::Pack) {
1579 // This is a template argument pack, so check each of its arguments against
1580 // the template parameter.
1581 llvm::SmallVector<TemplateArgument, 2> PackedArgsBuilder;
1582 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregor135ffa72011-01-05 21:00:53 +00001583 PAEnd = Arg.pack_end();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001584 PA != PAEnd; ++PA) {
Douglas Gregord53e16a2011-01-05 20:52:18 +00001585 // When converting the deduced template argument, append it to the
1586 // general output list. We need to do this so that the template argument
1587 // checking logic has all of the prior template arguments available.
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001588 DeducedTemplateArgument InnerArg(*PA);
1589 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
1590 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
1591 NTTPType, Info,
Douglas Gregord53e16a2011-01-05 20:52:18 +00001592 InFunctionTemplate, Output))
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001593 return true;
Douglas Gregord53e16a2011-01-05 20:52:18 +00001594
1595 // Move the converted template argument into our argument pack.
1596 PackedArgsBuilder.push_back(Output.back());
1597 Output.pop_back();
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001598 }
1599
1600 // Create the resulting argument pack.
1601 TemplateArgument *PackedArgs = 0;
1602 if (!PackedArgsBuilder.empty()) {
1603 PackedArgs = new (S.Context) TemplateArgument[PackedArgsBuilder.size()];
1604 std::copy(PackedArgsBuilder.begin(), PackedArgsBuilder.end(), PackedArgs);
1605 }
1606 Output.push_back(TemplateArgument(PackedArgs, PackedArgsBuilder.size()));
1607 return false;
1608 }
1609
1610 // Convert the deduced template argument into a template
1611 // argument that we can check, almost as if the user had written
1612 // the template argument explicitly.
1613 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
1614 Info.getLocation());
1615
1616 // Check the template argument, converting it as necessary.
1617 return S.CheckTemplateArgument(Param, ArgLoc,
1618 Template,
1619 Template->getLocation(),
1620 Template->getSourceRange().getEnd(),
1621 Output,
1622 InFunctionTemplate
1623 ? (Arg.wasDeducedFromArrayBound()
1624 ? Sema::CTAK_DeducedFromArrayBound
1625 : Sema::CTAK_Deduced)
1626 : Sema::CTAK_Specified);
1627}
1628
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001629/// Complete template argument deduction for a class template partial
1630/// specialization.
1631static Sema::TemplateDeductionResult
1632FinishTemplateArgumentDeduction(Sema &S,
1633 ClassTemplatePartialSpecializationDecl *Partial,
1634 const TemplateArgumentList &TemplateArgs,
1635 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001636 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001637 // Trap errors.
1638 Sema::SFINAETrap Trap(S);
1639
1640 Sema::ContextRAII SavedContext(S, Partial);
1641
1642 // C++ [temp.deduct.type]p2:
1643 // [...] or if any template argument remains neither deduced nor
1644 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001645 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor033a3ca2011-01-04 22:23:38 +00001646 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
1647 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001648 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001649 if (Deduced[I].isNull()) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001650 Info.Param = makeTemplateParameter(Param);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001651 return Sema::TDK_Incomplete;
1652 }
1653
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001654 // We have deduced this argument, so it still needs to be
1655 // checked and converted.
1656
1657 // First, for a non-type template parameter type that is
1658 // initialized by a declaration, we need the type of the
1659 // corresponding non-type template parameter.
1660 QualType NTTPType;
1661 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregord53e16a2011-01-05 20:52:18 +00001662 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001663 NTTPType = NTTP->getType();
Douglas Gregord53e16a2011-01-05 20:52:18 +00001664 if (NTTPType->isDependentType()) {
1665 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1666 Builder.data(), Builder.size());
1667 NTTPType = S.SubstType(NTTPType,
1668 MultiLevelTemplateArgumentList(TemplateArgs),
1669 NTTP->getLocation(),
1670 NTTP->getDeclName());
1671 if (NTTPType.isNull()) {
1672 Info.Param = makeTemplateParameter(Param);
1673 // FIXME: These template arguments are temporary. Free them!
1674 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
1675 Builder.data(),
1676 Builder.size()));
1677 return Sema::TDK_SubstitutionFailure;
1678 }
1679 }
1680 }
1681
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001682 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
1683 Partial, NTTPType, Info, false,
1684 Builder)) {
1685 Info.Param = makeTemplateParameter(Param);
1686 // FIXME: These template arguments are temporary. Free them!
1687 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1688 Builder.size()));
1689 return Sema::TDK_SubstitutionFailure;
1690 }
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001691 }
1692
1693 // Form the template argument list from the deduced template arguments.
1694 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001695 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1696 Builder.size());
1697
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001698 Info.reset(DeducedArgumentList);
1699
1700 // Substitute the deduced template arguments into the template
1701 // arguments of the class template partial specialization, and
1702 // verify that the instantiated template arguments are both valid
1703 // and are equivalent to the template arguments originally provided
1704 // to the class template.
John McCall2a7fb272010-08-25 05:32:35 +00001705 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001706 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1707 const TemplateArgumentLoc *PartialTemplateArgs
1708 = Partial->getTemplateArgsAsWritten();
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001709
1710 // Note that we don't provide the langle and rangle locations.
1711 TemplateArgumentListInfo InstArgs;
1712
Douglas Gregore02e2622010-12-22 21:19:48 +00001713 if (S.Subst(PartialTemplateArgs,
1714 Partial->getNumTemplateArgsAsWritten(),
1715 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1716 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1717 if (ParamIdx >= Partial->getTemplateParameters()->size())
1718 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1719
1720 Decl *Param
1721 = const_cast<NamedDecl *>(
1722 Partial->getTemplateParameters()->getParam(ParamIdx));
1723 Info.Param = makeTemplateParameter(Param);
1724 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1725 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001726 }
1727
Douglas Gregor910f8002010-11-07 23:05:16 +00001728 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001729 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001730 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001731 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001732
Douglas Gregor54c53cc2011-01-04 23:35:54 +00001733 TemplateParameterList *TemplateParams
1734 = ClassTemplate->getTemplateParameters();
1735 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001736 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001737 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00001738 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001739 Info.FirstArg = TemplateArgs[I];
1740 Info.SecondArg = InstArg;
1741 return Sema::TDK_NonDeducedMismatch;
1742 }
1743 }
1744
1745 if (Trap.hasErrorOccurred())
1746 return Sema::TDK_SubstitutionFailure;
1747
1748 return Sema::TDK_Success;
1749}
1750
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001751/// \brief Perform template argument deduction to determine whether
1752/// the given template arguments match the given class template
1753/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001754Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001755Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001756 const TemplateArgumentList &TemplateArgs,
1757 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001758 // C++ [temp.class.spec.match]p2:
1759 // A partial specialization matches a given actual template
1760 // argument list if the template arguments of the partial
1761 // specialization can be deduced from the actual template argument
1762 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001763 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001764 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001765 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001766 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001767 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001768 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001769 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001770 TemplateArgs, Info, Deduced))
1771 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001772
Douglas Gregor637a4092009-06-10 23:47:09 +00001773 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001774 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001775 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001776 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001777
Douglas Gregorbb260412009-06-14 08:02:22 +00001778 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001779 return Sema::TDK_SubstitutionFailure;
1780
1781 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1782 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001783}
Douglas Gregor031a5882009-06-13 00:26:55 +00001784
Douglas Gregor41128772009-06-26 23:27:24 +00001785/// \brief Determine whether the given type T is a simple-template-id type.
1786static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001787 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001788 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001789 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Douglas Gregor41128772009-06-26 23:27:24 +00001791 return false;
1792}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001793
1794/// \brief Substitute the explicitly-provided template arguments into the
1795/// given function template according to C++ [temp.arg.explicit].
1796///
1797/// \param FunctionTemplate the function template into which the explicit
1798/// template arguments will be substituted.
1799///
Mike Stump1eb44332009-09-09 15:08:12 +00001800/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001801/// arguments.
1802///
Mike Stump1eb44332009-09-09 15:08:12 +00001803/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001804/// with the converted and checked explicit template arguments.
1805///
Mike Stump1eb44332009-09-09 15:08:12 +00001806/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001807/// parameters.
1808///
1809/// \param FunctionType if non-NULL, the result type of the function template
1810/// will also be instantiated and the pointed-to value will be updated with
1811/// the instantiated function type.
1812///
1813/// \param Info if substitution fails for any reason, this object will be
1814/// populated with more information about the failure.
1815///
1816/// \returns TDK_Success if substitution was successful, or some failure
1817/// condition.
1818Sema::TemplateDeductionResult
1819Sema::SubstituteExplicitTemplateArguments(
1820 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001821 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001822 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001823 llvm::SmallVectorImpl<QualType> &ParamTypes,
1824 QualType *FunctionType,
1825 TemplateDeductionInfo &Info) {
1826 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1827 TemplateParameterList *TemplateParams
1828 = FunctionTemplate->getTemplateParameters();
1829
John McCalld5532b62009-11-23 01:53:49 +00001830 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001831 // No arguments to substitute; just copy over the parameter types and
1832 // fill in the function type.
1833 for (FunctionDecl::param_iterator P = Function->param_begin(),
1834 PEnd = Function->param_end();
1835 P != PEnd;
1836 ++P)
1837 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Douglas Gregor83314aa2009-07-08 20:55:45 +00001839 if (FunctionType)
1840 *FunctionType = Function->getType();
1841 return TDK_Success;
1842 }
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Douglas Gregor83314aa2009-07-08 20:55:45 +00001844 // Substitution of the explicit template arguments into a function template
1845 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001846 SFINAETrap Trap(*this);
1847
Douglas Gregor83314aa2009-07-08 20:55:45 +00001848 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001849 // Template arguments that are present shall be specified in the
1850 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001851 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001852 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001853 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001854
1855 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001856 // explicitly-specified template arguments against this function template,
1857 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001858 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001859 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001860 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1861 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001862 if (Inst)
1863 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregor83314aa2009-07-08 20:55:45 +00001865 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001866 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001867 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001868 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001869 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001870 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001871 if (Index >= TemplateParams->size())
1872 Index = TemplateParams->size() - 1;
1873 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001874 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001875 }
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Douglas Gregor83314aa2009-07-08 20:55:45 +00001877 // Form the template argument list from the explicitly-specified
1878 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001879 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001880 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001881 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001882
John McCalldf41f182010-10-12 19:40:14 +00001883 // Template argument deduction and the final substitution should be
1884 // done in the context of the templated declaration. Explicit
1885 // argument substitution, on the other hand, needs to happen in the
1886 // calling context.
1887 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1888
Douglas Gregor83314aa2009-07-08 20:55:45 +00001889 // Instantiate the types of each of the function parameters given the
1890 // explicitly-specified template arguments.
1891 for (FunctionDecl::param_iterator P = Function->param_begin(),
1892 PEnd = Function->param_end();
1893 P != PEnd;
1894 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001895 QualType ParamType
1896 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001897 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1898 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001899 if (ParamType.isNull() || Trap.hasErrorOccurred())
1900 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Douglas Gregor83314aa2009-07-08 20:55:45 +00001902 ParamTypes.push_back(ParamType);
1903 }
1904
1905 // If the caller wants a full function type back, instantiate the return
1906 // type and form that function type.
1907 if (FunctionType) {
1908 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001909 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001910 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001911 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001912
1913 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001914 = SubstType(Proto->getResultType(),
1915 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1916 Function->getTypeSpecStartLoc(),
1917 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001918 if (ResultType.isNull() || Trap.hasErrorOccurred())
1919 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001920
1921 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001922 ParamTypes.data(), ParamTypes.size(),
1923 Proto->isVariadic(),
1924 Proto->getTypeQuals(),
1925 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001926 Function->getDeclName(),
1927 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001928 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1929 return TDK_SubstitutionFailure;
1930 }
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Douglas Gregor83314aa2009-07-08 20:55:45 +00001932 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001933 // Trailing template arguments that can be deduced (14.8.2) may be
1934 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001935 // template arguments can be deduced, they may all be omitted; in this
1936 // case, the empty template argument list <> itself may also be omitted.
1937 //
1938 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001939 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001940 Deduced.reserve(TemplateParams->size());
1941 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001942 Deduced.push_back(ExplicitArgumentList->get(I));
1943
Douglas Gregor83314aa2009-07-08 20:55:45 +00001944 return TDK_Success;
1945}
1946
Mike Stump1eb44332009-09-09 15:08:12 +00001947/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001948/// checking the deduced template arguments for completeness and forming
1949/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001950Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001951Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001952 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1953 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001954 FunctionDecl *&Specialization,
1955 TemplateDeductionInfo &Info) {
1956 TemplateParameterList *TemplateParams
1957 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Douglas Gregor83314aa2009-07-08 20:55:45 +00001959 // Template argument deduction for function templates in a SFINAE context.
1960 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001961 SFINAETrap Trap(*this);
1962
Douglas Gregor83314aa2009-07-08 20:55:45 +00001963 // Enter a new template instantiation context while we instantiate the
1964 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001965 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001966 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001967 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1968 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001969 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001970 return TDK_InstantiationDepth;
1971
John McCall96db3102010-04-29 01:18:58 +00001972 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001973
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001974 // C++ [temp.deduct.type]p2:
1975 // [...] or if any template argument remains neither deduced nor
1976 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001977 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001978 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
1979 NamedDecl *Param = TemplateParams->getParam(I);
Douglas Gregorea6c96f2010-12-23 01:52:01 +00001980
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001981 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001982 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001983 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001984 // argument, because it was explicitly-specified. Just record the
1985 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001986 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001987 continue;
1988 }
1989
1990 // We have deduced this argument, so it still needs to be
1991 // checked and converted.
1992
1993 // First, for a non-type template parameter type that is
1994 // initialized by a declaration, we need the type of the
1995 // corresponding non-type template parameter.
1996 QualType NTTPType;
1997 if (NonTypeTemplateParmDecl *NTTP
1998 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00001999 NTTPType = NTTP->getType();
2000 if (NTTPType->isDependentType()) {
2001 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2002 Builder.data(), Builder.size());
2003 NTTPType = SubstType(NTTPType,
2004 MultiLevelTemplateArgumentList(TemplateArgs),
2005 NTTP->getLocation(),
2006 NTTP->getDeclName());
2007 if (NTTPType.isNull()) {
2008 Info.Param = makeTemplateParameter(Param);
2009 // FIXME: These template arguments are temporary. Free them!
2010 Info.reset(TemplateArgumentList::CreateCopy(Context,
2011 Builder.data(),
2012 Builder.size()));
2013 return TDK_SubstitutionFailure;
Douglas Gregor02024a92010-03-28 02:42:43 +00002014 }
2015 }
2016 }
2017
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002018 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2019 FunctionTemplate, NTTPType, Info,
Douglas Gregor54c53cc2011-01-04 23:35:54 +00002020 true, Builder)) {
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002021 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00002022 // FIXME: These template arguments are temporary. Free them!
2023 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregorb9a7d6f2011-01-04 22:13:36 +00002024 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00002025 return TDK_SubstitutionFailure;
2026 }
2027
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002028 continue;
2029 }
Douglas Gregorea6c96f2010-12-23 01:52:01 +00002030
2031 // C++0x [temp.arg.explicit]p3:
2032 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2033 // be deduced to an empty sequence of template arguments.
2034 // FIXME: Where did the word "trailing" come from?
2035 if (Param->isTemplateParameterPack()) {
2036 Builder.push_back(TemplateArgument(0, 0));
2037 continue;
2038 }
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002039
2040 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002041 TemplateArgumentLoc DefArg
2042 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2043 FunctionTemplate->getLocation(),
2044 FunctionTemplate->getSourceRange().getEnd(),
2045 Param,
2046 Builder);
2047
2048 // If there was no default argument, deduction is incomplete.
2049 if (DefArg.getArgument().isNull()) {
2050 Info.Param = makeTemplateParameter(
2051 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2052 return TDK_Incomplete;
2053 }
2054
2055 // Check whether we can actually use the default argument.
2056 if (CheckTemplateArgument(Param, DefArg,
2057 FunctionTemplate,
2058 FunctionTemplate->getLocation(),
2059 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00002060 Builder,
2061 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002062 Info.Param = makeTemplateParameter(
2063 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00002064 // FIXME: These template arguments are temporary. Free them!
2065 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2066 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002067 return TDK_SubstitutionFailure;
2068 }
2069
2070 // If we get here, we successfully used the default template argument.
2071 }
2072
2073 // Form the template argument list from the deduced template arguments.
2074 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00002075 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002076 Info.reset(DeducedArgumentList);
2077
Mike Stump1eb44332009-09-09 15:08:12 +00002078 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002079 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00002080 DeclContext *Owner = FunctionTemplate->getDeclContext();
2081 if (FunctionTemplate->getFriendObjectKind())
2082 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002083 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00002084 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00002085 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00002086 if (!Specialization)
2087 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Douglas Gregorf8825742009-09-15 18:26:13 +00002089 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2090 FunctionTemplate->getCanonicalDecl());
2091
Mike Stump1eb44332009-09-09 15:08:12 +00002092 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00002093 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00002094 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2095 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00002096 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Douglas Gregor83314aa2009-07-08 20:55:45 +00002098 // There may have been an error that did not prevent us from constructing a
2099 // declaration. Mark the declaration invalid and return with a substitution
2100 // failure.
2101 if (Trap.hasErrorOccurred()) {
2102 Specialization->setInvalidDecl(true);
2103 return TDK_SubstitutionFailure;
2104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Douglas Gregor9b623632010-10-12 23:32:35 +00002106 // If we suppressed any diagnostics while performing template argument
2107 // deduction, and if we haven't already instantiated this declaration,
2108 // keep track of these diagnostics. They'll be emitted if this specialization
2109 // is actually used.
2110 if (Info.diag_begin() != Info.diag_end()) {
2111 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
2112 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2113 if (Pos == SuppressedDiagnostics.end())
2114 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2115 .append(Info.diag_begin(), Info.diag_end());
2116 }
2117
Mike Stump1eb44332009-09-09 15:08:12 +00002118 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002119}
2120
John McCall9c72c602010-08-27 09:08:28 +00002121/// Gets the type of a function for template-argument-deducton
2122/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00002123static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00002124 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00002125 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00002126 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00002127 if (Method->isInstance()) {
2128 // An instance method that's referenced in a form that doesn't
2129 // look like a member pointer is just invalid.
2130 if (!R.HasFormOfMemberPointer) return QualType();
2131
John McCalleff92132010-02-02 02:21:27 +00002132 return Context.getMemberPointerType(Fn->getType(),
2133 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00002134 }
2135
2136 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00002137 return Context.getPointerType(Fn->getType());
2138}
2139
2140/// Apply the deduction rules for overload sets.
2141///
2142/// \return the null type if this argument should be treated as an
2143/// undeduced context
2144static QualType
2145ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002146 Expr *Arg, QualType ParamType,
2147 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00002148
2149 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00002150
John McCall9c72c602010-08-27 09:08:28 +00002151 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00002152
Douglas Gregor75f21af2010-08-30 21:04:23 +00002153 // C++0x [temp.deduct.call]p4
2154 unsigned TDF = 0;
2155 if (ParamWasReference)
2156 TDF |= TDF_ParamWithReferenceType;
2157 if (R.IsAddressOfOperand)
2158 TDF |= TDF_IgnoreQualifiers;
2159
John McCalleff92132010-02-02 02:21:27 +00002160 // If there were explicit template arguments, we can only find
2161 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
2162 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00002163 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00002164 // But we can still look for an explicit specialization.
2165 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00002166 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00002167 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00002168 return QualType();
2169 }
2170
2171 // C++0x [temp.deduct.call]p6:
2172 // When P is a function type, pointer to function type, or pointer
2173 // to member function type:
2174
2175 if (!ParamType->isFunctionType() &&
2176 !ParamType->isFunctionPointerType() &&
2177 !ParamType->isMemberFunctionPointerType())
2178 return QualType();
2179
2180 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00002181 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2182 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00002183 NamedDecl *D = (*I)->getUnderlyingDecl();
2184
2185 // - If the argument is an overload set containing one or more
2186 // function templates, the parameter is treated as a
2187 // non-deduced context.
2188 if (isa<FunctionTemplateDecl>(D))
2189 return QualType();
2190
2191 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00002192 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
2193 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00002194
Douglas Gregor75f21af2010-08-30 21:04:23 +00002195 // Function-to-pointer conversion.
2196 if (!ParamWasReference && ParamType->isPointerType() &&
2197 ArgType->isFunctionType())
2198 ArgType = S.Context.getPointerType(ArgType);
2199
John McCalleff92132010-02-02 02:21:27 +00002200 // - If the argument is an overload set (not containing function
2201 // templates), trial argument deduction is attempted using each
2202 // of the members of the set. If deduction succeeds for only one
2203 // of the overload set members, that member is used as the
2204 // argument value for the deduction. If deduction succeeds for
2205 // more than one member of the overload set the parameter is
2206 // treated as a non-deduced context.
2207
2208 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
2209 // Type deduction is done independently for each P/A pair, and
2210 // the deduced template argument values are then combined.
2211 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00002212 llvm::SmallVector<DeducedTemplateArgument, 8>
2213 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00002214 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00002215 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002216 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00002217 ParamType, ArgType,
2218 Info, Deduced, TDF);
2219 if (Result) continue;
2220 if (!Match.isNull()) return QualType();
2221 Match = ArgType;
2222 }
2223
2224 return Match;
2225}
2226
Douglas Gregore53060f2009-06-25 22:08:12 +00002227/// \brief Perform template argument deduction from a function call
2228/// (C++ [temp.deduct.call]).
2229///
2230/// \param FunctionTemplate the function template for which we are performing
2231/// template argument deduction.
2232///
Douglas Gregor48026d22010-01-11 18:40:55 +00002233/// \param ExplicitTemplateArguments the explicit template arguments provided
2234/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002235///
Douglas Gregore53060f2009-06-25 22:08:12 +00002236/// \param Args the function call arguments
2237///
2238/// \param NumArgs the number of arguments in Args
2239///
Douglas Gregor48026d22010-01-11 18:40:55 +00002240/// \param Name the name of the function being called. This is only significant
2241/// when the function template is a conversion function template, in which
2242/// case this routine will also perform template argument deduction based on
2243/// the function to which
2244///
Douglas Gregore53060f2009-06-25 22:08:12 +00002245/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002246/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00002247/// template argument deduction.
2248///
2249/// \param Info the argument will be updated to provide additional information
2250/// about template argument deduction.
2251///
2252/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00002253Sema::TemplateDeductionResult
2254Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00002255 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00002256 Expr **Args, unsigned NumArgs,
2257 FunctionDecl *&Specialization,
2258 TemplateDeductionInfo &Info) {
2259 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002260
Douglas Gregore53060f2009-06-25 22:08:12 +00002261 // C++ [temp.deduct.call]p1:
2262 // Template argument deduction is done by comparing each function template
2263 // parameter type (call it P) with the type of the corresponding argument
2264 // of the call (call it A) as described below.
2265 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002266 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00002267 return TDK_TooFewArguments;
2268 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002269 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00002270 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregore53060f2009-06-25 22:08:12 +00002271 if (!Proto->isVariadic())
2272 return TDK_TooManyArguments;
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Douglas Gregore53060f2009-06-25 22:08:12 +00002274 CheckArgs = Function->getNumParams();
2275 }
Mike Stump1eb44332009-09-09 15:08:12 +00002276
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002277 // The types of the parameters from which we will perform template argument
2278 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002279 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00002280 TemplateParameterList *TemplateParams
2281 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002282 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002283 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00002284 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00002285 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00002286 TemplateDeductionResult Result =
2287 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002288 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002289 Deduced,
2290 ParamTypes,
2291 0,
2292 Info);
2293 if (Result)
2294 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002295
2296 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002297 } else {
2298 // Just fill in the parameter types from the function declaration.
2299 for (unsigned I = 0; I != CheckArgs; ++I)
2300 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2301 }
Mike Stump1eb44332009-09-09 15:08:12 +00002302
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002303 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00002304 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00002305 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002306 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00002307 QualType ArgType = Args[I]->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Douglas Gregor75f21af2010-08-30 21:04:23 +00002309 // C++0x [temp.deduct.call]p3:
2310 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2311 // are ignored for type deduction.
2312 if (ParamType.getCVRQualifiers())
2313 ParamType = ParamType.getLocalUnqualifiedType();
2314 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2315 if (ParamRefType) {
2316 // [...] If P is a reference type, the type referred to by P is used
2317 // for type deduction.
2318 ParamType = ParamRefType->getPointeeType();
2319 }
2320
John McCalleff92132010-02-02 02:21:27 +00002321 // Overload sets usually make this parameter an undeduced
2322 // context, but there are sometimes special circumstances.
2323 if (ArgType == Context.OverloadTy) {
2324 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00002325 Args[I], ParamType,
2326 ParamRefType != 0);
John McCalleff92132010-02-02 02:21:27 +00002327 if (ArgType.isNull())
2328 continue;
2329 }
2330
Douglas Gregor75f21af2010-08-30 21:04:23 +00002331 if (ParamRefType) {
2332 // C++0x [temp.deduct.call]p3:
2333 // [...] If P is of the form T&&, where T is a template parameter, and
2334 // the argument is an lvalue, the type A& is used in place of A for
2335 // type deduction.
2336 if (ParamRefType->isRValueReferenceType() &&
2337 ParamRefType->getAs<TemplateTypeParmType>() &&
John McCall7eb0a9e2010-11-24 05:12:34 +00002338 Args[I]->isLValue())
Douglas Gregor75f21af2010-08-30 21:04:23 +00002339 ArgType = Context.getLValueReferenceType(ArgType);
2340 } else {
2341 // C++ [temp.deduct.call]p2:
2342 // If P is not a reference type:
Mike Stump1eb44332009-09-09 15:08:12 +00002343 // - If A is an array type, the pointer type produced by the
2344 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregore53060f2009-06-25 22:08:12 +00002345 // A for type deduction; otherwise,
2346 if (ArgType->isArrayType())
2347 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00002348 // - If A is a function type, the pointer type produced by the
2349 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregore53060f2009-06-25 22:08:12 +00002350 // of A for type deduction; otherwise,
2351 else if (ArgType->isFunctionType())
2352 ArgType = Context.getPointerType(ArgType);
2353 else {
2354 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2355 // type are ignored for type deduction.
2356 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor75f21af2010-08-30 21:04:23 +00002357 if (ArgType.getCVRQualifiers())
2358 ArgType = ArgType.getUnqualifiedType();
Douglas Gregore53060f2009-06-25 22:08:12 +00002359 }
2360 }
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Douglas Gregore53060f2009-06-25 22:08:12 +00002362 // C++0x [temp.deduct.call]p4:
2363 // In general, the deduction process attempts to find template argument
2364 // values that will make the deduced A identical to A (after the type A
2365 // is transformed as described above). [...]
Douglas Gregor12820292009-09-14 20:00:47 +00002366 unsigned TDF = TDF_SkipNonDependent;
Mike Stump1eb44332009-09-09 15:08:12 +00002367
Douglas Gregor508f1c82009-06-26 23:10:12 +00002368 // - If the original P is a reference type, the deduced A (i.e., the
2369 // type referred to by the reference) can be more cv-qualified than
2370 // the transformed A.
Douglas Gregor75f21af2010-08-30 21:04:23 +00002371 if (ParamRefType)
Douglas Gregor508f1c82009-06-26 23:10:12 +00002372 TDF |= TDF_ParamWithReferenceType;
Mike Stump1eb44332009-09-09 15:08:12 +00002373 // - The transformed A can be another pointer or pointer to member
2374 // type that can be converted to the deduced A via a qualification
Douglas Gregor508f1c82009-06-26 23:10:12 +00002375 // conversion (4.4).
John McCalldb0bc472010-08-05 05:30:45 +00002376 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2377 ArgType->isObjCObjectPointerType())
Douglas Gregor508f1c82009-06-26 23:10:12 +00002378 TDF |= TDF_IgnoreQualifiers;
Mike Stump1eb44332009-09-09 15:08:12 +00002379 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor41128772009-06-26 23:27:24 +00002380 // transformed A can be a derived class of the deduced A. Likewise,
2381 // if P is a pointer to a class of the form simple-template-id, the
2382 // transformed A can be a pointer to a derived class pointed to by
2383 // the deduced A.
2384 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002385 (isa<PointerType>(ParamType) &&
Douglas Gregor41128772009-06-26 23:27:24 +00002386 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00002387 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00002388 TDF |= TDF_DerivedClass;
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregore53060f2009-06-25 22:08:12 +00002390 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002391 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00002392 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00002393 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00002394 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002396 // FIXME: we need to check that the deduced A is the same as A,
2397 // modulo the various allowed differences.
Douglas Gregore53060f2009-06-25 22:08:12 +00002398 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002399
Mike Stump1eb44332009-09-09 15:08:12 +00002400 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00002401 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002402 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00002403}
2404
Douglas Gregor83314aa2009-07-08 20:55:45 +00002405/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00002406/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2407/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002408///
2409/// \param FunctionTemplate the function template for which we are performing
2410/// template argument deduction.
2411///
Douglas Gregor4b52e252009-12-21 23:17:24 +00002412/// \param ExplicitTemplateArguments the explicitly-specified template
2413/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002414///
2415/// \param ArgFunctionType the function type that will be used as the
2416/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00002417/// function template's function type. This type may be NULL, if there is no
2418/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00002419///
2420/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00002421/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00002422/// template argument deduction.
2423///
2424/// \param Info the argument will be updated to provide additional information
2425/// about template argument deduction.
2426///
2427/// \returns the result of template argument deduction.
2428Sema::TemplateDeductionResult
2429Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002430 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002431 QualType ArgFunctionType,
2432 FunctionDecl *&Specialization,
2433 TemplateDeductionInfo &Info) {
2434 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2435 TemplateParameterList *TemplateParams
2436 = FunctionTemplate->getTemplateParameters();
2437 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002438
Douglas Gregor83314aa2009-07-08 20:55:45 +00002439 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00002440 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00002441 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2442 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002443 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00002444 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002445 if (TemplateDeductionResult Result
2446 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00002447 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002448 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00002449 &FunctionType, Info))
2450 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002451
2452 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00002453 }
2454
2455 // Template argument deduction for function templates in a SFINAE context.
2456 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002457 SFINAETrap Trap(*this);
2458
John McCalleff92132010-02-02 02:21:27 +00002459 Deduced.resize(TemplateParams->size());
2460
Douglas Gregor4b52e252009-12-21 23:17:24 +00002461 if (!ArgFunctionType.isNull()) {
2462 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00002463 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002464 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00002465 FunctionType, ArgFunctionType, Info,
2466 Deduced, 0))
2467 return Result;
2468 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00002469
2470 if (TemplateDeductionResult Result
2471 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2472 NumExplicitlySpecified,
2473 Specialization, Info))
2474 return Result;
2475
2476 // If the requested function type does not match the actual type of the
2477 // specialization, template argument deduction fails.
2478 if (!ArgFunctionType.isNull() &&
2479 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2480 return TDK_NonDeducedMismatch;
2481
2482 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00002483}
2484
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002485/// \brief Deduce template arguments for a templated conversion
2486/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2487/// conversion function template specialization.
2488Sema::TemplateDeductionResult
2489Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2490 QualType ToType,
2491 CXXConversionDecl *&Specialization,
2492 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00002493 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002494 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2495 QualType FromType = Conv->getConversionType();
2496
2497 // Canonicalize the types for deduction.
2498 QualType P = Context.getCanonicalType(FromType);
2499 QualType A = Context.getCanonicalType(ToType);
2500
2501 // C++0x [temp.deduct.conv]p3:
2502 // If P is a reference type, the type referred to by P is used for
2503 // type deduction.
2504 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2505 P = PRef->getPointeeType();
2506
2507 // C++0x [temp.deduct.conv]p3:
2508 // If A is a reference type, the type referred to by A is used
2509 // for type deduction.
2510 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2511 A = ARef->getPointeeType();
2512 // C++ [temp.deduct.conv]p2:
2513 //
Mike Stump1eb44332009-09-09 15:08:12 +00002514 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002515 else {
2516 assert(!A->isReferenceType() && "Reference types were handled above");
2517
2518 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00002519 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002520 // of P for type deduction; otherwise,
2521 if (P->isArrayType())
2522 P = Context.getArrayDecayedType(P);
2523 // - If P is a function type, the pointer type produced by the
2524 // function-to-pointer standard conversion (4.3) is used in
2525 // place of P for type deduction; otherwise,
2526 else if (P->isFunctionType())
2527 P = Context.getPointerType(P);
2528 // - If P is a cv-qualified type, the top level cv-qualifiers of
2529 // P’s type are ignored for type deduction.
2530 else
2531 P = P.getUnqualifiedType();
2532
2533 // C++0x [temp.deduct.conv]p3:
2534 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2535 // type are ignored for type deduction.
2536 A = A.getUnqualifiedType();
2537 }
2538
2539 // Template argument deduction for function templates in a SFINAE context.
2540 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00002541 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002542
2543 // C++ [temp.deduct.conv]p1:
2544 // Template argument deduction is done by comparing the return
2545 // type of the template conversion function (call it P) with the
2546 // type that is required as the result of the conversion (call it
2547 // A) as described in 14.8.2.4.
2548 TemplateParameterList *TemplateParams
2549 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002550 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00002551 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002552
2553 // C++0x [temp.deduct.conv]p4:
2554 // In general, the deduction process attempts to find template
2555 // argument values that will make the deduced A identical to
2556 // A. However, there are two cases that allow a difference:
2557 unsigned TDF = 0;
2558 // - If the original A is a reference type, A can be more
2559 // cv-qualified than the deduced A (i.e., the type referred to
2560 // by the reference)
2561 if (ToType->isReferenceType())
2562 TDF |= TDF_ParamWithReferenceType;
2563 // - The deduced A can be another pointer or pointer to member
2564 // type that can be converted to A via a qualification
2565 // conversion.
2566 //
2567 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2568 // both P and A are pointers or member pointers. In this case, we
2569 // just ignore cv-qualifiers completely).
2570 if ((P->isPointerType() && A->isPointerType()) ||
2571 (P->isMemberPointerType() && P->isMemberPointerType()))
2572 TDF |= TDF_IgnoreQualifiers;
2573 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002574 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002575 P, A, Info, Deduced, TDF))
2576 return Result;
2577
2578 // FIXME: we need to check that the deduced A is the same as A,
2579 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002580
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002581 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002582 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002583 FunctionDecl *Spec = 0;
2584 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002585 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2586 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002587 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2588 return Result;
2589}
2590
Douglas Gregor4b52e252009-12-21 23:17:24 +00002591/// \brief Deduce template arguments for a function template when there is
2592/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2593///
2594/// \param FunctionTemplate the function template for which we are performing
2595/// template argument deduction.
2596///
2597/// \param ExplicitTemplateArguments the explicitly-specified template
2598/// arguments.
2599///
2600/// \param Specialization if template argument deduction was successful,
2601/// this will be set to the function template specialization produced by
2602/// template argument deduction.
2603///
2604/// \param Info the argument will be updated to provide additional information
2605/// about template argument deduction.
2606///
2607/// \returns the result of template argument deduction.
2608Sema::TemplateDeductionResult
2609Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2610 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2611 FunctionDecl *&Specialization,
2612 TemplateDeductionInfo &Info) {
2613 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2614 QualType(), Specialization, Info);
2615}
2616
Douglas Gregor8a514912009-09-14 18:39:43 +00002617/// \brief Stores the result of comparing the qualifiers of two types.
2618enum DeductionQualifierComparison {
2619 NeitherMoreQualified = 0,
2620 ParamMoreQualified,
2621 ArgMoreQualified
2622};
2623
2624/// \brief Deduce the template arguments during partial ordering by comparing
2625/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2626///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002627/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002628///
2629/// \param TemplateParams the template parameters that we are deducing
2630///
2631/// \param ParamIn the parameter type
2632///
2633/// \param ArgIn the argument type
2634///
2635/// \param Info information about the template argument deduction itself
2636///
2637/// \param Deduced the deduced template arguments
2638///
2639/// \returns the result of template argument deduction so far. Note that a
2640/// "success" result means that template argument deduction has not yet failed,
2641/// but it may still fail, later, for other reasons.
2642static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002643DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002644 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002645 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002646 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002647 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2648 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002649 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2650 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002651
2652 // C++0x [temp.deduct.partial]p5:
2653 // Before the partial ordering is done, certain transformations are
2654 // performed on the types used for partial ordering:
2655 // - If P is a reference type, P is replaced by the type referred to.
2656 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002657 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002658 Param = ParamRef->getPointeeType();
2659
2660 // - If A is a reference type, A is replaced by the type referred to.
2661 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002662 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002663 Arg = ArgRef->getPointeeType();
2664
John McCalle27ec8a2009-10-23 23:03:21 +00002665 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002666 // C++0x [temp.deduct.partial]p6:
2667 // If both P and A were reference types (before being replaced with the
2668 // type referred to above), determine which of the two types (if any) is
2669 // more cv-qualified than the other; otherwise the types are considered to
2670 // be equally cv-qualified for partial ordering purposes. The result of this
2671 // determination will be used below.
2672 //
2673 // We save this information for later, using it only when deduction
2674 // succeeds in both directions.
2675 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2676 if (Param.isMoreQualifiedThan(Arg))
2677 QualifierResult = ParamMoreQualified;
2678 else if (Arg.isMoreQualifiedThan(Param))
2679 QualifierResult = ArgMoreQualified;
2680 QualifierComparisons->push_back(QualifierResult);
2681 }
2682
2683 // C++0x [temp.deduct.partial]p7:
2684 // Remove any top-level cv-qualifiers:
2685 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2686 // version of P.
2687 Param = Param.getUnqualifiedType();
2688 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2689 // version of A.
2690 Arg = Arg.getUnqualifiedType();
2691
2692 // C++0x [temp.deduct.partial]p8:
2693 // Using the resulting types P and A the deduction is then done as
2694 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2695 // from the argument template is considered to be at least as specialized
2696 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002697 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002698 Deduced, TDF_None);
2699}
2700
2701static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002702MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2703 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002704 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002705 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002706
2707/// \brief If this is a non-static member function,
2708static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2709 CXXMethodDecl *Method,
2710 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2711 if (Method->isStatic())
2712 return;
2713
2714 // C++ [over.match.funcs]p4:
2715 //
2716 // For non-static member functions, the type of the implicit
2717 // object parameter is
2718 // — "lvalue reference to cv X" for functions declared without a
2719 // ref-qualifier or with the & ref-qualifier
2720 // - "rvalue reference to cv X" for functions declared with the
2721 // && ref-qualifier
2722 //
2723 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2724 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2725 ArgTy = Context.getQualifiedType(ArgTy,
2726 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2727 ArgTy = Context.getLValueReferenceType(ArgTy);
2728 ArgTypes.push_back(ArgTy);
2729}
2730
Douglas Gregor8a514912009-09-14 18:39:43 +00002731/// \brief Determine whether the function template \p FT1 is at least as
2732/// specialized as \p FT2.
2733static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002734 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002735 FunctionTemplateDecl *FT1,
2736 FunctionTemplateDecl *FT2,
2737 TemplatePartialOrderingContext TPOC,
2738 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2739 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2740 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2741 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2742 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2743
2744 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2745 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002746 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002747 Deduced.resize(TemplateParams->size());
2748
2749 // C++0x [temp.deduct.partial]p3:
2750 // The types used to determine the ordering depend on the context in which
2751 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002752 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002753 CXXMethodDecl *Method1 = 0;
2754 CXXMethodDecl *Method2 = 0;
2755 bool IsNonStatic2 = false;
2756 bool IsNonStatic1 = false;
2757 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002758 switch (TPOC) {
2759 case TPOC_Call: {
2760 // - In the context of a function call, the function parameter types are
2761 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002762 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2763 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2764 IsNonStatic1 = Method1 && !Method1->isStatic();
2765 IsNonStatic2 = Method2 && !Method2->isStatic();
2766
2767 // C++0x [temp.func.order]p3:
2768 // [...] If only one of the function templates is a non-static
2769 // member, that function template is considered to have a new
2770 // first parameter inserted in its function parameter list. The
2771 // new parameter is of type "reference to cv A," where cv are
2772 // the cv-qualifiers of the function template (if any) and A is
2773 // the class of which the function template is a member.
2774 //
2775 // C++98/03 doesn't have this provision, so instead we drop the
2776 // first argument of the free function or static member, which
2777 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002778 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002779 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2780 IsNonStatic2 && !IsNonStatic1;
2781 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002782 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2783 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002784 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002785
2786 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002787 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2788 IsNonStatic1 && !IsNonStatic2;
2789 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002790 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2791 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002792 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002793
2794 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002795 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002796 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002797 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002798 Args2[I],
2799 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002800 Info,
2801 Deduced,
2802 QualifierComparisons))
2803 return false;
2804
2805 break;
2806 }
2807
2808 case TPOC_Conversion:
2809 // - In the context of a call to a conversion operator, the return types
2810 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002811 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002812 TemplateParams,
2813 Proto2->getResultType(),
2814 Proto1->getResultType(),
2815 Info,
2816 Deduced,
2817 QualifierComparisons))
2818 return false;
2819 break;
2820
2821 case TPOC_Other:
2822 // - In other contexts (14.6.6.2) the function template’s function type
2823 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002824 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002825 TemplateParams,
2826 FD2->getType(),
2827 FD1->getType(),
2828 Info,
2829 Deduced,
2830 QualifierComparisons))
2831 return false;
2832 break;
2833 }
2834
2835 // C++0x [temp.deduct.partial]p11:
2836 // In most cases, all template parameters must have values in order for
2837 // deduction to succeed, but for partial ordering purposes a template
2838 // parameter may remain without a value provided it is not used in the
2839 // types being used for partial ordering. [ Note: a template parameter used
2840 // in a non-deduced context is considered used. -end note]
2841 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2842 for (; ArgIdx != NumArgs; ++ArgIdx)
2843 if (Deduced[ArgIdx].isNull())
2844 break;
2845
2846 if (ArgIdx == NumArgs) {
2847 // All template arguments were deduced. FT1 is at least as specialized
2848 // as FT2.
2849 return true;
2850 }
2851
Douglas Gregore73bb602009-09-14 21:25:05 +00002852 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002853 llvm::SmallVector<bool, 4> UsedParameters;
2854 UsedParameters.resize(TemplateParams->size());
2855 switch (TPOC) {
2856 case TPOC_Call: {
2857 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002858 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2859 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2860 TemplateParams->getDepth(), UsedParameters);
2861 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002862 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2863 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002864 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002865 break;
2866 }
2867
2868 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002869 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2870 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002871 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002872 break;
2873
2874 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002875 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2876 TemplateParams->getDepth(),
2877 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002878 break;
2879 }
2880
2881 for (; ArgIdx != NumArgs; ++ArgIdx)
2882 // If this argument had no value deduced but was used in one of the types
2883 // used for partial ordering, then deduction fails.
2884 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2885 return false;
2886
2887 return true;
2888}
2889
2890
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002891/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002892/// to the rules of function template partial ordering (C++ [temp.func.order]).
2893///
2894/// \param FT1 the first function template
2895///
2896/// \param FT2 the second function template
2897///
Douglas Gregor8a514912009-09-14 18:39:43 +00002898/// \param TPOC the context in which we are performing partial ordering of
2899/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00002900///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002901/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002902/// template is more specialized, returns NULL.
2903FunctionTemplateDecl *
2904Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2905 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00002906 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002907 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002908 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00002909 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2910 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00002911 &QualifierComparisons);
2912
2913 if (Better1 != Better2) // We have a clear winner
2914 return Better1? FT1 : FT2;
2915
2916 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002917 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002918
2919
2920 // C++0x [temp.deduct.partial]p10:
2921 // If for each type being considered a given template is at least as
2922 // specialized for all types and more specialized for some set of types and
2923 // the other template is not more specialized for any types or is not at
2924 // least as specialized for any types, then the given template is more
2925 // specialized than the other template. Otherwise, neither template is more
2926 // specialized than the other.
2927 Better1 = false;
2928 Better2 = false;
2929 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2930 // C++0x [temp.deduct.partial]p9:
2931 // If, for a given type, deduction succeeds in both directions (i.e., the
2932 // types are identical after the transformations above) and if the type
2933 // from the argument template is more cv-qualified than the type from the
2934 // parameter template (as described above) that type is considered to be
2935 // more specialized than the other. If neither type is more cv-qualified
2936 // than the other then neither type is more specialized than the other.
2937 switch (QualifierComparisons[I]) {
2938 case NeitherMoreQualified:
2939 break;
2940
2941 case ParamMoreQualified:
2942 Better1 = true;
2943 if (Better2)
2944 return 0;
2945 break;
2946
2947 case ArgMoreQualified:
2948 Better2 = true;
2949 if (Better1)
2950 return 0;
2951 break;
2952 }
2953 }
2954
2955 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002956 if (Better1)
2957 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00002958 else if (Better2)
2959 return FT2;
2960 else
2961 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002962}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002963
Douglas Gregord5a423b2009-09-25 18:43:00 +00002964/// \brief Determine if the two templates are equivalent.
2965static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2966 if (T1 == T2)
2967 return true;
2968
2969 if (!T1 || !T2)
2970 return false;
2971
2972 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2973}
2974
2975/// \brief Retrieve the most specialized of the given function template
2976/// specializations.
2977///
John McCallc373d482010-01-27 01:50:18 +00002978/// \param SpecBegin the start iterator of the function template
2979/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002980///
John McCallc373d482010-01-27 01:50:18 +00002981/// \param SpecEnd the end iterator of the function template
2982/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002983///
2984/// \param TPOC the partial ordering context to use to compare the function
2985/// template specializations.
2986///
2987/// \param Loc the location where the ambiguity or no-specializations
2988/// diagnostic should occur.
2989///
2990/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2991/// no matching candidates.
2992///
2993/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2994/// occurs.
2995///
2996/// \param CandidateDiag partial diagnostic used for each function template
2997/// specialization that is a candidate in the ambiguous ordering. One parameter
2998/// in this diagnostic should be unbound, which will correspond to the string
2999/// describing the template arguments for the function template specialization.
3000///
3001/// \param Index if non-NULL and the result of this function is non-nULL,
3002/// receives the index corresponding to the resulting function template
3003/// specialization.
3004///
3005/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00003006/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00003007///
3008/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
3009/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00003010UnresolvedSetIterator
3011Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
3012 UnresolvedSetIterator SpecEnd,
3013 TemplatePartialOrderingContext TPOC,
3014 SourceLocation Loc,
3015 const PartialDiagnostic &NoneDiag,
3016 const PartialDiagnostic &AmbigDiag,
3017 const PartialDiagnostic &CandidateDiag) {
3018 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00003019 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00003020 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003021 }
3022
John McCallc373d482010-01-27 01:50:18 +00003023 if (SpecBegin + 1 == SpecEnd)
3024 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003025
3026 // Find the function template that is better than all of the templates it
3027 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00003028 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003029 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00003030 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003031 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003032 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
3033 FunctionTemplateDecl *Challenger
3034 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003035 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00003036 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003037 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003038 Challenger)) {
3039 Best = I;
3040 BestTemplate = Challenger;
3041 }
3042 }
3043
3044 // Make sure that the "best" function template is more specialized than all
3045 // of the others.
3046 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00003047 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
3048 FunctionTemplateDecl *Challenger
3049 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00003050 if (I != Best &&
3051 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00003052 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00003053 BestTemplate)) {
3054 Ambiguous = true;
3055 break;
3056 }
3057 }
3058
3059 if (!Ambiguous) {
3060 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00003061 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003062 }
3063
3064 // Diagnose the ambiguity.
3065 Diag(Loc, AmbigDiag);
3066
3067 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00003068 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
3069 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00003070 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00003071 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
3072 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00003073
John McCallc373d482010-01-27 01:50:18 +00003074 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00003075}
3076
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003077/// \brief Returns the more specialized class template partial specialization
3078/// according to the rules of partial ordering of class template partial
3079/// specializations (C++ [temp.class.order]).
3080///
3081/// \param PS1 the first class template partial specialization
3082///
3083/// \param PS2 the second class template partial specialization
3084///
3085/// \returns the more specialized class template partial specialization. If
3086/// neither partial specialization is more specialized, returns NULL.
3087ClassTemplatePartialSpecializationDecl *
3088Sema::getMoreSpecializedPartialSpecialization(
3089 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00003090 ClassTemplatePartialSpecializationDecl *PS2,
3091 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003092 // C++ [temp.class.order]p1:
3093 // For two class template partial specializations, the first is at least as
3094 // specialized as the second if, given the following rewrite to two
3095 // function templates, the first function template is at least as
3096 // specialized as the second according to the ordering rules for function
3097 // templates (14.6.6.2):
3098 // - the first function template has the same template parameters as the
3099 // first partial specialization and has a single function parameter
3100 // whose type is a class template specialization with the template
3101 // arguments of the first partial specialization, and
3102 // - the second function template has the same template parameters as the
3103 // second partial specialization and has a single function parameter
3104 // whose type is a class template specialization with the template
3105 // arguments of the second partial specialization.
3106 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00003107 // Rather than synthesize function templates, we merely perform the
3108 // equivalent partial ordering by performing deduction directly on
3109 // the template arguments of the class template partial
3110 // specializations. This computation is slightly simpler than the
3111 // general problem of function template partial ordering, because
3112 // class template partial specializations are more constrained. We
3113 // know that every template parameter is deducible from the class
3114 // template partial specialization's template arguments, for
3115 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00003116 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00003117 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00003118
3119 QualType PT1 = PS1->getInjectedSpecializationType();
3120 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003121
3122 // Determine whether PS1 is at least as specialized as PS2
3123 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003124 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003125 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003126 PT2,
3127 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003128 Info,
3129 Deduced,
3130 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003131 if (Better1) {
3132 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
3133 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003134 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
3135 PS1->getTemplateArgs(),
3136 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003137 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00003138
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003139 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00003140 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003141 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00003142 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003143 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00003144 PT1,
3145 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003146 Info,
3147 Deduced,
3148 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003149 if (Better2) {
3150 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
3151 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00003152 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
3153 PS2->getTemplateArgs(),
3154 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00003155 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00003156
3157 if (Better1 == Better2)
3158 return 0;
3159
3160 return Better1? PS1 : PS2;
3161}
3162
Mike Stump1eb44332009-09-09 15:08:12 +00003163static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003164MarkUsedTemplateParameters(Sema &SemaRef,
3165 const TemplateArgument &TemplateArg,
3166 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003167 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003168 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003169
Douglas Gregore73bb602009-09-14 21:25:05 +00003170/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003171/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00003172static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003173MarkUsedTemplateParameters(Sema &SemaRef,
3174 const Expr *E,
3175 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003176 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003177 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregorbe230c32011-01-03 17:17:50 +00003178 // We can deduce from a pack expansion.
3179 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
3180 E = Expansion->getPattern();
3181
Douglas Gregor54c53cc2011-01-04 23:35:54 +00003182 // Skip through any implicit casts we added while type-checking.
3183 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3184 E = ICE->getSubExpr();
3185
Douglas Gregore73bb602009-09-14 21:25:05 +00003186 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
3187 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003188 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00003189 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00003190 return;
3191
Mike Stump1eb44332009-09-09 15:08:12 +00003192 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00003193 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3194 if (!NTTP)
3195 return;
3196
Douglas Gregored9c0f92009-10-29 00:04:11 +00003197 if (NTTP->getDepth() == Depth)
3198 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003199}
3200
Douglas Gregore73bb602009-09-14 21:25:05 +00003201/// \brief Mark the template parameters that are used by the given
3202/// nested name specifier.
3203static void
3204MarkUsedTemplateParameters(Sema &SemaRef,
3205 NestedNameSpecifier *NNS,
3206 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003207 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003208 llvm::SmallVectorImpl<bool> &Used) {
3209 if (!NNS)
3210 return;
3211
Douglas Gregored9c0f92009-10-29 00:04:11 +00003212 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
3213 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003214 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003215 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003216}
3217
3218/// \brief Mark the template parameters that are used by the given
3219/// template name.
3220static void
3221MarkUsedTemplateParameters(Sema &SemaRef,
3222 TemplateName Name,
3223 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003224 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003225 llvm::SmallVectorImpl<bool> &Used) {
3226 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3227 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00003228 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
3229 if (TTP->getDepth() == Depth)
3230 Used[TTP->getIndex()] = true;
3231 }
Douglas Gregore73bb602009-09-14 21:25:05 +00003232 return;
3233 }
3234
Douglas Gregor788cd062009-11-11 01:00:40 +00003235 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
3236 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
3237 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003238 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00003239 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
3240 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003241}
3242
3243/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00003244/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003245static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003246MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
3247 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003248 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003249 llvm::SmallVectorImpl<bool> &Used) {
3250 if (T.isNull())
3251 return;
3252
Douglas Gregor031a5882009-06-13 00:26:55 +00003253 // Non-dependent types have nothing deducible
3254 if (!T->isDependentType())
3255 return;
3256
3257 T = SemaRef.Context.getCanonicalType(T);
3258 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003259 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003260 MarkUsedTemplateParameters(SemaRef,
3261 cast<PointerType>(T)->getPointeeType(),
3262 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003263 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003264 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003265 break;
3266
3267 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00003268 MarkUsedTemplateParameters(SemaRef,
3269 cast<BlockPointerType>(T)->getPointeeType(),
3270 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003271 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003272 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003273 break;
3274
3275 case Type::LValueReference:
3276 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00003277 MarkUsedTemplateParameters(SemaRef,
3278 cast<ReferenceType>(T)->getPointeeType(),
3279 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003280 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003281 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003282 break;
3283
3284 case Type::MemberPointer: {
3285 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00003286 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003287 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003288 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003289 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003290 break;
3291 }
3292
3293 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003294 MarkUsedTemplateParameters(SemaRef,
3295 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003296 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003297 // Fall through to check the element type
3298
3299 case Type::ConstantArray:
3300 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00003301 MarkUsedTemplateParameters(SemaRef,
3302 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003303 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003304 break;
3305
3306 case Type::Vector:
3307 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00003308 MarkUsedTemplateParameters(SemaRef,
3309 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003310 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003311 break;
3312
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003313 case Type::DependentSizedExtVector: {
3314 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003315 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003316 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003317 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003318 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003319 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003320 break;
3321 }
3322
Douglas Gregor031a5882009-06-13 00:26:55 +00003323 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003324 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003325 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003326 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003327 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00003328 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003329 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003330 break;
3331 }
3332
Douglas Gregored9c0f92009-10-29 00:04:11 +00003333 case Type::TemplateTypeParm: {
3334 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3335 if (TTP->getDepth() == Depth)
3336 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00003337 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00003338 }
Douglas Gregor031a5882009-06-13 00:26:55 +00003339
John McCall31f17ec2010-04-27 00:57:59 +00003340 case Type::InjectedClassName:
3341 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3342 // fall through
3343
Douglas Gregor031a5882009-06-13 00:26:55 +00003344 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00003345 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00003346 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00003347 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003348 Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003349
3350 // C++0x [temp.deduct.type]p9:
3351 // If the template argument list of P contains a pack expansion that is not
3352 // the last template argument, the entire template argument list is a
3353 // non-deduced context.
3354 if (OnlyDeduced &&
3355 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3356 break;
3357
Douglas Gregore73bb602009-09-14 21:25:05 +00003358 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003359 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3360 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003361 break;
3362 }
3363
Douglas Gregore73bb602009-09-14 21:25:05 +00003364 case Type::Complex:
3365 if (!OnlyDeduced)
3366 MarkUsedTemplateParameters(SemaRef,
3367 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003368 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003369 break;
3370
Douglas Gregor4714c122010-03-31 17:34:00 +00003371 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00003372 if (!OnlyDeduced)
3373 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00003374 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003375 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00003376 break;
3377
John McCall33500952010-06-11 00:33:02 +00003378 case Type::DependentTemplateSpecialization: {
3379 const DependentTemplateSpecializationType *Spec
3380 = cast<DependentTemplateSpecializationType>(T);
3381 if (!OnlyDeduced)
3382 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3383 OnlyDeduced, Depth, Used);
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003384
3385 // C++0x [temp.deduct.type]p9:
3386 // If the template argument list of P contains a pack expansion that is not
3387 // the last template argument, the entire template argument list is a
3388 // non-deduced context.
3389 if (OnlyDeduced &&
3390 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3391 break;
3392
John McCall33500952010-06-11 00:33:02 +00003393 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3394 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3395 Used);
3396 break;
3397 }
3398
John McCallad5e7382010-03-01 23:49:17 +00003399 case Type::TypeOf:
3400 if (!OnlyDeduced)
3401 MarkUsedTemplateParameters(SemaRef,
3402 cast<TypeOfType>(T)->getUnderlyingType(),
3403 OnlyDeduced, Depth, Used);
3404 break;
3405
3406 case Type::TypeOfExpr:
3407 if (!OnlyDeduced)
3408 MarkUsedTemplateParameters(SemaRef,
3409 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3410 OnlyDeduced, Depth, Used);
3411 break;
3412
3413 case Type::Decltype:
3414 if (!OnlyDeduced)
3415 MarkUsedTemplateParameters(SemaRef,
3416 cast<DecltypeType>(T)->getUnderlyingExpr(),
3417 OnlyDeduced, Depth, Used);
3418 break;
3419
Douglas Gregor7536dd52010-12-20 02:24:11 +00003420 case Type::PackExpansion:
3421 MarkUsedTemplateParameters(SemaRef,
3422 cast<PackExpansionType>(T)->getPattern(),
3423 OnlyDeduced, Depth, Used);
3424 break;
3425
Douglas Gregore73bb602009-09-14 21:25:05 +00003426 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00003427 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00003428 case Type::VariableArray:
3429 case Type::FunctionNoProto:
3430 case Type::Record:
3431 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00003432 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00003433 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00003434 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00003435 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00003436#define TYPE(Class, Base)
3437#define ABSTRACT_TYPE(Class, Base)
3438#define DEPENDENT_TYPE(Class, Base)
3439#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3440#include "clang/AST/TypeNodes.def"
3441 break;
3442 }
3443}
3444
Douglas Gregore73bb602009-09-14 21:25:05 +00003445/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00003446/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00003447static void
Douglas Gregore73bb602009-09-14 21:25:05 +00003448MarkUsedTemplateParameters(Sema &SemaRef,
3449 const TemplateArgument &TemplateArg,
3450 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003451 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003452 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00003453 switch (TemplateArg.getKind()) {
3454 case TemplateArgument::Null:
3455 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00003456 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00003457 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Douglas Gregor031a5882009-06-13 00:26:55 +00003459 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00003460 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003461 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003462 break;
3463
Douglas Gregor788cd062009-11-11 01:00:40 +00003464 case TemplateArgument::Template:
Douglas Gregora7fc9012011-01-05 18:58:31 +00003465 case TemplateArgument::TemplateExpansion:
3466 MarkUsedTemplateParameters(SemaRef,
3467 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor788cd062009-11-11 01:00:40 +00003468 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003469 break;
3470
3471 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00003472 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003473 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003474 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00003475
Anders Carlssond01b1da2009-06-15 17:04:53 +00003476 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00003477 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3478 PEnd = TemplateArg.pack_end();
3479 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003480 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00003481 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00003482 }
3483}
3484
3485/// \brief Mark the template parameters can be deduced by the given
3486/// template argument list.
3487///
3488/// \param TemplateArgs the template argument list from which template
3489/// parameters will be deduced.
3490///
3491/// \param Deduced a bit vector whose elements will be set to \c true
3492/// to indicate when the corresponding template parameter will be
3493/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00003494void
Douglas Gregore73bb602009-09-14 21:25:05 +00003495Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003496 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00003497 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor7b976ec2010-12-23 01:24:45 +00003498 // C++0x [temp.deduct.type]p9:
3499 // If the template argument list of P contains a pack expansion that is not
3500 // the last template argument, the entire template argument list is a
3501 // non-deduced context.
3502 if (OnlyDeduced &&
3503 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3504 return;
3505
Douglas Gregor031a5882009-06-13 00:26:55 +00003506 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00003507 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3508 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00003509}
Douglas Gregor63f07c52009-09-18 23:21:38 +00003510
3511/// \brief Marks all of the template parameters that will be deduced by a
3512/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00003513void
3514Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3515 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00003516 TemplateParameterList *TemplateParams
3517 = FunctionTemplate->getTemplateParameters();
3518 Deduced.clear();
3519 Deduced.resize(TemplateParams->size());
3520
3521 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3522 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3523 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00003524 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00003525}