blob: ad649c067c69968b75f3ed9034fd2912567e253e [file] [log] [blame]
Douglas Gregor55ca8f62009-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 Gregorc3a6ade2010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall8b0666c2010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
Douglas Gregor7baabef2010-12-22 18:17:10 +000015#include "clang/Sema/SemaDiagnostic.h" // FIXME: temporary!
John McCallde6836a2010-08-24 07:21:54 +000016#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000017#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000018#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000019#include "clang/AST/DeclObjC.h"
Douglas Gregor55ca8f62009-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 Gregor0f3feb42010-12-22 21:19:48 +000024#include "llvm/ADT/BitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000025#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000026
27namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000028 using namespace sema;
29
Douglas Gregorcf0b47d2009-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 Gregorfc516c92009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-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 Gregorcf0b47d2009-06-26 23:10:12 +000053 };
54}
55
Douglas Gregor55ca8f62009-06-04 00:03:07 +000056using namespace clang;
57
Douglas Gregor0a29a052010-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 Foad6d4db0c2010-12-07 08:25:34 +000062 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000063 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000064 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-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 Gregor181aa4a2009-06-12 18:26:56 +000079static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000080DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000081 TemplateParameterList *TemplateParams,
82 const TemplateArgument &Param,
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000083 const TemplateArgument &Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000084 TemplateDeductionInfo &Info,
Douglas Gregord80ea202010-12-22 18:55:49 +000085 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000086
Douglas Gregor7baabef2010-12-22 18:17:10 +000087static Sema::TemplateDeductionResult
88DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
90 const TemplateArgument *Params, unsigned NumParams,
91 const TemplateArgument *Args, unsigned NumArgs,
92 TemplateDeductionInfo &Info,
Douglas Gregord80ea202010-12-22 18:55:49 +000093 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
94 bool NumberOfArgumentsMustMatch = true);
Douglas Gregor7baabef2010-12-22 18:17:10 +000095
Douglas Gregorb7ae10f2009-06-05 00:53:49 +000096/// \brief If the given expression is of a form that permits the deduction
97/// of a non-type template parameter, return the declaration of that
98/// non-type template parameter.
99static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
100 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
101 E = IC->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000102
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000103 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
104 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000105
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000106 return 0;
107}
108
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000109/// \brief Determine whether two declaration pointers refer to the same
110/// declaration.
111static bool isSameDeclaration(Decl *X, Decl *Y) {
112 if (!X || !Y)
113 return !X && !Y;
114
115 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
116 X = NX->getUnderlyingDecl();
117 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
118 Y = NY->getUnderlyingDecl();
119
120 return X->getCanonicalDecl() == Y->getCanonicalDecl();
121}
122
123/// \brief Verify that the given, deduced template arguments are compatible.
124///
125/// \returns The deduced template argument, or a NULL template argument if
126/// the deduced template arguments were incompatible.
127static DeducedTemplateArgument
128checkDeducedTemplateArguments(ASTContext &Context,
129 const DeducedTemplateArgument &X,
130 const DeducedTemplateArgument &Y) {
131 // We have no deduction for one or both of the arguments; they're compatible.
132 if (X.isNull())
133 return Y;
134 if (Y.isNull())
135 return X;
136
137 switch (X.getKind()) {
138 case TemplateArgument::Null:
139 llvm_unreachable("Non-deduced template arguments handled above");
140
141 case TemplateArgument::Type:
142 // If two template type arguments have the same type, they're compatible.
143 if (Y.getKind() == TemplateArgument::Type &&
144 Context.hasSameType(X.getAsType(), Y.getAsType()))
145 return X;
146
147 return DeducedTemplateArgument();
148
149 case TemplateArgument::Integral:
150 // If we deduced a constant in one case and either a dependent expression or
151 // declaration in another case, keep the integral constant.
152 // If both are integral constants with the same value, keep that value.
153 if (Y.getKind() == TemplateArgument::Expression ||
154 Y.getKind() == TemplateArgument::Declaration ||
155 (Y.getKind() == TemplateArgument::Integral &&
156 hasSameExtendedValue(*X.getAsIntegral(), *Y.getAsIntegral())))
157 return DeducedTemplateArgument(X,
158 X.wasDeducedFromArrayBound() &&
159 Y.wasDeducedFromArrayBound());
160
161 // All other combinations are incompatible.
162 return DeducedTemplateArgument();
163
164 case TemplateArgument::Template:
165 if (Y.getKind() == TemplateArgument::Template &&
166 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
167 return X;
168
169 // All other combinations are incompatible.
170 return DeducedTemplateArgument();
171
172 case TemplateArgument::Expression:
173 // If we deduced a dependent expression in one case and either an integral
174 // constant or a declaration in another case, keep the integral constant
175 // or declaration.
176 if (Y.getKind() == TemplateArgument::Integral ||
177 Y.getKind() == TemplateArgument::Declaration)
178 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
179 Y.wasDeducedFromArrayBound());
180
181 if (Y.getKind() == TemplateArgument::Expression) {
182 // Compare the expressions for equality
183 llvm::FoldingSetNodeID ID1, ID2;
184 X.getAsExpr()->Profile(ID1, Context, true);
185 Y.getAsExpr()->Profile(ID2, Context, true);
186 if (ID1 == ID2)
187 return X;
188 }
189
190 // All other combinations are incompatible.
191 return DeducedTemplateArgument();
192
193 case TemplateArgument::Declaration:
194 // If we deduced a declaration and a dependent expression, keep the
195 // declaration.
196 if (Y.getKind() == TemplateArgument::Expression)
197 return X;
198
199 // If we deduced a declaration and an integral constant, keep the
200 // integral constant.
201 if (Y.getKind() == TemplateArgument::Integral)
202 return Y;
203
204 // If we deduced two declarations, make sure they they refer to the
205 // same declaration.
206 if (Y.getKind() == TemplateArgument::Declaration &&
207 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
208 return X;
209
210 // All other combinations are incompatible.
211 return DeducedTemplateArgument();
212
213 case TemplateArgument::Pack:
214 if (Y.getKind() != TemplateArgument::Pack ||
215 X.pack_size() != Y.pack_size())
216 return DeducedTemplateArgument();
217
218 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
219 XAEnd = X.pack_end(),
220 YA = Y.pack_begin();
221 XA != XAEnd; ++XA, ++YA) {
222 // FIXME: We've lost the "deduced from array bound" bit.
223 if (checkDeducedTemplateArguments(Context, *XA, *YA).isNull())
224 return DeducedTemplateArgument();
225 }
226
227 return X;
228 }
229
230 return DeducedTemplateArgument();
231}
232
Mike Stump11289f42009-09-09 15:08:12 +0000233/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000234/// from the given constant.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000235static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000236DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump11289f42009-09-09 15:08:12 +0000237 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor0a29a052010-03-26 05:50:28 +0000238 llvm::APSInt Value, QualType ValueType,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000239 bool DeducedFromArrayBound,
John McCall19c1bfd2010-08-25 05:32:35 +0000240 TemplateDeductionInfo &Info,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000241 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000242 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000243 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000244
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000245 DeducedTemplateArgument NewDeduced(Value, ValueType, DeducedFromArrayBound);
246 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
247 Deduced[NTTP->getIndex()],
248 NewDeduced);
249 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000250 Info.Param = NTTP;
251 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000252 Info.SecondArg = NewDeduced;
253 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000254 }
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000255
256 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000257 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000258}
259
Mike Stump11289f42009-09-09 15:08:12 +0000260/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000261/// from the given type- or value-dependent expression.
262///
263/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000264static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000265DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000266 NonTypeTemplateParmDecl *NTTP,
267 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000268 TemplateDeductionInfo &Info,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000269 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000270 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000271 "Cannot deduce non-type template argument with depth > 0");
272 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
273 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000274
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000275 DeducedTemplateArgument NewDeduced(Value);
276 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
277 Deduced[NTTP->getIndex()],
278 NewDeduced);
279
280 if (Result.isNull()) {
281 Info.Param = NTTP;
282 Info.FirstArg = Deduced[NTTP->getIndex()];
283 Info.SecondArg = NewDeduced;
284 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000285 }
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000286
287 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000288 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000289}
290
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000291/// \brief Deduce the value of the given non-type template parameter
292/// from the given declaration.
293///
294/// \returns true if deduction succeeded, false otherwise.
295static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000296DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000297 NonTypeTemplateParmDecl *NTTP,
298 Decl *D,
John McCall19c1bfd2010-08-25 05:32:35 +0000299 TemplateDeductionInfo &Info,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000300 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000301 assert(NTTP->getDepth() == 0 &&
302 "Cannot deduce non-type template argument with depth > 0");
303
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000304 DeducedTemplateArgument NewDeduced(D? D->getCanonicalDecl() : 0);
305 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
306 Deduced[NTTP->getIndex()],
307 NewDeduced);
308 if (Result.isNull()) {
309 Info.Param = NTTP;
310 Info.FirstArg = Deduced[NTTP->getIndex()];
311 Info.SecondArg = NewDeduced;
312 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000313 }
314
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000315 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000316 return Sema::TDK_Success;
317}
318
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000319static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000320DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000321 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000322 TemplateName Param,
323 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000324 TemplateDeductionInfo &Info,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000325 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000326 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000327 if (!ParamDecl) {
328 // The parameter type is dependent and is not a template template parameter,
329 // so there is nothing that we can deduce.
330 return Sema::TDK_Success;
331 }
332
333 if (TemplateTemplateParmDecl *TempParam
334 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000335 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
336 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
337 Deduced[TempParam->getIndex()],
338 NewDeduced);
339 if (Result.isNull()) {
340 Info.Param = TempParam;
341 Info.FirstArg = Deduced[TempParam->getIndex()];
342 Info.SecondArg = NewDeduced;
343 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000344 }
345
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000346 Deduced[TempParam->getIndex()] = Result;
347 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000348 }
Douglas Gregoradee3e32009-11-11 23:06:43 +0000349
350 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000351 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000352 return Sema::TDK_Success;
353
354 // Mismatch of non-dependent template parameter to argument.
355 Info.FirstArg = TemplateArgument(Param);
356 Info.SecondArg = TemplateArgument(Arg);
357 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000358}
359
Mike Stump11289f42009-09-09 15:08:12 +0000360/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000361/// type (which is a template-id) with the template argument type.
362///
Chandler Carruthc1263112010-02-07 21:33:28 +0000363/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000364///
365/// \param TemplateParams the template parameters that we are deducing
366///
367/// \param Param the parameter type
368///
369/// \param Arg the argument type
370///
371/// \param Info information about the template argument deduction itself
372///
373/// \param Deduced the deduced template arguments
374///
375/// \returns the result of template argument deduction so far. Note that a
376/// "success" result means that template argument deduction has not yet failed,
377/// but it may still fail, later, for other reasons.
378static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000379DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000380 TemplateParameterList *TemplateParams,
381 const TemplateSpecializationType *Param,
382 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000383 TemplateDeductionInfo &Info,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000384 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000385 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000386
Douglas Gregore81f3e72009-07-07 23:09:34 +0000387 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000388 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000389 = dyn_cast<TemplateSpecializationType>(Arg)) {
390 // Perform template argument deduction for the template name.
391 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000392 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000393 Param->getTemplateName(),
394 SpecArg->getTemplateName(),
395 Info, Deduced))
396 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000397
Mike Stump11289f42009-09-09 15:08:12 +0000398
Douglas Gregore81f3e72009-07-07 23:09:34 +0000399 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000400 // argument. Ignore any missing/extra arguments, since they could be
401 // filled in by default arguments.
Douglas Gregor7baabef2010-12-22 18:17:10 +0000402 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord80ea202010-12-22 18:55:49 +0000403 Param->getArgs(), Param->getNumArgs(),
404 SpecArg->getArgs(), SpecArg->getNumArgs(),
405 Info, Deduced,
406 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000407 }
Mike Stump11289f42009-09-09 15:08:12 +0000408
Douglas Gregore81f3e72009-07-07 23:09:34 +0000409 // If the argument type is a class template specialization, we
410 // perform template argument deduction using its template
411 // arguments.
412 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
413 if (!RecordArg)
414 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000415
416 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000417 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
418 if (!SpecArg)
419 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000420
Douglas Gregore81f3e72009-07-07 23:09:34 +0000421 // Perform template argument deduction for the template name.
422 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000423 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000424 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000425 Param->getTemplateName(),
426 TemplateName(SpecArg->getSpecializedTemplate()),
427 Info, Deduced))
428 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000429
Douglas Gregor7baabef2010-12-22 18:17:10 +0000430 // Perform template argument deduction for the template arguments.
431 return DeduceTemplateArguments(S, TemplateParams,
432 Param->getArgs(), Param->getNumArgs(),
433 SpecArg->getTemplateArgs().data(),
434 SpecArg->getTemplateArgs().size(),
435 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000436}
437
John McCall08569062010-08-28 22:14:41 +0000438/// \brief Determines whether the given type is an opaque type that
439/// might be more qualified when instantiated.
440static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
441 switch (T->getTypeClass()) {
442 case Type::TypeOfExpr:
443 case Type::TypeOf:
444 case Type::DependentName:
445 case Type::Decltype:
446 case Type::UnresolvedUsing:
447 return true;
448
449 case Type::ConstantArray:
450 case Type::IncompleteArray:
451 case Type::VariableArray:
452 case Type::DependentSizedArray:
453 return IsPossiblyOpaquelyQualifiedType(
454 cast<ArrayType>(T)->getElementType());
455
456 default:
457 return false;
458 }
459}
460
Douglas Gregorcceb9752009-06-26 18:27:22 +0000461/// \brief Deduce the template arguments by comparing the parameter type and
462/// the argument type (C++ [temp.deduct.type]).
463///
Chandler Carruthc1263112010-02-07 21:33:28 +0000464/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000465///
466/// \param TemplateParams the template parameters that we are deducing
467///
468/// \param ParamIn the parameter type
469///
470/// \param ArgIn the argument type
471///
472/// \param Info information about the template argument deduction itself
473///
474/// \param Deduced the deduced template arguments
475///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000476/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000477/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000478///
479/// \returns the result of template argument deduction so far. Note that a
480/// "success" result means that template argument deduction has not yet failed,
481/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000482static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000483DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000484 TemplateParameterList *TemplateParams,
485 QualType ParamIn, QualType ArgIn,
John McCall19c1bfd2010-08-25 05:32:35 +0000486 TemplateDeductionInfo &Info,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000487 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000488 unsigned TDF) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000489 // We only want to look at the canonical types, since typedefs and
490 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000491 QualType Param = S.Context.getCanonicalType(ParamIn);
492 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000493
Douglas Gregorcceb9752009-06-26 18:27:22 +0000494 // C++0x [temp.deduct.call]p4 bullet 1:
495 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump11289f42009-09-09 15:08:12 +0000496 // referred to by the reference) can be more cv-qualified than the
Douglas Gregorcceb9752009-06-26 18:27:22 +0000497 // transformed A.
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000498 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthc712ce12009-12-30 04:10:01 +0000499 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +0000500 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthc712ce12009-12-30 04:10:01 +0000501 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
502 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carruthc1263112010-02-07 21:33:28 +0000503 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregorcceb9752009-06-26 18:27:22 +0000504 }
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregor705c9002009-06-26 20:57:09 +0000506 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor406f6342009-09-14 20:00:47 +0000507 if (!Param->isDependentType()) {
508 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
509
510 return Sema::TDK_NonDeducedMismatch;
511 }
512
Douglas Gregor705c9002009-06-26 20:57:09 +0000513 return Sema::TDK_Success;
Douglas Gregor406f6342009-09-14 20:00:47 +0000514 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000515
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000516 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +0000517 // A template type argument T, a template template argument TT or a
518 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000519 // the following forms:
520 //
521 // T
522 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +0000523 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +0000524 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000525 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +0000526 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +0000527
Douglas Gregor60454822009-07-22 20:02:25 +0000528 // If the argument type is an array type, move the qualifiers up to the
529 // top level, so they can be matched with the qualifiers on the parameter.
530 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregord6605db2009-07-22 21:30:48 +0000531 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +0000532 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +0000533 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +0000534 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +0000535 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +0000536 RecanonicalizeArg = true;
537 }
538 }
Mike Stump11289f42009-09-09 15:08:12 +0000539
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000540 // The argument type can not be less qualified than the parameter
541 // type.
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000542 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000543 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +0000544 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +0000545 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +0000546 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000547 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000548
549 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +0000550 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +0000551 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +0000552
553 // local manipulation is okay because it's canonical
554 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregord6605db2009-07-22 21:30:48 +0000555 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +0000556 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +0000557
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000558 DeducedTemplateArgument NewDeduced(DeducedType);
559 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
560 Deduced[Index],
561 NewDeduced);
562 if (Result.isNull()) {
563 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
564 Info.FirstArg = Deduced[Index];
565 Info.SecondArg = NewDeduced;
566 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000567 }
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000568
569 Deduced[Index] = Result;
570 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000571 }
572
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000573 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +0000574 Info.FirstArg = TemplateArgument(ParamIn);
575 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000576
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000577 // Check the cv-qualifiers on the parameter and argument types.
578 if (!(TDF & TDF_IgnoreQualifiers)) {
579 if (TDF & TDF_ParamWithReferenceType) {
580 if (Param.isMoreQualifiedThan(Arg))
581 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +0000582 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000583 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +0000584 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000585 }
586 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000587
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000588 switch (Param->getTypeClass()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000589 // No deduction possible for these types
590 case Type::Builtin:
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000591 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000592
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000593 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000594 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +0000595 QualType PointeeType;
596 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
597 PointeeType = PointerArg->getPointeeType();
598 } else if (const ObjCObjectPointerType *PointerArg
599 = Arg->getAs<ObjCObjectPointerType>()) {
600 PointeeType = PointerArg->getPointeeType();
601 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000602 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +0000603 }
Mike Stump11289f42009-09-09 15:08:12 +0000604
Douglas Gregorfc516c92009-06-26 23:27:24 +0000605 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carruthc1263112010-02-07 21:33:28 +0000606 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000607 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +0000608 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +0000609 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000610 }
Mike Stump11289f42009-09-09 15:08:12 +0000611
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000612 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000613 case Type::LValueReference: {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000614 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000615 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000616 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000617
Chandler Carruthc1263112010-02-07 21:33:28 +0000618 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000619 cast<LValueReferenceType>(Param)->getPointeeType(),
620 ReferenceArg->getPointeeType(),
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000621 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000622 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000623
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000624 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000625 case Type::RValueReference: {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000626 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000627 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000628 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000629
Chandler Carruthc1263112010-02-07 21:33:28 +0000630 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000631 cast<RValueReferenceType>(Param)->getPointeeType(),
632 ReferenceArg->getPointeeType(),
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000633 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000634 }
Mike Stump11289f42009-09-09 15:08:12 +0000635
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000636 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +0000637 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +0000638 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +0000639 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +0000640 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000641 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000642
John McCallf7332682010-08-19 00:20:19 +0000643 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carruthc1263112010-02-07 21:33:28 +0000644 return DeduceTemplateArguments(S, TemplateParams,
645 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson35533d12009-06-04 04:11:30 +0000646 IncompleteArrayArg->getElementType(),
John McCallf7332682010-08-19 00:20:19 +0000647 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +0000648 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000649
650 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +0000651 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +0000652 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +0000653 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +0000654 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000655 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000656
657 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +0000658 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +0000659 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000660 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000661
John McCallf7332682010-08-19 00:20:19 +0000662 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carruthc1263112010-02-07 21:33:28 +0000663 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson35533d12009-06-04 04:11:30 +0000664 ConstantArrayParm->getElementType(),
665 ConstantArrayArg->getElementType(),
John McCallf7332682010-08-19 00:20:19 +0000666 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +0000667 }
668
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000669 // type [i]
670 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +0000671 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000672 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000673 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000674
John McCallf7332682010-08-19 00:20:19 +0000675 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
676
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000677 // Check the element type of the arrays
678 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +0000679 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000680 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000681 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000682 DependentArrayParm->getElementType(),
683 ArrayArg->getElementType(),
John McCallf7332682010-08-19 00:20:19 +0000684 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000685 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000686
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000687 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +0000688 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000689 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
690 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000691 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +0000692
693 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000694 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +0000695 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000696 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000697 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +0000698 = dyn_cast<ConstantArrayType>(ArrayArg)) {
699 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor0a29a052010-03-26 05:50:28 +0000700 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
701 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000702 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000703 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +0000704 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000705 if (const DependentSizedArrayType *DependentArrayArg
706 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +0000707 if (DependentArrayArg->getSizeExpr())
708 return DeduceNonTypeTemplateArgument(S, NTTP,
709 DependentArrayArg->getSizeExpr(),
710 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +0000711
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000712 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000713 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000714 }
Mike Stump11289f42009-09-09 15:08:12 +0000715
716 // type(*)(T)
717 // T(*)()
718 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +0000719 case Type::FunctionProto: {
Mike Stump11289f42009-09-09 15:08:12 +0000720 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +0000721 dyn_cast<FunctionProtoType>(Arg);
722 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000723 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000724
725 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +0000726 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +0000727
Mike Stump11289f42009-09-09 15:08:12 +0000728 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson096e6ee2009-06-08 19:22:23 +0000729 FunctionProtoArg->getTypeQuals())
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000730 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000731
Anders Carlsson096e6ee2009-06-08 19:22:23 +0000732 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000733 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000734
Anders Carlsson096e6ee2009-06-08 19:22:23 +0000735 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000736 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +0000737
Anders Carlsson2128ec72009-06-08 15:19:08 +0000738 // Check return types.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000739 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000740 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000741 FunctionProtoParam->getResultType(),
742 FunctionProtoArg->getResultType(),
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000743 Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000744 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000745
Anders Carlsson2128ec72009-06-08 15:19:08 +0000746 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
747 // Check argument types.
Douglas Gregor7baabef2010-12-22 18:17:10 +0000748 // FIXME: Variadic templates.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000749 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000750 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000751 FunctionProtoParam->getArgType(I),
752 FunctionProtoArg->getArgType(I),
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000753 Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000754 return Result;
Anders Carlsson2128ec72009-06-08 15:19:08 +0000755 }
Mike Stump11289f42009-09-09 15:08:12 +0000756
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000757 return Sema::TDK_Success;
Anders Carlsson2128ec72009-06-08 15:19:08 +0000758 }
Mike Stump11289f42009-09-09 15:08:12 +0000759
John McCalle78aac42010-03-10 03:28:59 +0000760 case Type::InjectedClassName: {
761 // Treat a template's injected-class-name as if the template
762 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +0000763 Param = cast<InjectedClassNameType>(Param)
764 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +0000765 assert(isa<TemplateSpecializationType>(Param) &&
766 "injected class name is not a template specialization type");
767 // fall through
768 }
769
Douglas Gregor705c9002009-06-26 20:57:09 +0000770 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000771 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +0000772 // TT<T>
773 // TT<i>
774 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000775 case Type::TemplateSpecialization: {
776 const TemplateSpecializationType *SpecParam
777 = cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +0000778
Douglas Gregore81f3e72009-07-07 23:09:34 +0000779 // Try to deduce template arguments from the template-id.
780 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000781 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000782 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +0000783
Douglas Gregor42909752009-09-30 22:13:51 +0000784 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregore81f3e72009-07-07 23:09:34 +0000785 // C++ [temp.deduct.call]p3b3:
786 // If P is a class, and P has the form template-id, then A can be a
787 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump11289f42009-09-09 15:08:12 +0000788 // class of the form template-id, A can be a pointer to a derived
Douglas Gregore81f3e72009-07-07 23:09:34 +0000789 // class pointed to by the deduced A.
790 //
791 // More importantly:
Mike Stump11289f42009-09-09 15:08:12 +0000792 // These alternatives are considered only if type deduction would
Douglas Gregore81f3e72009-07-07 23:09:34 +0000793 // otherwise fail.
Chandler Carruthc1263112010-02-07 21:33:28 +0000794 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
795 // We cannot inspect base classes as part of deduction when the type
796 // is incomplete, so either instantiate any templates necessary to
797 // complete the type, or skip over it if it cannot be completed.
John McCallbc077cf2010-02-08 23:07:23 +0000798 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carruthc1263112010-02-07 21:33:28 +0000799 return Result;
800
Douglas Gregore81f3e72009-07-07 23:09:34 +0000801 // Use data recursion to crawl through the list of base classes.
Mike Stump11289f42009-09-09 15:08:12 +0000802 // Visited contains the set of nodes we have already visited, while
Douglas Gregore81f3e72009-07-07 23:09:34 +0000803 // ToVisit is our stack of records that we still need to visit.
804 llvm::SmallPtrSet<const RecordType *, 8> Visited;
805 llvm::SmallVector<const RecordType *, 8> ToVisit;
806 ToVisit.push_back(RecordT);
807 bool Successful = false;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +0000808 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
809 DeducedOrig = Deduced;
Douglas Gregore81f3e72009-07-07 23:09:34 +0000810 while (!ToVisit.empty()) {
811 // Retrieve the next class in the inheritance hierarchy.
812 const RecordType *NextT = ToVisit.back();
813 ToVisit.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000814
Douglas Gregore81f3e72009-07-07 23:09:34 +0000815 // If we have already seen this type, skip it.
816 if (!Visited.insert(NextT))
817 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000818
Douglas Gregore81f3e72009-07-07 23:09:34 +0000819 // If this is a base class, try to perform template argument
820 // deduction from it.
821 if (NextT != RecordT) {
822 Sema::TemplateDeductionResult BaseResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000823 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000824 QualType(NextT, 0), Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +0000825
Douglas Gregore81f3e72009-07-07 23:09:34 +0000826 // If template argument deduction for this base was successful,
Douglas Gregore0f7a8a2010-11-02 00:02:34 +0000827 // note that we had some success. Otherwise, ignore any deductions
828 // from this base class.
829 if (BaseResult == Sema::TDK_Success) {
Douglas Gregore81f3e72009-07-07 23:09:34 +0000830 Successful = true;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +0000831 DeducedOrig = Deduced;
832 }
833 else
834 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +0000835 }
Mike Stump11289f42009-09-09 15:08:12 +0000836
Douglas Gregore81f3e72009-07-07 23:09:34 +0000837 // Visit base classes
838 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
839 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
840 BaseEnd = Next->bases_end();
Sebastian Redl1054fae2009-10-25 17:03:50 +0000841 Base != BaseEnd; ++Base) {
Mike Stump11289f42009-09-09 15:08:12 +0000842 assert(Base->getType()->isRecordType() &&
Douglas Gregore81f3e72009-07-07 23:09:34 +0000843 "Base class that isn't a record?");
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000844 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregore81f3e72009-07-07 23:09:34 +0000845 }
846 }
Mike Stump11289f42009-09-09 15:08:12 +0000847
Douglas Gregore81f3e72009-07-07 23:09:34 +0000848 if (Successful)
849 return Sema::TDK_Success;
850 }
Mike Stump11289f42009-09-09 15:08:12 +0000851
Douglas Gregore81f3e72009-07-07 23:09:34 +0000852 }
Mike Stump11289f42009-09-09 15:08:12 +0000853
Douglas Gregore81f3e72009-07-07 23:09:34 +0000854 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000855 }
856
Douglas Gregor637d9982009-06-10 23:47:09 +0000857 // T type::*
858 // T T::*
859 // T (type::*)()
860 // type (T::*)()
861 // type (type::*)(T)
862 // type (T::*)(T)
863 // T (type::*)(T)
864 // T (T::*)()
865 // T (T::*)(T)
866 case Type::MemberPointer: {
867 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
868 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
869 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000870 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +0000871
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000872 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000873 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000874 MemPtrParam->getPointeeType(),
875 MemPtrArg->getPointeeType(),
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000876 Info, Deduced,
877 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000878 return Result;
879
Chandler Carruthc1263112010-02-07 21:33:28 +0000880 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000881 QualType(MemPtrParam->getClass(), 0),
882 QualType(MemPtrArg->getClass(), 0),
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000883 Info, Deduced, 0);
Douglas Gregor637d9982009-06-10 23:47:09 +0000884 }
885
Anders Carlsson15f1dd12009-06-12 22:56:54 +0000886 // (clang extension)
887 //
Mike Stump11289f42009-09-09 15:08:12 +0000888 // type(^)(T)
889 // T(^)()
890 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +0000891 case Type::BlockPointer: {
892 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
893 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000894
Anders Carlssona767eee2009-06-12 16:23:10 +0000895 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000896 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000897
Chandler Carruthc1263112010-02-07 21:33:28 +0000898 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlssona767eee2009-06-12 16:23:10 +0000899 BlockPtrParam->getPointeeType(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000900 BlockPtrArg->getPointeeType(), Info,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000901 Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +0000902 }
903
Douglas Gregor637d9982009-06-10 23:47:09 +0000904 case Type::TypeOfExpr:
905 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +0000906 case Type::DependentName:
Douglas Gregor637d9982009-06-10 23:47:09 +0000907 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000908 return Sema::TDK_Success;
Douglas Gregor637d9982009-06-10 23:47:09 +0000909
Douglas Gregor5cdac0a2009-06-04 00:21:18 +0000910 default:
911 break;
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000912 }
913
914 // FIXME: Many more cases to go (to go).
Douglas Gregor705c9002009-06-26 20:57:09 +0000915 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000916}
917
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000918static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000919DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000920 TemplateParameterList *TemplateParams,
921 const TemplateArgument &Param,
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000922 const TemplateArgument &Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000923 TemplateDeductionInfo &Info,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000924 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000925 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000926 case TemplateArgument::Null:
927 assert(false && "Null template argument in parameter list");
928 break;
Mike Stump11289f42009-09-09 15:08:12 +0000929
930 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000931 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carruthc1263112010-02-07 21:33:28 +0000932 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000933 Arg.getAsType(), Info, Deduced, 0);
934 Info.FirstArg = Param;
935 Info.SecondArg = Arg;
936 return Sema::TDK_NonDeducedMismatch;
937
938 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +0000939 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carruthc1263112010-02-07 21:33:28 +0000940 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000941 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +0000942 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000943 Info.FirstArg = Param;
944 Info.SecondArg = Arg;
945 return Sema::TDK_NonDeducedMismatch;
946
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000947 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000948 if (Arg.getKind() == TemplateArgument::Declaration &&
949 Param.getAsDecl()->getCanonicalDecl() ==
950 Arg.getAsDecl()->getCanonicalDecl())
951 return Sema::TDK_Success;
952
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000953 Info.FirstArg = Param;
954 Info.SecondArg = Arg;
955 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000956
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000957 case TemplateArgument::Integral:
958 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor0a29a052010-03-26 05:50:28 +0000959 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000960 return Sema::TDK_Success;
961
962 Info.FirstArg = Param;
963 Info.SecondArg = Arg;
964 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000965 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000966
967 if (Arg.getKind() == TemplateArgument::Expression) {
968 Info.FirstArg = Param;
969 Info.SecondArg = Arg;
970 return Sema::TDK_NonDeducedMismatch;
971 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000972
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000973 Info.FirstArg = Param;
974 Info.SecondArg = Arg;
975 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +0000976
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000977 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +0000978 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000979 = getDeducedParameterFromExpr(Param.getAsExpr())) {
980 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +0000981 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump11289f42009-09-09 15:08:12 +0000982 *Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +0000983 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000984 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000985 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000986 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +0000987 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000988 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000989 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +0000990 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000991 Info, Deduced);
992
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000993 Info.FirstArg = Param;
994 Info.SecondArg = Arg;
995 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000996 }
Mike Stump11289f42009-09-09 15:08:12 +0000997
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000998 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000999 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001000 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001001 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001002 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001003 }
Mike Stump11289f42009-09-09 15:08:12 +00001004
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001005 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001006}
1007
Douglas Gregor7baabef2010-12-22 18:17:10 +00001008/// \brief Determine whether there is a template argument to be used for
1009/// deduction.
1010///
1011/// This routine "expands" argument packs in-place, overriding its input
1012/// parameters so that \c Args[ArgIdx] will be the available template argument.
1013///
1014/// \returns true if there is another template argument (which will be at
1015/// \c Args[ArgIdx]), false otherwise.
1016static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
1017 unsigned &ArgIdx,
1018 unsigned &NumArgs) {
1019 if (ArgIdx == NumArgs)
1020 return false;
1021
1022 const TemplateArgument &Arg = Args[ArgIdx];
1023 if (Arg.getKind() != TemplateArgument::Pack)
1024 return true;
1025
1026 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1027 Args = Arg.pack_begin();
1028 NumArgs = Arg.pack_size();
1029 ArgIdx = 0;
1030 return ArgIdx < NumArgs;
1031}
1032
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001033/// \brief Retrieve the depth and index of an unexpanded parameter pack.
1034static std::pair<unsigned, unsigned>
1035getDepthAndIndex(UnexpandedParameterPack UPP) {
1036 if (const TemplateTypeParmType *TTP
1037 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
1038 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1039
1040 if (TemplateTypeParmDecl *TTP = UPP.first.dyn_cast<TemplateTypeParmDecl *>())
1041 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1042
1043 if (NonTypeTemplateParmDecl *NTTP
1044 = UPP.first.dyn_cast<NonTypeTemplateParmDecl *>())
1045 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
1046
1047 TemplateTemplateParmDecl *TTP = UPP.first.get<TemplateTemplateParmDecl *>();
1048 return std::make_pair(TTP->getDepth(), TTP->getIndex());
1049}
1050
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001051/// \brief Helper function to build a TemplateParameter when we don't
1052/// know its type statically.
1053static TemplateParameter makeTemplateParameter(Decl *D) {
1054 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
1055 return TemplateParameter(TTP);
1056 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
1057 return TemplateParameter(NTTP);
1058
1059 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
1060}
1061
Douglas Gregord0ad2942010-12-23 01:24:45 +00001062/// \brief Determine whether the given set of template arguments has a pack
1063/// expansion that is not the last template argument.
1064static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1065 unsigned NumArgs) {
1066 unsigned ArgIdx = 0;
1067 while (ArgIdx < NumArgs) {
1068 const TemplateArgument &Arg = Args[ArgIdx];
1069
1070 // Unwrap argument packs.
1071 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1072 Args = Arg.pack_begin();
1073 NumArgs = Arg.pack_size();
1074 ArgIdx = 0;
1075 continue;
1076 }
1077
1078 ++ArgIdx;
1079 if (ArgIdx == NumArgs)
1080 return false;
1081
1082 if (Arg.isPackExpansion())
1083 return true;
1084 }
1085
1086 return false;
1087}
1088
Douglas Gregor7baabef2010-12-22 18:17:10 +00001089static Sema::TemplateDeductionResult
1090DeduceTemplateArguments(Sema &S,
1091 TemplateParameterList *TemplateParams,
1092 const TemplateArgument *Params, unsigned NumParams,
1093 const TemplateArgument *Args, unsigned NumArgs,
1094 TemplateDeductionInfo &Info,
Douglas Gregord80ea202010-12-22 18:55:49 +00001095 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1096 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001097 // C++0x [temp.deduct.type]p9:
1098 // If the template argument list of P contains a pack expansion that is not
1099 // the last template argument, the entire template argument list is a
1100 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001101 if (hasPackExpansionBeforeEnd(Params, NumParams))
1102 return Sema::TDK_Success;
1103
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001104 // C++0x [temp.deduct.type]p9:
1105 // If P has a form that contains <T> or <i>, then each argument Pi of the
1106 // respective template argument list P is compared with the corresponding
1107 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001108 unsigned ArgIdx = 0, ParamIdx = 0;
1109 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1110 ++ParamIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001111 // FIXME: Variadic templates.
1112 // What do we do if the argument is a pack expansion?
1113
Douglas Gregor7baabef2010-12-22 18:17:10 +00001114 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001115 // The simple case: deduce template arguments by matching Pi and Ai.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001116
1117 // Check whether we have enough arguments.
1118 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregord80ea202010-12-22 18:55:49 +00001119 return NumberOfArgumentsMustMatch? Sema::TDK_TooFewArguments
1120 : Sema::TDK_Success;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001121
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001122 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001123 if (Sema::TemplateDeductionResult Result
1124 = DeduceTemplateArguments(S, TemplateParams,
1125 Params[ParamIdx], Args[ArgIdx],
1126 Info, Deduced))
1127 return Result;
1128
1129 // Move to the next argument.
1130 ++ArgIdx;
1131 continue;
1132 }
1133
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001134 // The parameter is a pack expansion.
1135
1136 // C++0x [temp.deduct.type]p9:
1137 // If Pi is a pack expansion, then the pattern of Pi is compared with
1138 // each remaining argument in the template argument list of A. Each
1139 // comparison deduces template arguments for subsequent positions in the
1140 // template parameter packs expanded by Pi.
1141 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1142
1143 // Compute the set of template parameter indices that correspond to
1144 // parameter packs expanded by the pack expansion.
1145 llvm::SmallVector<unsigned, 2> PackIndices;
1146 {
1147 llvm::BitVector SawIndices(TemplateParams->size());
1148 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1149 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1150 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1151 unsigned Depth, Index;
1152 llvm::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
1153 if (Depth == 0 && !SawIndices[Index]) {
1154 SawIndices[Index] = true;
1155 PackIndices.push_back(Index);
1156 }
1157 }
1158 }
1159 assert(!PackIndices.empty() && "Pack expansion without unexpanded packs?");
1160
1161 // FIXME: If there are no remaining arguments, we can bail out early
1162 // and set any deduced parameter packs to an empty argument pack.
1163 // The latter part of this is a (minor) correctness issue.
1164
1165 // Save the deduced template arguments for each parameter pack expanded
1166 // by this pack expansion, then clear out the deduction.
1167 llvm::SmallVector<DeducedTemplateArgument, 2>
1168 SavedPacks(PackIndices.size());
1169 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1170 SavedPacks[I] = Deduced[PackIndices[I]];
1171 Deduced[PackIndices[I]] = DeducedTemplateArgument();
1172 }
1173
1174 // Keep track of the deduced template arguments for each parameter pack
1175 // expanded by this pack expansion (the outer index) and for each
1176 // template argument (the inner SmallVectors).
1177 llvm::SmallVector<llvm::SmallVector<DeducedTemplateArgument, 4>, 2>
1178 NewlyDeducedPacks(PackIndices.size());
1179 bool HasAnyArguments = false;
1180 while (hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs)) {
1181 HasAnyArguments = true;
1182
1183 // Deduce template arguments from the pattern.
1184 if (Sema::TemplateDeductionResult Result
1185 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1186 Info, Deduced))
1187 return Result;
1188
1189 // Capture the deduced template arguments for each parameter pack expanded
1190 // by this pack expansion, add them to the list of arguments we've deduced
1191 // for that pack, then clear out the deduced argument.
1192 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1193 DeducedTemplateArgument &DeducedArg = Deduced[PackIndices[I]];
1194 if (!DeducedArg.isNull()) {
1195 NewlyDeducedPacks[I].push_back(DeducedArg);
1196 DeducedArg = DeducedTemplateArgument();
1197 }
1198 }
1199
1200 ++ArgIdx;
1201 }
1202
1203 // Build argument packs for each of the parameter packs expanded by this
1204 // pack expansion.
1205 for (unsigned I = 0, N = PackIndices.size(); I != N; ++I) {
1206 if (HasAnyArguments && NewlyDeducedPacks[I].empty()) {
1207 // We were not able to deduce anything for this parameter pack,
1208 // so just restore the saved argument pack.
1209 Deduced[PackIndices[I]] = SavedPacks[I];
1210 continue;
1211 }
1212
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001213 DeducedTemplateArgument NewPack;
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001214
1215 if (NewlyDeducedPacks[I].empty()) {
1216 // If we deduced an empty argument pack, create it now.
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001217 NewPack = DeducedTemplateArgument(TemplateArgument(0, 0));
1218 } else {
1219 TemplateArgument *ArgumentPack
1220 = new (S.Context) TemplateArgument [NewlyDeducedPacks[I].size()];
1221 std::copy(NewlyDeducedPacks[I].begin(), NewlyDeducedPacks[I].end(),
1222 ArgumentPack);
1223 NewPack
1224 = DeducedTemplateArgument(TemplateArgument(ArgumentPack,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001225 NewlyDeducedPacks[I].size()),
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001226 NewlyDeducedPacks[I][0].wasDeducedFromArrayBound());
1227 }
1228
1229 DeducedTemplateArgument Result
1230 = checkDeducedTemplateArguments(S.Context, SavedPacks[I], NewPack);
1231 if (Result.isNull()) {
1232 Info.Param
1233 = makeTemplateParameter(TemplateParams->getParam(PackIndices[I]));
1234 Info.FirstArg = SavedPacks[I];
1235 Info.SecondArg = NewPack;
1236 return Sema::TDK_Inconsistent;
1237 }
1238
1239 Deduced[PackIndices[I]] = Result;
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001240 }
Douglas Gregor7baabef2010-12-22 18:17:10 +00001241 }
1242
1243 // If there is an argument remaining, then we had too many arguments.
Douglas Gregord80ea202010-12-22 18:55:49 +00001244 if (NumberOfArgumentsMustMatch &&
1245 hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Douglas Gregor7baabef2010-12-22 18:17:10 +00001246 return Sema::TDK_TooManyArguments;
1247
1248 return Sema::TDK_Success;
1249}
1250
Mike Stump11289f42009-09-09 15:08:12 +00001251static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001252DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001253 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001254 const TemplateArgumentList &ParamList,
1255 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001256 TemplateDeductionInfo &Info,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001257 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001258 return DeduceTemplateArguments(S, TemplateParams,
1259 ParamList.data(), ParamList.size(),
1260 ArgList.data(), ArgList.size(),
1261 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001262}
1263
Douglas Gregor705c9002009-06-26 20:57:09 +00001264/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001265static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001266 const TemplateArgument &X,
1267 const TemplateArgument &Y) {
1268 if (X.getKind() != Y.getKind())
1269 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001270
Douglas Gregor705c9002009-06-26 20:57:09 +00001271 switch (X.getKind()) {
1272 case TemplateArgument::Null:
1273 assert(false && "Comparing NULL template argument");
1274 break;
Mike Stump11289f42009-09-09 15:08:12 +00001275
Douglas Gregor705c9002009-06-26 20:57:09 +00001276 case TemplateArgument::Type:
1277 return Context.getCanonicalType(X.getAsType()) ==
1278 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001279
Douglas Gregor705c9002009-06-26 20:57:09 +00001280 case TemplateArgument::Declaration:
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00001281 return X.getAsDecl()->getCanonicalDecl() ==
1282 Y.getAsDecl()->getCanonicalDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001283
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001284 case TemplateArgument::Template:
1285 return Context.getCanonicalTemplateName(X.getAsTemplate())
1286 .getAsVoidPointer() ==
1287 Context.getCanonicalTemplateName(Y.getAsTemplate())
1288 .getAsVoidPointer();
1289
Douglas Gregor705c9002009-06-26 20:57:09 +00001290 case TemplateArgument::Integral:
1291 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001292
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001293 case TemplateArgument::Expression: {
1294 llvm::FoldingSetNodeID XID, YID;
1295 X.getAsExpr()->Profile(XID, Context, true);
1296 Y.getAsExpr()->Profile(YID, Context, true);
1297 return XID == YID;
1298 }
Mike Stump11289f42009-09-09 15:08:12 +00001299
Douglas Gregor705c9002009-06-26 20:57:09 +00001300 case TemplateArgument::Pack:
1301 if (X.pack_size() != Y.pack_size())
1302 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001303
1304 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1305 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001306 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001307 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001308 if (!isSameTemplateArg(Context, *XP, *YP))
1309 return false;
1310
1311 return true;
1312 }
1313
1314 return false;
1315}
1316
Douglas Gregor684268d2010-04-29 06:21:43 +00001317/// Complete template argument deduction for a class template partial
1318/// specialization.
1319static Sema::TemplateDeductionResult
1320FinishTemplateArgumentDeduction(Sema &S,
1321 ClassTemplatePartialSpecializationDecl *Partial,
1322 const TemplateArgumentList &TemplateArgs,
1323 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00001324 TemplateDeductionInfo &Info) {
Douglas Gregor684268d2010-04-29 06:21:43 +00001325 // Trap errors.
1326 Sema::SFINAETrap Trap(S);
1327
1328 Sema::ContextRAII SavedContext(S, Partial);
1329
1330 // C++ [temp.deduct.type]p2:
1331 // [...] or if any template argument remains neither deduced nor
1332 // explicitly specified, template argument deduction fails.
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001333 // FIXME: Variadic templates Empty parameter packs?
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001334 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor684268d2010-04-29 06:21:43 +00001335 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1336 if (Deduced[I].isNull()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001337 unsigned ParamIdx = I;
1338 if (ParamIdx >= Partial->getTemplateParameters()->size())
1339 ParamIdx = Partial->getTemplateParameters()->size() - 1;
Douglas Gregor684268d2010-04-29 06:21:43 +00001340 Decl *Param
Douglas Gregor6e9cf632010-10-12 18:51:08 +00001341 = const_cast<NamedDecl *>(
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001342 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor684268d2010-04-29 06:21:43 +00001343 Info.Param = makeTemplateParameter(Param);
1344 return Sema::TDK_Incomplete;
1345 }
1346
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001347 Builder.push_back(Deduced[I]);
Douglas Gregor684268d2010-04-29 06:21:43 +00001348 }
1349
1350 // Form the template argument list from the deduced template arguments.
1351 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001352 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1353 Builder.size());
1354
Douglas Gregor684268d2010-04-29 06:21:43 +00001355 Info.reset(DeducedArgumentList);
1356
1357 // Substitute the deduced template arguments into the template
1358 // arguments of the class template partial specialization, and
1359 // verify that the instantiated template arguments are both valid
1360 // and are equivalent to the template arguments originally provided
1361 // to the class template.
1362 // FIXME: Do we have to correct the types of deduced non-type template
1363 // arguments (in particular, integral non-type template arguments?).
John McCall19c1bfd2010-08-25 05:32:35 +00001364 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00001365 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1366 const TemplateArgumentLoc *PartialTemplateArgs
1367 = Partial->getTemplateArgsAsWritten();
Douglas Gregor684268d2010-04-29 06:21:43 +00001368
1369 // Note that we don't provide the langle and rangle locations.
1370 TemplateArgumentListInfo InstArgs;
1371
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001372 if (S.Subst(PartialTemplateArgs,
1373 Partial->getNumTemplateArgsAsWritten(),
1374 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1375 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
1376 if (ParamIdx >= Partial->getTemplateParameters()->size())
1377 ParamIdx = Partial->getTemplateParameters()->size() - 1;
1378
1379 Decl *Param
1380 = const_cast<NamedDecl *>(
1381 Partial->getTemplateParameters()->getParam(ParamIdx));
1382 Info.Param = makeTemplateParameter(Param);
1383 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
1384 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00001385 }
1386
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001387 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00001388 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregord09efd42010-05-08 20:07:26 +00001389 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00001390 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00001391
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001392 for (unsigned I = 0, E = ConvertedInstArgs.size(); I != E; ++I) {
1393 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00001394
1395 Decl *Param = const_cast<NamedDecl *>(
1396 ClassTemplate->getTemplateParameters()->getParam(I));
1397
1398 if (InstArg.getKind() == TemplateArgument::Expression) {
1399 // When the argument is an expression, check the expression result
1400 // against the actual template parameter to get down to the canonical
1401 // template argument.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001402 // FIXME: Variadic templates.
Douglas Gregor684268d2010-04-29 06:21:43 +00001403 Expr *InstExpr = InstArg.getAsExpr();
1404 if (NonTypeTemplateParmDecl *NTTP
1405 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1406 if (S.CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
1407 Info.Param = makeTemplateParameter(Param);
1408 Info.FirstArg = Partial->getTemplateArgs()[I];
1409 return Sema::TDK_SubstitutionFailure;
1410 }
1411 }
1412 }
1413
1414 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
1415 Info.Param = makeTemplateParameter(Param);
1416 Info.FirstArg = TemplateArgs[I];
1417 Info.SecondArg = InstArg;
1418 return Sema::TDK_NonDeducedMismatch;
1419 }
1420 }
1421
1422 if (Trap.hasErrorOccurred())
1423 return Sema::TDK_SubstitutionFailure;
1424
1425 return Sema::TDK_Success;
1426}
1427
Douglas Gregor170bc422009-06-12 22:31:52 +00001428/// \brief Perform template argument deduction to determine whether
1429/// the given template arguments match the given class template
1430/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001431Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001432Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001433 const TemplateArgumentList &TemplateArgs,
1434 TemplateDeductionInfo &Info) {
Douglas Gregor170bc422009-06-12 22:31:52 +00001435 // C++ [temp.class.spec.match]p2:
1436 // A partial specialization matches a given actual template
1437 // argument list if the template arguments of the partial
1438 // specialization can be deduced from the actual template argument
1439 // list (14.8.2).
Douglas Gregore1416332009-06-14 08:02:22 +00001440 SFINAETrap Trap(*this);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001441 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001442 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001443 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001444 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001445 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00001446 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001447 TemplateArgs, Info, Deduced))
1448 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00001449
Douglas Gregor637d9982009-06-10 23:47:09 +00001450 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001451 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637d9982009-06-10 23:47:09 +00001452 if (Inst)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001453 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001454
Douglas Gregore1416332009-06-14 08:02:22 +00001455 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00001456 return Sema::TDK_SubstitutionFailure;
1457
1458 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1459 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001460}
Douglas Gregor91772d12009-06-13 00:26:55 +00001461
Douglas Gregorfc516c92009-06-26 23:27:24 +00001462/// \brief Determine whether the given type T is a simple-template-id type.
1463static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00001464 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00001465 = T->getAs<TemplateSpecializationType>())
Douglas Gregorfc516c92009-06-26 23:27:24 +00001466 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump11289f42009-09-09 15:08:12 +00001467
Douglas Gregorfc516c92009-06-26 23:27:24 +00001468 return false;
1469}
Douglas Gregor9b146582009-07-08 20:55:45 +00001470
1471/// \brief Substitute the explicitly-provided template arguments into the
1472/// given function template according to C++ [temp.arg.explicit].
1473///
1474/// \param FunctionTemplate the function template into which the explicit
1475/// template arguments will be substituted.
1476///
Mike Stump11289f42009-09-09 15:08:12 +00001477/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00001478/// arguments.
1479///
Mike Stump11289f42009-09-09 15:08:12 +00001480/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00001481/// with the converted and checked explicit template arguments.
1482///
Mike Stump11289f42009-09-09 15:08:12 +00001483/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00001484/// parameters.
1485///
1486/// \param FunctionType if non-NULL, the result type of the function template
1487/// will also be instantiated and the pointed-to value will be updated with
1488/// the instantiated function type.
1489///
1490/// \param Info if substitution fails for any reason, this object will be
1491/// populated with more information about the failure.
1492///
1493/// \returns TDK_Success if substitution was successful, or some failure
1494/// condition.
1495Sema::TemplateDeductionResult
1496Sema::SubstituteExplicitTemplateArguments(
1497 FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00001498 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001499 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor9b146582009-07-08 20:55:45 +00001500 llvm::SmallVectorImpl<QualType> &ParamTypes,
1501 QualType *FunctionType,
1502 TemplateDeductionInfo &Info) {
1503 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1504 TemplateParameterList *TemplateParams
1505 = FunctionTemplate->getTemplateParameters();
1506
John McCall6b51f282009-11-23 01:53:49 +00001507 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00001508 // No arguments to substitute; just copy over the parameter types and
1509 // fill in the function type.
1510 for (FunctionDecl::param_iterator P = Function->param_begin(),
1511 PEnd = Function->param_end();
1512 P != PEnd;
1513 ++P)
1514 ParamTypes.push_back((*P)->getType());
Mike Stump11289f42009-09-09 15:08:12 +00001515
Douglas Gregor9b146582009-07-08 20:55:45 +00001516 if (FunctionType)
1517 *FunctionType = Function->getType();
1518 return TDK_Success;
1519 }
Mike Stump11289f42009-09-09 15:08:12 +00001520
Douglas Gregor9b146582009-07-08 20:55:45 +00001521 // Substitution of the explicit template arguments into a function template
1522 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump11289f42009-09-09 15:08:12 +00001523 SFINAETrap Trap(*this);
1524
Douglas Gregor9b146582009-07-08 20:55:45 +00001525 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001526 // Template arguments that are present shall be specified in the
1527 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00001528 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00001529 // there are corresponding template-parameters.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001530 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00001531
1532 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00001533 // explicitly-specified template arguments against this function template,
1534 // and then substitute them into the function parameter types.
Mike Stump11289f42009-09-09 15:08:12 +00001535 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor9b146582009-07-08 20:55:45 +00001536 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001537 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1538 Info);
Douglas Gregor9b146582009-07-08 20:55:45 +00001539 if (Inst)
1540 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00001541
Douglas Gregor9b146582009-07-08 20:55:45 +00001542 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00001543 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00001544 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00001545 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00001546 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001547 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00001548 if (Index >= TemplateParams->size())
1549 Index = TemplateParams->size() - 1;
1550 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00001551 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00001552 }
Mike Stump11289f42009-09-09 15:08:12 +00001553
Douglas Gregor9b146582009-07-08 20:55:45 +00001554 // Form the template argument list from the explicitly-specified
1555 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00001556 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001557 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00001558 Info.reset(ExplicitArgumentList);
Mike Stump11289f42009-09-09 15:08:12 +00001559
John McCall036855a2010-10-12 19:40:14 +00001560 // Template argument deduction and the final substitution should be
1561 // done in the context of the templated declaration. Explicit
1562 // argument substitution, on the other hand, needs to happen in the
1563 // calling context.
1564 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1565
Douglas Gregor9b146582009-07-08 20:55:45 +00001566 // Instantiate the types of each of the function parameters given the
1567 // explicitly-specified template arguments.
1568 for (FunctionDecl::param_iterator P = Function->param_begin(),
1569 PEnd = Function->param_end();
1570 P != PEnd;
1571 ++P) {
Mike Stump11289f42009-09-09 15:08:12 +00001572 QualType ParamType
1573 = SubstType((*P)->getType(),
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001574 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1575 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor9b146582009-07-08 20:55:45 +00001576 if (ParamType.isNull() || Trap.hasErrorOccurred())
1577 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00001578
Douglas Gregor9b146582009-07-08 20:55:45 +00001579 ParamTypes.push_back(ParamType);
1580 }
1581
1582 // If the caller wants a full function type back, instantiate the return
1583 // type and form that function type.
1584 if (FunctionType) {
1585 // FIXME: exception-specifications?
Mike Stump11289f42009-09-09 15:08:12 +00001586 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00001587 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor9b146582009-07-08 20:55:45 +00001588 assert(Proto && "Function template does not have a prototype?");
Mike Stump11289f42009-09-09 15:08:12 +00001589
1590 QualType ResultType
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001591 = SubstType(Proto->getResultType(),
1592 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1593 Function->getTypeSpecStartLoc(),
1594 Function->getDeclName());
Douglas Gregor9b146582009-07-08 20:55:45 +00001595 if (ResultType.isNull() || Trap.hasErrorOccurred())
1596 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00001597
1598 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor9b146582009-07-08 20:55:45 +00001599 ParamTypes.data(), ParamTypes.size(),
1600 Proto->isVariadic(),
1601 Proto->getTypeQuals(),
1602 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00001603 Function->getDeclName(),
1604 Proto->getExtInfo());
Douglas Gregor9b146582009-07-08 20:55:45 +00001605 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1606 return TDK_SubstitutionFailure;
1607 }
Mike Stump11289f42009-09-09 15:08:12 +00001608
Douglas Gregor9b146582009-07-08 20:55:45 +00001609 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00001610 // Trailing template arguments that can be deduced (14.8.2) may be
1611 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00001612 // template arguments can be deduced, they may all be omitted; in this
1613 // case, the empty template argument list <> itself may also be omitted.
1614 //
1615 // Take all of the explicitly-specified arguments and put them into the
Mike Stump11289f42009-09-09 15:08:12 +00001616 // set of deduced template arguments.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001617 //
1618 // FIXME: Variadic templates?
Douglas Gregor9b146582009-07-08 20:55:45 +00001619 Deduced.reserve(TemplateParams->size());
1620 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump11289f42009-09-09 15:08:12 +00001621 Deduced.push_back(ExplicitArgumentList->get(I));
1622
Douglas Gregor9b146582009-07-08 20:55:45 +00001623 return TDK_Success;
1624}
1625
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001626/// \brief Allocate a TemplateArgumentLoc where all locations have
1627/// been initialized to the given location.
1628///
1629/// \param S The semantic analysis object.
1630///
1631/// \param The template argument we are producing template argument
1632/// location information for.
1633///
1634/// \param NTTPType For a declaration template argument, the type of
1635/// the non-type template parameter that corresponds to this template
1636/// argument.
1637///
1638/// \param Loc The source location to use for the resulting template
1639/// argument.
1640static TemplateArgumentLoc
1641getTrivialTemplateArgumentLoc(Sema &S,
1642 const TemplateArgument &Arg,
1643 QualType NTTPType,
1644 SourceLocation Loc) {
1645 switch (Arg.getKind()) {
1646 case TemplateArgument::Null:
1647 llvm_unreachable("Can't get a NULL template argument here");
1648 break;
1649
1650 case TemplateArgument::Type:
1651 return TemplateArgumentLoc(Arg,
1652 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1653
1654 case TemplateArgument::Declaration: {
1655 Expr *E
1656 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1657 .takeAs<Expr>();
1658 return TemplateArgumentLoc(TemplateArgument(E), E);
1659 }
1660
1661 case TemplateArgument::Integral: {
1662 Expr *E
1663 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
1664 return TemplateArgumentLoc(TemplateArgument(E), E);
1665 }
1666
1667 case TemplateArgument::Template:
1668 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1669
1670 case TemplateArgument::Expression:
1671 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1672
1673 case TemplateArgument::Pack:
Douglas Gregor0192c232010-12-20 16:52:59 +00001674 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001675 }
1676
1677 return TemplateArgumentLoc();
1678}
1679
Mike Stump11289f42009-09-09 15:08:12 +00001680/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00001681/// checking the deduced template arguments for completeness and forming
1682/// the function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00001683Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00001684Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001685 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1686 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00001687 FunctionDecl *&Specialization,
1688 TemplateDeductionInfo &Info) {
1689 TemplateParameterList *TemplateParams
1690 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001691
Douglas Gregor9b146582009-07-08 20:55:45 +00001692 // Template argument deduction for function templates in a SFINAE context.
1693 // Trap any errors that might occur.
Mike Stump11289f42009-09-09 15:08:12 +00001694 SFINAETrap Trap(*this);
1695
Douglas Gregor9b146582009-07-08 20:55:45 +00001696 // Enter a new template instantiation context while we instantiate the
1697 // actual function declaration.
Mike Stump11289f42009-09-09 15:08:12 +00001698 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor9b146582009-07-08 20:55:45 +00001699 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001700 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1701 Info);
Douglas Gregor9b146582009-07-08 20:55:45 +00001702 if (Inst)
Mike Stump11289f42009-09-09 15:08:12 +00001703 return TDK_InstantiationDepth;
1704
John McCalle23b8712010-04-29 01:18:58 +00001705 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00001706
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001707 // C++ [temp.deduct.type]p2:
1708 // [...] or if any template argument remains neither deduced nor
1709 // explicitly specified, template argument deduction fails.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001710 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001711 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001712 // FIXME: Variadic templates. Unwrap argument packs?
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001713 NamedDecl *Param = FunctionTemplate->getTemplateParameters()->getParam(I);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001714 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00001715 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001716 // We have already fully type-checked and converted this
Douglas Gregor6e9cf632010-10-12 18:51:08 +00001717 // argument, because it was explicitly-specified. Just record the
1718 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001719 Builder.push_back(Deduced[I]);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001720 continue;
1721 }
1722
1723 // We have deduced this argument, so it still needs to be
1724 // checked and converted.
1725
1726 // First, for a non-type template parameter type that is
1727 // initialized by a declaration, we need the type of the
1728 // corresponding non-type template parameter.
1729 QualType NTTPType;
1730 if (NonTypeTemplateParmDecl *NTTP
1731 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1732 if (Deduced[I].getKind() == TemplateArgument::Declaration) {
1733 NTTPType = NTTP->getType();
1734 if (NTTPType->isDependentType()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001735 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1736 Builder.data(), Builder.size());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001737 NTTPType = SubstType(NTTPType,
1738 MultiLevelTemplateArgumentList(TemplateArgs),
1739 NTTP->getLocation(),
1740 NTTP->getDeclName());
1741 if (NTTPType.isNull()) {
1742 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001743 // FIXME: These template arguments are temporary. Free them!
1744 Info.reset(TemplateArgumentList::CreateCopy(Context,
1745 Builder.data(),
1746 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001747 return TDK_SubstitutionFailure;
1748 }
1749 }
1750 }
1751 }
1752
1753 // Convert the deduced template argument into a template
1754 // argument that we can check, almost as if the user had written
1755 // the template argument explicitly.
1756 TemplateArgumentLoc Arg = getTrivialTemplateArgumentLoc(*this,
1757 Deduced[I],
1758 NTTPType,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001759 Info.getLocation());
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001760
1761 // Check the template argument, converting it as necessary.
1762 if (CheckTemplateArgument(Param, Arg,
1763 FunctionTemplate,
1764 FunctionTemplate->getLocation(),
1765 FunctionTemplate->getSourceRange().getEnd(),
1766 Builder,
1767 Deduced[I].wasDeducedFromArrayBound()
1768 ? CTAK_DeducedFromArrayBound
1769 : CTAK_Deduced)) {
1770 Info.Param = makeTemplateParameter(
1771 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001772 // FIXME: These template arguments are temporary. Free them!
1773 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1774 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001775 return TDK_SubstitutionFailure;
1776 }
1777
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001778 continue;
1779 }
1780
1781 // Substitute into the default template argument, if available.
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001782 TemplateArgumentLoc DefArg
1783 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1784 FunctionTemplate->getLocation(),
1785 FunctionTemplate->getSourceRange().getEnd(),
1786 Param,
1787 Builder);
1788
1789 // If there was no default argument, deduction is incomplete.
1790 if (DefArg.getArgument().isNull()) {
1791 Info.Param = makeTemplateParameter(
1792 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1793 return TDK_Incomplete;
1794 }
1795
1796 // Check whether we can actually use the default argument.
1797 if (CheckTemplateArgument(Param, DefArg,
1798 FunctionTemplate,
1799 FunctionTemplate->getLocation(),
1800 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001801 Builder,
1802 CTAK_Deduced)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001803 Info.Param = makeTemplateParameter(
1804 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001805 // FIXME: These template arguments are temporary. Free them!
1806 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1807 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001808 return TDK_SubstitutionFailure;
1809 }
1810
1811 // If we get here, we successfully used the default template argument.
1812 }
1813
1814 // Form the template argument list from the deduced template arguments.
1815 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001816 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001817 Info.reset(DeducedArgumentList);
1818
Mike Stump11289f42009-09-09 15:08:12 +00001819 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00001820 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00001821 DeclContext *Owner = FunctionTemplate->getDeclContext();
1822 if (FunctionTemplate->getFriendObjectKind())
1823 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00001824 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00001825 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00001826 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor9b146582009-07-08 20:55:45 +00001827 if (!Specialization)
1828 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00001829
Douglas Gregor31fae892009-09-15 18:26:13 +00001830 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1831 FunctionTemplate->getCanonicalDecl());
1832
Mike Stump11289f42009-09-09 15:08:12 +00001833 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00001834 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00001835 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
1836 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00001837 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00001838
Douglas Gregor9b146582009-07-08 20:55:45 +00001839 // There may have been an error that did not prevent us from constructing a
1840 // declaration. Mark the declaration invalid and return with a substitution
1841 // failure.
1842 if (Trap.hasErrorOccurred()) {
1843 Specialization->setInvalidDecl(true);
1844 return TDK_SubstitutionFailure;
1845 }
Mike Stump11289f42009-09-09 15:08:12 +00001846
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00001847 // If we suppressed any diagnostics while performing template argument
1848 // deduction, and if we haven't already instantiated this declaration,
1849 // keep track of these diagnostics. They'll be emitted if this specialization
1850 // is actually used.
1851 if (Info.diag_begin() != Info.diag_end()) {
1852 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
1853 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
1854 if (Pos == SuppressedDiagnostics.end())
1855 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
1856 .append(Info.diag_begin(), Info.diag_end());
1857 }
1858
Mike Stump11289f42009-09-09 15:08:12 +00001859 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00001860}
1861
John McCall8d08b9b2010-08-27 09:08:28 +00001862/// Gets the type of a function for template-argument-deducton
1863/// purposes when it's considered as part of an overload set.
John McCallc1f69982010-02-02 02:21:27 +00001864static QualType GetTypeOfFunction(ASTContext &Context,
John McCall8d08b9b2010-08-27 09:08:28 +00001865 const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00001866 FunctionDecl *Fn) {
John McCallc1f69982010-02-02 02:21:27 +00001867 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00001868 if (Method->isInstance()) {
1869 // An instance method that's referenced in a form that doesn't
1870 // look like a member pointer is just invalid.
1871 if (!R.HasFormOfMemberPointer) return QualType();
1872
John McCallc1f69982010-02-02 02:21:27 +00001873 return Context.getMemberPointerType(Fn->getType(),
1874 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00001875 }
1876
1877 if (!R.IsAddressOfOperand) return Fn->getType();
John McCallc1f69982010-02-02 02:21:27 +00001878 return Context.getPointerType(Fn->getType());
1879}
1880
1881/// Apply the deduction rules for overload sets.
1882///
1883/// \return the null type if this argument should be treated as an
1884/// undeduced context
1885static QualType
1886ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00001887 Expr *Arg, QualType ParamType,
1888 bool ParamWasReference) {
John McCall8d08b9b2010-08-27 09:08:28 +00001889
1890 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00001891
John McCall8d08b9b2010-08-27 09:08:28 +00001892 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00001893
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00001894 // C++0x [temp.deduct.call]p4
1895 unsigned TDF = 0;
1896 if (ParamWasReference)
1897 TDF |= TDF_ParamWithReferenceType;
1898 if (R.IsAddressOfOperand)
1899 TDF |= TDF_IgnoreQualifiers;
1900
John McCallc1f69982010-02-02 02:21:27 +00001901 // If there were explicit template arguments, we can only find
1902 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1903 // unambiguously name a full specialization.
John McCall1acbbb52010-02-02 06:20:04 +00001904 if (Ovl->hasExplicitTemplateArgs()) {
John McCallc1f69982010-02-02 02:21:27 +00001905 // But we can still look for an explicit specialization.
1906 if (FunctionDecl *ExplicitSpec
John McCall1acbbb52010-02-02 06:20:04 +00001907 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall8d08b9b2010-08-27 09:08:28 +00001908 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCallc1f69982010-02-02 02:21:27 +00001909 return QualType();
1910 }
1911
1912 // C++0x [temp.deduct.call]p6:
1913 // When P is a function type, pointer to function type, or pointer
1914 // to member function type:
1915
1916 if (!ParamType->isFunctionType() &&
1917 !ParamType->isFunctionPointerType() &&
1918 !ParamType->isMemberFunctionPointerType())
1919 return QualType();
1920
1921 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00001922 for (UnresolvedSetIterator I = Ovl->decls_begin(),
1923 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00001924 NamedDecl *D = (*I)->getUnderlyingDecl();
1925
1926 // - If the argument is an overload set containing one or more
1927 // function templates, the parameter is treated as a
1928 // non-deduced context.
1929 if (isa<FunctionTemplateDecl>(D))
1930 return QualType();
1931
1932 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall8d08b9b2010-08-27 09:08:28 +00001933 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
1934 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00001935
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00001936 // Function-to-pointer conversion.
1937 if (!ParamWasReference && ParamType->isPointerType() &&
1938 ArgType->isFunctionType())
1939 ArgType = S.Context.getPointerType(ArgType);
1940
John McCallc1f69982010-02-02 02:21:27 +00001941 // - If the argument is an overload set (not containing function
1942 // templates), trial argument deduction is attempted using each
1943 // of the members of the set. If deduction succeeds for only one
1944 // of the overload set members, that member is used as the
1945 // argument value for the deduction. If deduction succeeds for
1946 // more than one member of the overload set the parameter is
1947 // treated as a non-deduced context.
1948
1949 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
1950 // Type deduction is done independently for each P/A pair, and
1951 // the deduced template argument values are then combined.
1952 // So we do not reject deductions which were made elsewhere.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001953 llvm::SmallVector<DeducedTemplateArgument, 8>
1954 Deduced(TemplateParams->size());
John McCall19c1bfd2010-08-25 05:32:35 +00001955 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00001956 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001957 = DeduceTemplateArguments(S, TemplateParams,
John McCallc1f69982010-02-02 02:21:27 +00001958 ParamType, ArgType,
1959 Info, Deduced, TDF);
1960 if (Result) continue;
1961 if (!Match.isNull()) return QualType();
1962 Match = ArgType;
1963 }
1964
1965 return Match;
1966}
1967
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001968/// \brief Perform template argument deduction from a function call
1969/// (C++ [temp.deduct.call]).
1970///
1971/// \param FunctionTemplate the function template for which we are performing
1972/// template argument deduction.
1973///
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001974/// \param ExplicitTemplateArguments the explicit template arguments provided
1975/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00001976///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001977/// \param Args the function call arguments
1978///
1979/// \param NumArgs the number of arguments in Args
1980///
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001981/// \param Name the name of the function being called. This is only significant
1982/// when the function template is a conversion function template, in which
1983/// case this routine will also perform template argument deduction based on
1984/// the function to which
1985///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001986/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00001987/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001988/// template argument deduction.
1989///
1990/// \param Info the argument will be updated to provide additional information
1991/// about template argument deduction.
1992///
1993/// \returns the result of template argument deduction.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001994Sema::TemplateDeductionResult
1995Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001996 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001997 Expr **Args, unsigned NumArgs,
1998 FunctionDecl *&Specialization,
1999 TemplateDeductionInfo &Info) {
2000 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor89026b52009-06-30 23:57:56 +00002001
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002002 // C++ [temp.deduct.call]p1:
2003 // Template argument deduction is done by comparing each function template
2004 // parameter type (call it P) with the type of the corresponding argument
2005 // of the call (call it A) as described below.
2006 unsigned CheckArgs = NumArgs;
Douglas Gregor89026b52009-06-30 23:57:56 +00002007 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002008 return TDK_TooFewArguments;
2009 else if (NumArgs > Function->getNumParams()) {
Mike Stump11289f42009-09-09 15:08:12 +00002010 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00002011 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002012 if (!Proto->isVariadic())
2013 return TDK_TooManyArguments;
Mike Stump11289f42009-09-09 15:08:12 +00002014
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002015 CheckArgs = Function->getNumParams();
2016 }
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor89026b52009-06-30 23:57:56 +00002018 // The types of the parameters from which we will perform template argument
2019 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00002020 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002021 TemplateParameterList *TemplateParams
2022 = FunctionTemplate->getTemplateParameters();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002023 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor89026b52009-06-30 23:57:56 +00002024 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002025 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00002026 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002027 TemplateDeductionResult Result =
2028 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002029 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002030 Deduced,
2031 ParamTypes,
2032 0,
2033 Info);
2034 if (Result)
2035 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002036
2037 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00002038 } else {
2039 // Just fill in the parameter types from the function declaration.
2040 for (unsigned I = 0; I != CheckArgs; ++I)
2041 ParamTypes.push_back(Function->getParamDecl(I)->getType());
2042 }
Mike Stump11289f42009-09-09 15:08:12 +00002043
Douglas Gregor89026b52009-06-30 23:57:56 +00002044 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00002045 Deduced.resize(TemplateParams->size());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002046 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor89026b52009-06-30 23:57:56 +00002047 QualType ParamType = ParamTypes[I];
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002048 QualType ArgType = Args[I]->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002049
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002050 // C++0x [temp.deduct.call]p3:
2051 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
2052 // are ignored for type deduction.
2053 if (ParamType.getCVRQualifiers())
2054 ParamType = ParamType.getLocalUnqualifiedType();
2055 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
2056 if (ParamRefType) {
2057 // [...] If P is a reference type, the type referred to by P is used
2058 // for type deduction.
2059 ParamType = ParamRefType->getPointeeType();
2060 }
2061
John McCallc1f69982010-02-02 02:21:27 +00002062 // Overload sets usually make this parameter an undeduced
2063 // context, but there are sometimes special circumstances.
2064 if (ArgType == Context.OverloadTy) {
2065 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002066 Args[I], ParamType,
2067 ParamRefType != 0);
John McCallc1f69982010-02-02 02:21:27 +00002068 if (ArgType.isNull())
2069 continue;
2070 }
2071
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002072 if (ParamRefType) {
2073 // C++0x [temp.deduct.call]p3:
2074 // [...] If P is of the form T&&, where T is a template parameter, and
2075 // the argument is an lvalue, the type A& is used in place of A for
2076 // type deduction.
2077 if (ParamRefType->isRValueReferenceType() &&
2078 ParamRefType->getAs<TemplateTypeParmType>() &&
John McCall086a4642010-11-24 05:12:34 +00002079 Args[I]->isLValue())
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002080 ArgType = Context.getLValueReferenceType(ArgType);
2081 } else {
2082 // C++ [temp.deduct.call]p2:
2083 // If P is not a reference type:
Mike Stump11289f42009-09-09 15:08:12 +00002084 // - If A is an array type, the pointer type produced by the
2085 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002086 // A for type deduction; otherwise,
2087 if (ArgType->isArrayType())
2088 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump11289f42009-09-09 15:08:12 +00002089 // - If A is a function type, the pointer type produced by the
2090 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002091 // of A for type deduction; otherwise,
2092 else if (ArgType->isFunctionType())
2093 ArgType = Context.getPointerType(ArgType);
2094 else {
2095 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
2096 // type are ignored for type deduction.
2097 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002098 if (ArgType.getCVRQualifiers())
2099 ArgType = ArgType.getUnqualifiedType();
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002100 }
2101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002103 // C++0x [temp.deduct.call]p4:
2104 // In general, the deduction process attempts to find template argument
2105 // values that will make the deduced A identical to A (after the type A
2106 // is transformed as described above). [...]
Douglas Gregor406f6342009-09-14 20:00:47 +00002107 unsigned TDF = TDF_SkipNonDependent;
Mike Stump11289f42009-09-09 15:08:12 +00002108
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00002109 // - If the original P is a reference type, the deduced A (i.e., the
2110 // type referred to by the reference) can be more cv-qualified than
2111 // the transformed A.
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002112 if (ParamRefType)
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00002113 TDF |= TDF_ParamWithReferenceType;
Mike Stump11289f42009-09-09 15:08:12 +00002114 // - The transformed A can be another pointer or pointer to member
2115 // type that can be converted to the deduced A via a qualification
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00002116 // conversion (4.4).
John McCallda518412010-08-05 05:30:45 +00002117 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
2118 ArgType->isObjCObjectPointerType())
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00002119 TDF |= TDF_IgnoreQualifiers;
Mike Stump11289f42009-09-09 15:08:12 +00002120 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregorfc516c92009-06-26 23:27:24 +00002121 // transformed A can be a derived class of the deduced A. Likewise,
2122 // if P is a pointer to a class of the form simple-template-id, the
2123 // transformed A can be a pointer to a derived class pointed to by
2124 // the deduced A.
2125 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump11289f42009-09-09 15:08:12 +00002126 (isa<PointerType>(ParamType) &&
Douglas Gregorfc516c92009-06-26 23:27:24 +00002127 isSimpleTemplateIdType(
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002128 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregorfc516c92009-06-26 23:27:24 +00002129 TDF |= TDF_DerivedClass;
Mike Stump11289f42009-09-09 15:08:12 +00002130
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002131 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002132 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregorcceb9752009-06-26 18:27:22 +00002133 ParamType, ArgType, Info, Deduced,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00002134 TDF))
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002135 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00002136
Douglas Gregor05155d82009-08-21 23:19:43 +00002137 // FIXME: we need to check that the deduced A is the same as A,
2138 // modulo the various allowed differences.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002139 }
Douglas Gregor05155d82009-08-21 23:19:43 +00002140
Mike Stump11289f42009-09-09 15:08:12 +00002141 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002142 NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002143 Specialization, Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002144}
2145
Douglas Gregor9b146582009-07-08 20:55:45 +00002146/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002147/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
2148/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00002149///
2150/// \param FunctionTemplate the function template for which we are performing
2151/// template argument deduction.
2152///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002153/// \param ExplicitTemplateArguments the explicitly-specified template
2154/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00002155///
2156/// \param ArgFunctionType the function type that will be used as the
2157/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002158/// function template's function type. This type may be NULL, if there is no
2159/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00002160///
2161/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00002162/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00002163/// template argument deduction.
2164///
2165/// \param Info the argument will be updated to provide additional information
2166/// about template argument deduction.
2167///
2168/// \returns the result of template argument deduction.
2169Sema::TemplateDeductionResult
2170Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002171 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002172 QualType ArgFunctionType,
2173 FunctionDecl *&Specialization,
2174 TemplateDeductionInfo &Info) {
2175 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2176 TemplateParameterList *TemplateParams
2177 = FunctionTemplate->getTemplateParameters();
2178 QualType FunctionType = Function->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002179
Douglas Gregor9b146582009-07-08 20:55:45 +00002180 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00002181 LocalInstantiationScope InstScope(*this);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002182 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
2183 unsigned NumExplicitlySpecified = 0;
Douglas Gregor9b146582009-07-08 20:55:45 +00002184 llvm::SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00002185 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00002186 if (TemplateDeductionResult Result
2187 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00002188 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00002189 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002190 &FunctionType, Info))
2191 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002192
2193 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00002194 }
2195
2196 // Template argument deduction for function templates in a SFINAE context.
2197 // Trap any errors that might occur.
Mike Stump11289f42009-09-09 15:08:12 +00002198 SFINAETrap Trap(*this);
2199
John McCallc1f69982010-02-02 02:21:27 +00002200 Deduced.resize(TemplateParams->size());
2201
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002202 if (!ArgFunctionType.isNull()) {
2203 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002204 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002205 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002206 FunctionType, ArgFunctionType, Info,
2207 Deduced, 0))
2208 return Result;
2209 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00002210
2211 if (TemplateDeductionResult Result
2212 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
2213 NumExplicitlySpecified,
2214 Specialization, Info))
2215 return Result;
2216
2217 // If the requested function type does not match the actual type of the
2218 // specialization, template argument deduction fails.
2219 if (!ArgFunctionType.isNull() &&
2220 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
2221 return TDK_NonDeducedMismatch;
2222
2223 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002224}
2225
Douglas Gregor05155d82009-08-21 23:19:43 +00002226/// \brief Deduce template arguments for a templated conversion
2227/// function (C++ [temp.deduct.conv]) and, if successful, produce a
2228/// conversion function template specialization.
2229Sema::TemplateDeductionResult
2230Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2231 QualType ToType,
2232 CXXConversionDecl *&Specialization,
2233 TemplateDeductionInfo &Info) {
Mike Stump11289f42009-09-09 15:08:12 +00002234 CXXConversionDecl *Conv
Douglas Gregor05155d82009-08-21 23:19:43 +00002235 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
2236 QualType FromType = Conv->getConversionType();
2237
2238 // Canonicalize the types for deduction.
2239 QualType P = Context.getCanonicalType(FromType);
2240 QualType A = Context.getCanonicalType(ToType);
2241
2242 // C++0x [temp.deduct.conv]p3:
2243 // If P is a reference type, the type referred to by P is used for
2244 // type deduction.
2245 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
2246 P = PRef->getPointeeType();
2247
2248 // C++0x [temp.deduct.conv]p3:
2249 // If A is a reference type, the type referred to by A is used
2250 // for type deduction.
2251 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2252 A = ARef->getPointeeType();
2253 // C++ [temp.deduct.conv]p2:
2254 //
Mike Stump11289f42009-09-09 15:08:12 +00002255 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00002256 else {
2257 assert(!A->isReferenceType() && "Reference types were handled above");
2258
2259 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00002260 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00002261 // of P for type deduction; otherwise,
2262 if (P->isArrayType())
2263 P = Context.getArrayDecayedType(P);
2264 // - If P is a function type, the pointer type produced by the
2265 // function-to-pointer standard conversion (4.3) is used in
2266 // place of P for type deduction; otherwise,
2267 else if (P->isFunctionType())
2268 P = Context.getPointerType(P);
2269 // - If P is a cv-qualified type, the top level cv-qualifiers of
2270 // P’s type are ignored for type deduction.
2271 else
2272 P = P.getUnqualifiedType();
2273
2274 // C++0x [temp.deduct.conv]p3:
2275 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
2276 // type are ignored for type deduction.
2277 A = A.getUnqualifiedType();
2278 }
2279
2280 // Template argument deduction for function templates in a SFINAE context.
2281 // Trap any errors that might occur.
Mike Stump11289f42009-09-09 15:08:12 +00002282 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00002283
2284 // C++ [temp.deduct.conv]p1:
2285 // Template argument deduction is done by comparing the return
2286 // type of the template conversion function (call it P) with the
2287 // type that is required as the result of the conversion (call it
2288 // A) as described in 14.8.2.4.
2289 TemplateParameterList *TemplateParams
2290 = FunctionTemplate->getTemplateParameters();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002291 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00002292 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00002293
2294 // C++0x [temp.deduct.conv]p4:
2295 // In general, the deduction process attempts to find template
2296 // argument values that will make the deduced A identical to
2297 // A. However, there are two cases that allow a difference:
2298 unsigned TDF = 0;
2299 // - If the original A is a reference type, A can be more
2300 // cv-qualified than the deduced A (i.e., the type referred to
2301 // by the reference)
2302 if (ToType->isReferenceType())
2303 TDF |= TDF_ParamWithReferenceType;
2304 // - The deduced A can be another pointer or pointer to member
2305 // type that can be converted to A via a qualification
2306 // conversion.
2307 //
2308 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
2309 // both P and A are pointers or member pointers. In this case, we
2310 // just ignore cv-qualifiers completely).
2311 if ((P->isPointerType() && A->isPointerType()) ||
2312 (P->isMemberPointerType() && P->isMemberPointerType()))
2313 TDF |= TDF_IgnoreQualifiers;
2314 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002315 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor05155d82009-08-21 23:19:43 +00002316 P, A, Info, Deduced, TDF))
2317 return Result;
2318
2319 // FIXME: we need to check that the deduced A is the same as A,
2320 // modulo the various allowed differences.
Mike Stump11289f42009-09-09 15:08:12 +00002321
Douglas Gregor05155d82009-08-21 23:19:43 +00002322 // Finish template argument deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00002323 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00002324 FunctionDecl *Spec = 0;
2325 TemplateDeductionResult Result
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002326 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2327 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00002328 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2329 return Result;
2330}
2331
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002332/// \brief Deduce template arguments for a function template when there is
2333/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2334///
2335/// \param FunctionTemplate the function template for which we are performing
2336/// template argument deduction.
2337///
2338/// \param ExplicitTemplateArguments the explicitly-specified template
2339/// arguments.
2340///
2341/// \param Specialization if template argument deduction was successful,
2342/// this will be set to the function template specialization produced by
2343/// template argument deduction.
2344///
2345/// \param Info the argument will be updated to provide additional information
2346/// about template argument deduction.
2347///
2348/// \returns the result of template argument deduction.
2349Sema::TemplateDeductionResult
2350Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2351 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2352 FunctionDecl *&Specialization,
2353 TemplateDeductionInfo &Info) {
2354 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2355 QualType(), Specialization, Info);
2356}
2357
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002358/// \brief Stores the result of comparing the qualifiers of two types.
2359enum DeductionQualifierComparison {
2360 NeitherMoreQualified = 0,
2361 ParamMoreQualified,
2362 ArgMoreQualified
2363};
2364
2365/// \brief Deduce the template arguments during partial ordering by comparing
2366/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2367///
Chandler Carruthc1263112010-02-07 21:33:28 +00002368/// \param S the semantic analysis object within which we are deducing
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002369///
2370/// \param TemplateParams the template parameters that we are deducing
2371///
2372/// \param ParamIn the parameter type
2373///
2374/// \param ArgIn the argument type
2375///
2376/// \param Info information about the template argument deduction itself
2377///
2378/// \param Deduced the deduced template arguments
2379///
2380/// \returns the result of template argument deduction so far. Note that a
2381/// "success" result means that template argument deduction has not yet failed,
2382/// but it may still fail, later, for other reasons.
2383static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002384DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002385 TemplateParameterList *TemplateParams,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002386 QualType ParamIn, QualType ArgIn,
John McCall19c1bfd2010-08-25 05:32:35 +00002387 TemplateDeductionInfo &Info,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002388 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2389 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carruthc1263112010-02-07 21:33:28 +00002390 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2391 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002392
2393 // C++0x [temp.deduct.partial]p5:
2394 // Before the partial ordering is done, certain transformations are
2395 // performed on the types used for partial ordering:
2396 // - If P is a reference type, P is replaced by the type referred to.
2397 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCall48f2d582009-10-23 23:03:21 +00002398 if (!ParamRef.isNull())
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002399 Param = ParamRef->getPointeeType();
2400
2401 // - If A is a reference type, A is replaced by the type referred to.
2402 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCall48f2d582009-10-23 23:03:21 +00002403 if (!ArgRef.isNull())
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002404 Arg = ArgRef->getPointeeType();
2405
John McCall48f2d582009-10-23 23:03:21 +00002406 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002407 // C++0x [temp.deduct.partial]p6:
2408 // If both P and A were reference types (before being replaced with the
2409 // type referred to above), determine which of the two types (if any) is
2410 // more cv-qualified than the other; otherwise the types are considered to
2411 // be equally cv-qualified for partial ordering purposes. The result of this
2412 // determination will be used below.
2413 //
2414 // We save this information for later, using it only when deduction
2415 // succeeds in both directions.
2416 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2417 if (Param.isMoreQualifiedThan(Arg))
2418 QualifierResult = ParamMoreQualified;
2419 else if (Arg.isMoreQualifiedThan(Param))
2420 QualifierResult = ArgMoreQualified;
2421 QualifierComparisons->push_back(QualifierResult);
2422 }
2423
2424 // C++0x [temp.deduct.partial]p7:
2425 // Remove any top-level cv-qualifiers:
2426 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2427 // version of P.
2428 Param = Param.getUnqualifiedType();
2429 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2430 // version of A.
2431 Arg = Arg.getUnqualifiedType();
2432
2433 // C++0x [temp.deduct.partial]p8:
2434 // Using the resulting types P and A the deduction is then done as
2435 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2436 // from the argument template is considered to be at least as specialized
2437 // as the type from the parameter template.
Chandler Carruthc1263112010-02-07 21:33:28 +00002438 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002439 Deduced, TDF_None);
2440}
2441
2442static void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002443MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2444 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00002445 unsigned Level,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002446 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor52773dc2010-11-12 23:44:13 +00002447
2448/// \brief If this is a non-static member function,
2449static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2450 CXXMethodDecl *Method,
2451 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2452 if (Method->isStatic())
2453 return;
2454
2455 // C++ [over.match.funcs]p4:
2456 //
2457 // For non-static member functions, the type of the implicit
2458 // object parameter is
2459 // — "lvalue reference to cv X" for functions declared without a
2460 // ref-qualifier or with the & ref-qualifier
2461 // - "rvalue reference to cv X" for functions declared with the
2462 // && ref-qualifier
2463 //
2464 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2465 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2466 ArgTy = Context.getQualifiedType(ArgTy,
2467 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2468 ArgTy = Context.getLValueReferenceType(ArgTy);
2469 ArgTypes.push_back(ArgTy);
2470}
2471
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002472/// \brief Determine whether the function template \p FT1 is at least as
2473/// specialized as \p FT2.
2474static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00002475 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002476 FunctionTemplateDecl *FT1,
2477 FunctionTemplateDecl *FT2,
2478 TemplatePartialOrderingContext TPOC,
2479 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2480 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2481 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2482 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2483 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2484
2485 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2486 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002487 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002488 Deduced.resize(TemplateParams->size());
2489
2490 // C++0x [temp.deduct.partial]p3:
2491 // The types used to determine the ordering depend on the context in which
2492 // the partial ordering is done:
John McCall19c1bfd2010-08-25 05:32:35 +00002493 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregoree430a32010-11-15 15:41:16 +00002494 CXXMethodDecl *Method1 = 0;
2495 CXXMethodDecl *Method2 = 0;
2496 bool IsNonStatic2 = false;
2497 bool IsNonStatic1 = false;
2498 unsigned Skip2 = 0;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002499 switch (TPOC) {
2500 case TPOC_Call: {
2501 // - In the context of a function call, the function parameter types are
2502 // used.
Douglas Gregoree430a32010-11-15 15:41:16 +00002503 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2504 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2505 IsNonStatic1 = Method1 && !Method1->isStatic();
2506 IsNonStatic2 = Method2 && !Method2->isStatic();
2507
2508 // C++0x [temp.func.order]p3:
2509 // [...] If only one of the function templates is a non-static
2510 // member, that function template is considered to have a new
2511 // first parameter inserted in its function parameter list. The
2512 // new parameter is of type "reference to cv A," where cv are
2513 // the cv-qualifiers of the function template (if any) and A is
2514 // the class of which the function template is a member.
2515 //
2516 // C++98/03 doesn't have this provision, so instead we drop the
2517 // first argument of the free function or static member, which
2518 // seems to match existing practice.
Douglas Gregor52773dc2010-11-12 23:44:13 +00002519 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregoree430a32010-11-15 15:41:16 +00002520 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2521 IsNonStatic2 && !IsNonStatic1;
2522 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor52773dc2010-11-12 23:44:13 +00002523 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2524 Args1.insert(Args1.end(),
Douglas Gregoree430a32010-11-15 15:41:16 +00002525 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor52773dc2010-11-12 23:44:13 +00002526
2527 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregoree430a32010-11-15 15:41:16 +00002528 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2529 IsNonStatic1 && !IsNonStatic2;
2530 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor52773dc2010-11-12 23:44:13 +00002531 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2532 Args2.insert(Args2.end(),
Douglas Gregoree430a32010-11-15 15:41:16 +00002533 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor52773dc2010-11-12 23:44:13 +00002534
2535 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002536 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carruthc1263112010-02-07 21:33:28 +00002537 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002538 TemplateParams,
Douglas Gregor52773dc2010-11-12 23:44:13 +00002539 Args2[I],
2540 Args1[I],
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002541 Info,
2542 Deduced,
2543 QualifierComparisons))
2544 return false;
2545
2546 break;
2547 }
2548
2549 case TPOC_Conversion:
2550 // - In the context of a call to a conversion operator, the return types
2551 // of the conversion function templates are used.
Chandler Carruthc1263112010-02-07 21:33:28 +00002552 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002553 TemplateParams,
2554 Proto2->getResultType(),
2555 Proto1->getResultType(),
2556 Info,
2557 Deduced,
2558 QualifierComparisons))
2559 return false;
2560 break;
2561
2562 case TPOC_Other:
2563 // - In other contexts (14.6.6.2) the function template’s function type
2564 // is used.
Chandler Carruthc1263112010-02-07 21:33:28 +00002565 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002566 TemplateParams,
2567 FD2->getType(),
2568 FD1->getType(),
2569 Info,
2570 Deduced,
2571 QualifierComparisons))
2572 return false;
2573 break;
2574 }
2575
2576 // C++0x [temp.deduct.partial]p11:
2577 // In most cases, all template parameters must have values in order for
2578 // deduction to succeed, but for partial ordering purposes a template
2579 // parameter may remain without a value provided it is not used in the
2580 // types being used for partial ordering. [ Note: a template parameter used
2581 // in a non-deduced context is considered used. -end note]
2582 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2583 for (; ArgIdx != NumArgs; ++ArgIdx)
2584 if (Deduced[ArgIdx].isNull())
2585 break;
2586
2587 if (ArgIdx == NumArgs) {
2588 // All template arguments were deduced. FT1 is at least as specialized
2589 // as FT2.
2590 return true;
2591 }
2592
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002593 // Figure out which template parameters were used.
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002594 llvm::SmallVector<bool, 4> UsedParameters;
2595 UsedParameters.resize(TemplateParams->size());
2596 switch (TPOC) {
2597 case TPOC_Call: {
2598 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregoree430a32010-11-15 15:41:16 +00002599 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2600 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2601 TemplateParams->getDepth(), UsedParameters);
2602 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregor21610382009-10-29 00:04:11 +00002603 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2604 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002605 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002606 break;
2607 }
2608
2609 case TPOC_Conversion:
Douglas Gregor21610382009-10-29 00:04:11 +00002610 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2611 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002612 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002613 break;
2614
2615 case TPOC_Other:
Douglas Gregor21610382009-10-29 00:04:11 +00002616 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2617 TemplateParams->getDepth(),
2618 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002619 break;
2620 }
2621
2622 for (; ArgIdx != NumArgs; ++ArgIdx)
2623 // If this argument had no value deduced but was used in one of the types
2624 // used for partial ordering, then deduction fails.
2625 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2626 return false;
2627
2628 return true;
2629}
2630
2631
Douglas Gregorbe999392009-09-15 16:23:51 +00002632/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00002633/// to the rules of function template partial ordering (C++ [temp.func.order]).
2634///
2635/// \param FT1 the first function template
2636///
2637/// \param FT2 the second function template
2638///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002639/// \param TPOC the context in which we are performing partial ordering of
2640/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00002641///
Douglas Gregorbe999392009-09-15 16:23:51 +00002642/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00002643/// template is more specialized, returns NULL.
2644FunctionTemplateDecl *
2645Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2646 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00002647 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002648 TemplatePartialOrderingContext TPOC) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002649 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCallbc077cf2010-02-08 23:07:23 +00002650 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2651 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002652 &QualifierComparisons);
2653
2654 if (Better1 != Better2) // We have a clear winner
2655 return Better1? FT1 : FT2;
2656
2657 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor05155d82009-08-21 23:19:43 +00002658 return 0;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002659
2660
2661 // C++0x [temp.deduct.partial]p10:
2662 // If for each type being considered a given template is at least as
2663 // specialized for all types and more specialized for some set of types and
2664 // the other template is not more specialized for any types or is not at
2665 // least as specialized for any types, then the given template is more
2666 // specialized than the other template. Otherwise, neither template is more
2667 // specialized than the other.
2668 Better1 = false;
2669 Better2 = false;
2670 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2671 // C++0x [temp.deduct.partial]p9:
2672 // If, for a given type, deduction succeeds in both directions (i.e., the
2673 // types are identical after the transformations above) and if the type
2674 // from the argument template is more cv-qualified than the type from the
2675 // parameter template (as described above) that type is considered to be
2676 // more specialized than the other. If neither type is more cv-qualified
2677 // than the other then neither type is more specialized than the other.
2678 switch (QualifierComparisons[I]) {
2679 case NeitherMoreQualified:
2680 break;
2681
2682 case ParamMoreQualified:
2683 Better1 = true;
2684 if (Better2)
2685 return 0;
2686 break;
2687
2688 case ArgMoreQualified:
2689 Better2 = true;
2690 if (Better1)
2691 return 0;
2692 break;
2693 }
2694 }
2695
2696 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor05155d82009-08-21 23:19:43 +00002697 if (Better1)
2698 return FT1;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00002699 else if (Better2)
2700 return FT2;
2701 else
2702 return 0;
Douglas Gregor05155d82009-08-21 23:19:43 +00002703}
Douglas Gregor9b146582009-07-08 20:55:45 +00002704
Douglas Gregor450f00842009-09-25 18:43:00 +00002705/// \brief Determine if the two templates are equivalent.
2706static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2707 if (T1 == T2)
2708 return true;
2709
2710 if (!T1 || !T2)
2711 return false;
2712
2713 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2714}
2715
2716/// \brief Retrieve the most specialized of the given function template
2717/// specializations.
2718///
John McCall58cc69d2010-01-27 01:50:18 +00002719/// \param SpecBegin the start iterator of the function template
2720/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00002721///
John McCall58cc69d2010-01-27 01:50:18 +00002722/// \param SpecEnd the end iterator of the function template
2723/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00002724///
2725/// \param TPOC the partial ordering context to use to compare the function
2726/// template specializations.
2727///
2728/// \param Loc the location where the ambiguity or no-specializations
2729/// diagnostic should occur.
2730///
2731/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2732/// no matching candidates.
2733///
2734/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2735/// occurs.
2736///
2737/// \param CandidateDiag partial diagnostic used for each function template
2738/// specialization that is a candidate in the ambiguous ordering. One parameter
2739/// in this diagnostic should be unbound, which will correspond to the string
2740/// describing the template arguments for the function template specialization.
2741///
2742/// \param Index if non-NULL and the result of this function is non-nULL,
2743/// receives the index corresponding to the resulting function template
2744/// specialization.
2745///
2746/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00002747/// found. Otherwise, returns SpecEnd.
Douglas Gregor450f00842009-09-25 18:43:00 +00002748///
2749/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2750/// template argument deduction.
John McCall58cc69d2010-01-27 01:50:18 +00002751UnresolvedSetIterator
2752Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
2753 UnresolvedSetIterator SpecEnd,
2754 TemplatePartialOrderingContext TPOC,
2755 SourceLocation Loc,
2756 const PartialDiagnostic &NoneDiag,
2757 const PartialDiagnostic &AmbigDiag,
2758 const PartialDiagnostic &CandidateDiag) {
2759 if (SpecBegin == SpecEnd) {
Douglas Gregor450f00842009-09-25 18:43:00 +00002760 Diag(Loc, NoneDiag);
John McCall58cc69d2010-01-27 01:50:18 +00002761 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00002762 }
2763
John McCall58cc69d2010-01-27 01:50:18 +00002764 if (SpecBegin + 1 == SpecEnd)
2765 return SpecBegin;
Douglas Gregor450f00842009-09-25 18:43:00 +00002766
2767 // Find the function template that is better than all of the templates it
2768 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00002769 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregor450f00842009-09-25 18:43:00 +00002770 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00002771 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00002772 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00002773 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
2774 FunctionTemplateDecl *Challenger
2775 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00002776 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00002777 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCallbc077cf2010-02-08 23:07:23 +00002778 Loc, TPOC),
Douglas Gregor450f00842009-09-25 18:43:00 +00002779 Challenger)) {
2780 Best = I;
2781 BestTemplate = Challenger;
2782 }
2783 }
2784
2785 // Make sure that the "best" function template is more specialized than all
2786 // of the others.
2787 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00002788 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
2789 FunctionTemplateDecl *Challenger
2790 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00002791 if (I != Best &&
2792 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCallbc077cf2010-02-08 23:07:23 +00002793 Loc, TPOC),
Douglas Gregor450f00842009-09-25 18:43:00 +00002794 BestTemplate)) {
2795 Ambiguous = true;
2796 break;
2797 }
2798 }
2799
2800 if (!Ambiguous) {
2801 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00002802 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00002803 }
2804
2805 // Diagnose the ambiguity.
2806 Diag(Loc, AmbigDiag);
2807
2808 // FIXME: Can we order the candidates in some sane way?
John McCall58cc69d2010-01-27 01:50:18 +00002809 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
2810 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregor450f00842009-09-25 18:43:00 +00002811 << getTemplateArgumentBindingsText(
John McCall58cc69d2010-01-27 01:50:18 +00002812 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
2813 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregor450f00842009-09-25 18:43:00 +00002814
John McCall58cc69d2010-01-27 01:50:18 +00002815 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00002816}
2817
Douglas Gregorbe999392009-09-15 16:23:51 +00002818/// \brief Returns the more specialized class template partial specialization
2819/// according to the rules of partial ordering of class template partial
2820/// specializations (C++ [temp.class.order]).
2821///
2822/// \param PS1 the first class template partial specialization
2823///
2824/// \param PS2 the second class template partial specialization
2825///
2826/// \returns the more specialized class template partial specialization. If
2827/// neither partial specialization is more specialized, returns NULL.
2828ClassTemplatePartialSpecializationDecl *
2829Sema::getMoreSpecializedPartialSpecialization(
2830 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00002831 ClassTemplatePartialSpecializationDecl *PS2,
2832 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002833 // C++ [temp.class.order]p1:
2834 // For two class template partial specializations, the first is at least as
2835 // specialized as the second if, given the following rewrite to two
2836 // function templates, the first function template is at least as
2837 // specialized as the second according to the ordering rules for function
2838 // templates (14.6.6.2):
2839 // - the first function template has the same template parameters as the
2840 // first partial specialization and has a single function parameter
2841 // whose type is a class template specialization with the template
2842 // arguments of the first partial specialization, and
2843 // - the second function template has the same template parameters as the
2844 // second partial specialization and has a single function parameter
2845 // whose type is a class template specialization with the template
2846 // arguments of the second partial specialization.
2847 //
Douglas Gregor684268d2010-04-29 06:21:43 +00002848 // Rather than synthesize function templates, we merely perform the
2849 // equivalent partial ordering by performing deduction directly on
2850 // the template arguments of the class template partial
2851 // specializations. This computation is slightly simpler than the
2852 // general problem of function template partial ordering, because
2853 // class template partial specializations are more constrained. We
2854 // know that every template parameter is deducible from the class
2855 // template partial specialization's template arguments, for
2856 // example.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002857 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall19c1bfd2010-08-25 05:32:35 +00002858 TemplateDeductionInfo Info(Context, Loc);
John McCall2408e322010-04-27 00:57:59 +00002859
2860 QualType PT1 = PS1->getInjectedSpecializationType();
2861 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbe999392009-09-15 16:23:51 +00002862
2863 // Determine whether PS1 is at least as specialized as PS2
2864 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carruthc1263112010-02-07 21:33:28 +00002865 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbe999392009-09-15 16:23:51 +00002866 PS2->getTemplateParameters(),
John McCall2408e322010-04-27 00:57:59 +00002867 PT2,
2868 PT1,
Douglas Gregorbe999392009-09-15 16:23:51 +00002869 Info,
2870 Deduced,
2871 0);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00002872 if (Better1) {
2873 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
2874 Deduced.data(), Deduced.size(), Info);
Douglas Gregor9225b022010-04-29 06:31:36 +00002875 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
2876 PS1->getTemplateArgs(),
2877 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00002878 }
Douglas Gregor9225b022010-04-29 06:31:36 +00002879
Douglas Gregorbe999392009-09-15 16:23:51 +00002880 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00002881 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00002882 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carruthc1263112010-02-07 21:33:28 +00002883 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbe999392009-09-15 16:23:51 +00002884 PS1->getTemplateParameters(),
John McCall2408e322010-04-27 00:57:59 +00002885 PT1,
2886 PT2,
Douglas Gregorbe999392009-09-15 16:23:51 +00002887 Info,
2888 Deduced,
2889 0);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00002890 if (Better2) {
2891 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
2892 Deduced.data(), Deduced.size(), Info);
Douglas Gregor9225b022010-04-29 06:31:36 +00002893 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
2894 PS2->getTemplateArgs(),
2895 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00002896 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002897
2898 if (Better1 == Better2)
2899 return 0;
2900
2901 return Better1? PS1 : PS2;
2902}
2903
Mike Stump11289f42009-09-09 15:08:12 +00002904static void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002905MarkUsedTemplateParameters(Sema &SemaRef,
2906 const TemplateArgument &TemplateArg,
2907 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00002908 unsigned Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002909 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00002910
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002911/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00002912/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00002913static void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002914MarkUsedTemplateParameters(Sema &SemaRef,
2915 const Expr *E,
2916 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00002917 unsigned Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002918 llvm::SmallVectorImpl<bool> &Used) {
2919 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2920 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00002921 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00002922 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00002923 return;
2924
Mike Stump11289f42009-09-09 15:08:12 +00002925 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00002926 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2927 if (!NTTP)
2928 return;
2929
Douglas Gregor21610382009-10-29 00:04:11 +00002930 if (NTTP->getDepth() == Depth)
2931 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00002932}
2933
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002934/// \brief Mark the template parameters that are used by the given
2935/// nested name specifier.
2936static void
2937MarkUsedTemplateParameters(Sema &SemaRef,
2938 NestedNameSpecifier *NNS,
2939 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00002940 unsigned Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002941 llvm::SmallVectorImpl<bool> &Used) {
2942 if (!NNS)
2943 return;
2944
Douglas Gregor21610382009-10-29 00:04:11 +00002945 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
2946 Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002947 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00002948 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002949}
2950
2951/// \brief Mark the template parameters that are used by the given
2952/// template name.
2953static void
2954MarkUsedTemplateParameters(Sema &SemaRef,
2955 TemplateName Name,
2956 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00002957 unsigned Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002958 llvm::SmallVectorImpl<bool> &Used) {
2959 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2960 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00002961 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
2962 if (TTP->getDepth() == Depth)
2963 Used[TTP->getIndex()] = true;
2964 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002965 return;
2966 }
2967
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002968 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
2969 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
2970 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002971 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregor21610382009-10-29 00:04:11 +00002972 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
2973 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002974}
2975
2976/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00002977/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002978static void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002979MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2980 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00002981 unsigned Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002982 llvm::SmallVectorImpl<bool> &Used) {
2983 if (T.isNull())
2984 return;
2985
Douglas Gregor91772d12009-06-13 00:26:55 +00002986 // Non-dependent types have nothing deducible
2987 if (!T->isDependentType())
2988 return;
2989
2990 T = SemaRef.Context.getCanonicalType(T);
2991 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00002992 case Type::Pointer:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002993 MarkUsedTemplateParameters(SemaRef,
2994 cast<PointerType>(T)->getPointeeType(),
2995 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00002996 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00002997 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00002998 break;
2999
3000 case Type::BlockPointer:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003001 MarkUsedTemplateParameters(SemaRef,
3002 cast<BlockPointerType>(T)->getPointeeType(),
3003 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003004 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003005 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003006 break;
3007
3008 case Type::LValueReference:
3009 case Type::RValueReference:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003010 MarkUsedTemplateParameters(SemaRef,
3011 cast<ReferenceType>(T)->getPointeeType(),
3012 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003013 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003014 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003015 break;
3016
3017 case Type::MemberPointer: {
3018 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003019 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003020 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003021 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00003022 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003023 break;
3024 }
3025
3026 case Type::DependentSizedArray:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003027 MarkUsedTemplateParameters(SemaRef,
3028 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00003029 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003030 // Fall through to check the element type
3031
3032 case Type::ConstantArray:
3033 case Type::IncompleteArray:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003034 MarkUsedTemplateParameters(SemaRef,
3035 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00003036 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003037 break;
3038
3039 case Type::Vector:
3040 case Type::ExtVector:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003041 MarkUsedTemplateParameters(SemaRef,
3042 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00003043 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003044 break;
3045
Douglas Gregor758a8692009-06-17 21:51:59 +00003046 case Type::DependentSizedExtVector: {
3047 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00003048 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003049 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003050 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003051 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003052 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00003053 break;
3054 }
3055
Douglas Gregor91772d12009-06-13 00:26:55 +00003056 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00003057 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003058 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003059 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003060 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003061 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003062 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003063 break;
3064 }
3065
Douglas Gregor21610382009-10-29 00:04:11 +00003066 case Type::TemplateTypeParm: {
3067 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
3068 if (TTP->getDepth() == Depth)
3069 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00003070 break;
Douglas Gregor21610382009-10-29 00:04:11 +00003071 }
Douglas Gregor91772d12009-06-13 00:26:55 +00003072
John McCall2408e322010-04-27 00:57:59 +00003073 case Type::InjectedClassName:
3074 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
3075 // fall through
3076
Douglas Gregor91772d12009-06-13 00:26:55 +00003077 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00003078 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00003079 = cast<TemplateSpecializationType>(T);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003080 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003081 Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00003082
3083 // C++0x [temp.deduct.type]p9:
3084 // If the template argument list of P contains a pack expansion that is not
3085 // the last template argument, the entire template argument list is a
3086 // non-deduced context.
3087 if (OnlyDeduced &&
3088 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3089 break;
3090
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003091 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregor21610382009-10-29 00:04:11 +00003092 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3093 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003094 break;
3095 }
3096
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003097 case Type::Complex:
3098 if (!OnlyDeduced)
3099 MarkUsedTemplateParameters(SemaRef,
3100 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00003101 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003102 break;
3103
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003104 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003105 if (!OnlyDeduced)
3106 MarkUsedTemplateParameters(SemaRef,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003107 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00003108 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003109 break;
3110
John McCallc392f372010-06-11 00:33:02 +00003111 case Type::DependentTemplateSpecialization: {
3112 const DependentTemplateSpecializationType *Spec
3113 = cast<DependentTemplateSpecializationType>(T);
3114 if (!OnlyDeduced)
3115 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
3116 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00003117
3118 // C++0x [temp.deduct.type]p9:
3119 // If the template argument list of P contains a pack expansion that is not
3120 // the last template argument, the entire template argument list is a
3121 // non-deduced context.
3122 if (OnlyDeduced &&
3123 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
3124 break;
3125
John McCallc392f372010-06-11 00:33:02 +00003126 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
3127 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
3128 Used);
3129 break;
3130 }
3131
John McCallbd8d9bd2010-03-01 23:49:17 +00003132 case Type::TypeOf:
3133 if (!OnlyDeduced)
3134 MarkUsedTemplateParameters(SemaRef,
3135 cast<TypeOfType>(T)->getUnderlyingType(),
3136 OnlyDeduced, Depth, Used);
3137 break;
3138
3139 case Type::TypeOfExpr:
3140 if (!OnlyDeduced)
3141 MarkUsedTemplateParameters(SemaRef,
3142 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
3143 OnlyDeduced, Depth, Used);
3144 break;
3145
3146 case Type::Decltype:
3147 if (!OnlyDeduced)
3148 MarkUsedTemplateParameters(SemaRef,
3149 cast<DecltypeType>(T)->getUnderlyingExpr(),
3150 OnlyDeduced, Depth, Used);
3151 break;
3152
Douglas Gregord2fa7662010-12-20 02:24:11 +00003153 case Type::PackExpansion:
3154 MarkUsedTemplateParameters(SemaRef,
3155 cast<PackExpansionType>(T)->getPattern(),
3156 OnlyDeduced, Depth, Used);
3157 break;
3158
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003159 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00003160 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00003161 case Type::VariableArray:
3162 case Type::FunctionNoProto:
3163 case Type::Record:
3164 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00003165 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00003166 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00003167 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00003168 case Type::UnresolvedUsing:
Douglas Gregor91772d12009-06-13 00:26:55 +00003169#define TYPE(Class, Base)
3170#define ABSTRACT_TYPE(Class, Base)
3171#define DEPENDENT_TYPE(Class, Base)
3172#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3173#include "clang/AST/TypeNodes.def"
3174 break;
3175 }
3176}
3177
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003178/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00003179/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00003180static void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003181MarkUsedTemplateParameters(Sema &SemaRef,
3182 const TemplateArgument &TemplateArg,
3183 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003184 unsigned Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003185 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00003186 switch (TemplateArg.getKind()) {
3187 case TemplateArgument::Null:
3188 case TemplateArgument::Integral:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003189 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00003190 break;
Mike Stump11289f42009-09-09 15:08:12 +00003191
Douglas Gregor91772d12009-06-13 00:26:55 +00003192 case TemplateArgument::Type:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003193 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003194 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003195 break;
3196
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003197 case TemplateArgument::Template:
3198 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsTemplate(),
3199 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003200 break;
3201
3202 case TemplateArgument::Expression:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003203 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00003204 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003205 break;
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003206
Anders Carlssonbc343912009-06-15 17:04:53 +00003207 case TemplateArgument::Pack:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003208 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
3209 PEnd = TemplateArg.pack_end();
3210 P != PEnd; ++P)
Douglas Gregor21610382009-10-29 00:04:11 +00003211 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00003212 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00003213 }
3214}
3215
3216/// \brief Mark the template parameters can be deduced by the given
3217/// template argument list.
3218///
3219/// \param TemplateArgs the template argument list from which template
3220/// parameters will be deduced.
3221///
3222/// \param Deduced a bit vector whose elements will be set to \c true
3223/// to indicate when the corresponding template parameter will be
3224/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00003225void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003226Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00003227 bool OnlyDeduced, unsigned Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003228 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00003229 // C++0x [temp.deduct.type]p9:
3230 // If the template argument list of P contains a pack expansion that is not
3231 // the last template argument, the entire template argument list is a
3232 // non-deduced context.
3233 if (OnlyDeduced &&
3234 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
3235 return;
3236
Douglas Gregor91772d12009-06-13 00:26:55 +00003237 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregor21610382009-10-29 00:04:11 +00003238 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
3239 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00003240}
Douglas Gregorce23bae2009-09-18 23:21:38 +00003241
3242/// \brief Marks all of the template parameters that will be deduced by a
3243/// call to the given function template.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003244void
3245Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
3246 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregorce23bae2009-09-18 23:21:38 +00003247 TemplateParameterList *TemplateParams
3248 = FunctionTemplate->getTemplateParameters();
3249 Deduced.clear();
3250 Deduced.resize(TemplateParams->size());
3251
Douglas Gregord0ad2942010-12-23 01:24:45 +00003252 // FIXME: Variadic templates.
Douglas Gregorce23bae2009-09-18 23:21:38 +00003253 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3254 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
3255 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00003256 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00003257}