blob: da04b6219859fd9ee96223671913714372d6706f [file] [log] [blame]
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Sema.h"
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/DeclSpec.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000017#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregor0b9247f2009-06-04 00:03:07 +000019#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/StmtVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
Douglas Gregor8a514912009-09-14 18:39:43 +000023#include <algorithm>
Douglas Gregor508f1c82009-06-26 23:10:12 +000024
25namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000026 using namespace sema;
27
Douglas Gregor508f1c82009-06-26 23:10:12 +000028 /// \brief Various flags that control template argument deduction.
29 ///
30 /// These flags can be bitwise-OR'd together.
31 enum TemplateDeductionFlags {
32 /// \brief No template argument deduction flags, which indicates the
33 /// strictest results for template argument deduction (as used for, e.g.,
34 /// matching class template partial specializations).
35 TDF_None = 0,
36 /// \brief Within template argument deduction from a function call, we are
37 /// matching with a parameter type for which the original parameter was
38 /// a reference.
39 TDF_ParamWithReferenceType = 0x1,
40 /// \brief Within template argument deduction from a function call, we
41 /// are matching in a case where we ignore cv-qualifiers.
42 TDF_IgnoreQualifiers = 0x02,
43 /// \brief Within template argument deduction from a function call,
44 /// we are matching in a case where we can perform template argument
Douglas Gregor41128772009-06-26 23:27:24 +000045 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor12820292009-09-14 20:00:47 +000046 TDF_DerivedClass = 0x04,
47 /// \brief Allow non-dependent types to differ, e.g., when performing
48 /// template argument deduction from a function call where conversions
49 /// may apply.
50 TDF_SkipNonDependent = 0x08
Douglas Gregor508f1c82009-06-26 23:10:12 +000051 };
52}
53
Douglas Gregor0b9247f2009-06-04 00:03:07 +000054using namespace clang;
55
Douglas Gregor9d0e4412010-03-26 05:50:28 +000056/// \brief Compare two APSInts, extending and switching the sign as
57/// necessary to compare their values regardless of underlying type.
58static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
59 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000060 X = X.extend(Y.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000061 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +000062 Y = Y.extend(X.getBitWidth());
Douglas Gregor9d0e4412010-03-26 05:50:28 +000063
64 // If there is a signedness mismatch, correct it.
65 if (X.isSigned() != Y.isSigned()) {
66 // If the signed value is negative, then the values cannot be the same.
67 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
68 return false;
69
70 Y.setIsSigned(true);
71 X.setIsSigned(true);
72 }
73
74 return X == Y;
75}
76
Douglas Gregorf67875d2009-06-12 18:26:56 +000077static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +000078DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +000079 TemplateParameterList *TemplateParams,
80 const TemplateArgument &Param,
Douglas Gregord708c722009-06-09 16:35:58 +000081 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +000082 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +000083 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregord708c722009-06-09 16:35:58 +000084
Douglas Gregor199d9912009-06-05 00:53:49 +000085/// \brief If the given expression is of a form that permits the deduction
86/// of a non-type template parameter, return the declaration of that
87/// non-type template parameter.
88static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
89 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
90 E = IC->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +000091
Douglas Gregor199d9912009-06-05 00:53:49 +000092 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
93 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +000094
Douglas Gregor199d9912009-06-05 00:53:49 +000095 return 0;
96}
97
Mike Stump1eb44332009-09-09 15:08:12 +000098/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +000099/// from the given constant.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000100static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000101DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump1eb44332009-09-09 15:08:12 +0000102 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000103 llvm::APSInt Value, QualType ValueType,
Douglas Gregor02024a92010-03-28 02:42:43 +0000104 bool DeducedFromArrayBound,
John McCall2a7fb272010-08-25 05:32:35 +0000105 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000106 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000107 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000108 "Cannot deduce non-type template argument with depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Douglas Gregor199d9912009-06-05 00:53:49 +0000110 if (Deduced[NTTP->getIndex()].isNull()) {
Douglas Gregor02024a92010-03-28 02:42:43 +0000111 Deduced[NTTP->getIndex()] = DeducedTemplateArgument(Value, ValueType,
112 DeducedFromArrayBound);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000113 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000114 }
Mike Stump1eb44332009-09-09 15:08:12 +0000115
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000116 if (Deduced[NTTP->getIndex()].getKind() != TemplateArgument::Integral) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000117 Info.Param = NTTP;
118 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000119 Info.SecondArg = TemplateArgument(Value, ValueType);
120 return Sema::TDK_Inconsistent;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000121 }
122
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000123 // Extent the smaller of the two values.
124 llvm::APSInt PrevValue = *Deduced[NTTP->getIndex()].getAsIntegral();
125 if (!hasSameExtendedValue(PrevValue, Value)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000126 Info.Param = NTTP;
127 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000128 Info.SecondArg = TemplateArgument(Value, ValueType);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000129 return Sema::TDK_Inconsistent;
130 }
131
Douglas Gregor02024a92010-03-28 02:42:43 +0000132 if (!DeducedFromArrayBound)
133 Deduced[NTTP->getIndex()].setDeducedFromArrayBound(false);
134
Douglas Gregorf67875d2009-06-12 18:26:56 +0000135 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000136}
137
Mike Stump1eb44332009-09-09 15:08:12 +0000138/// \brief Deduce the value of the given non-type template parameter
Douglas Gregor199d9912009-06-05 00:53:49 +0000139/// from the given type- or value-dependent expression.
140///
141/// \returns true if deduction succeeded, false otherwise.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000142static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000143DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000144 NonTypeTemplateParmDecl *NTTP,
145 Expr *Value,
John McCall2a7fb272010-08-25 05:32:35 +0000146 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000147 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump1eb44332009-09-09 15:08:12 +0000148 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000149 "Cannot deduce non-type template argument with depth > 0");
150 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
151 "Expression template argument must be type- or value-dependent.");
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Douglas Gregor199d9912009-06-05 00:53:49 +0000153 if (Deduced[NTTP->getIndex()].isNull()) {
John McCall3fa5cae2010-10-26 07:05:15 +0000154 Deduced[NTTP->getIndex()] = TemplateArgument(Value);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000155 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000156 }
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Douglas Gregor199d9912009-06-05 00:53:49 +0000158 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Integral) {
Mike Stump1eb44332009-09-09 15:08:12 +0000159 // Okay, we deduced a constant in one case and a dependent expression
160 // in another case. FIXME: Later, we will check that instantiating the
Douglas Gregor199d9912009-06-05 00:53:49 +0000161 // dependent expression gives us the constant value.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000162 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000163 }
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Douglas Gregor9eea08b2009-09-15 16:51:42 +0000165 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
166 // Compare the expressions for equality
167 llvm::FoldingSetNodeID ID1, ID2;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000168 Deduced[NTTP->getIndex()].getAsExpr()->Profile(ID1, S.Context, true);
169 Value->Profile(ID2, S.Context, true);
Douglas Gregor9eea08b2009-09-15 16:51:42 +0000170 if (ID1 == ID2)
171 return Sema::TDK_Success;
172
173 // FIXME: Fill in argument mismatch information
174 return Sema::TDK_NonDeducedMismatch;
175 }
176
Douglas Gregorf67875d2009-06-12 18:26:56 +0000177 return Sema::TDK_Success;
Douglas Gregor199d9912009-06-05 00:53:49 +0000178}
179
Douglas Gregor15755cb2009-11-13 23:45:44 +0000180/// \brief Deduce the value of the given non-type template parameter
181/// from the given declaration.
182///
183/// \returns true if deduction succeeded, false otherwise.
184static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000185DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor15755cb2009-11-13 23:45:44 +0000186 NonTypeTemplateParmDecl *NTTP,
187 Decl *D,
John McCall2a7fb272010-08-25 05:32:35 +0000188 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000189 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor15755cb2009-11-13 23:45:44 +0000190 assert(NTTP->getDepth() == 0 &&
191 "Cannot deduce non-type template argument with depth > 0");
192
193 if (Deduced[NTTP->getIndex()].isNull()) {
194 Deduced[NTTP->getIndex()] = TemplateArgument(D->getCanonicalDecl());
195 return Sema::TDK_Success;
196 }
197
198 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Expression) {
199 // Okay, we deduced a declaration in one case and a dependent expression
200 // in another case.
201 return Sema::TDK_Success;
202 }
203
204 if (Deduced[NTTP->getIndex()].getKind() == TemplateArgument::Declaration) {
205 // Compare the declarations for equality
206 if (Deduced[NTTP->getIndex()].getAsDecl()->getCanonicalDecl() ==
207 D->getCanonicalDecl())
208 return Sema::TDK_Success;
209
210 // FIXME: Fill in argument mismatch information
211 return Sema::TDK_NonDeducedMismatch;
212 }
213
214 return Sema::TDK_Success;
215}
216
Douglas Gregorf67875d2009-06-12 18:26:56 +0000217static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000218DeduceTemplateArguments(Sema &S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000219 TemplateParameterList *TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000220 TemplateName Param,
221 TemplateName Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000222 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000223 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregord708c722009-06-09 16:35:58 +0000224 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000225 if (!ParamDecl) {
226 // The parameter type is dependent and is not a template template parameter,
227 // so there is nothing that we can deduce.
228 return Sema::TDK_Success;
229 }
230
231 if (TemplateTemplateParmDecl *TempParam
232 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
233 // Bind the template template parameter to the given template name.
234 TemplateArgument &ExistingArg = Deduced[TempParam->getIndex()];
235 if (ExistingArg.isNull()) {
236 // This is the first deduction for this template template parameter.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000237 ExistingArg = TemplateArgument(S.Context.getCanonicalTemplateName(Arg));
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000238 return Sema::TDK_Success;
239 }
240
241 // Verify that the previous binding matches this deduction.
242 assert(ExistingArg.getKind() == TemplateArgument::Template);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000243 if (S.Context.hasSameTemplateName(ExistingArg.getAsTemplate(), Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000244 return Sema::TDK_Success;
245
246 // Inconsistent deduction.
247 Info.Param = TempParam;
248 Info.FirstArg = ExistingArg;
249 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000250 return Sema::TDK_Inconsistent;
251 }
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000252
253 // Verify that the two template names are equivalent.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000254 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000255 return Sema::TDK_Success;
256
257 // Mismatch of non-dependent template parameter to argument.
258 Info.FirstArg = TemplateArgument(Param);
259 Info.SecondArg = TemplateArgument(Arg);
260 return Sema::TDK_NonDeducedMismatch;
Douglas Gregord708c722009-06-09 16:35:58 +0000261}
262
Mike Stump1eb44332009-09-09 15:08:12 +0000263/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000264/// type (which is a template-id) with the template argument type.
265///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000266/// \param S the Sema
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000267///
268/// \param TemplateParams the template parameters that we are deducing
269///
270/// \param Param the parameter type
271///
272/// \param Arg the argument type
273///
274/// \param Info information about the template argument deduction itself
275///
276/// \param Deduced the deduced template arguments
277///
278/// \returns the result of template argument deduction so far. Note that a
279/// "success" result means that template argument deduction has not yet failed,
280/// but it may still fail, later, for other reasons.
281static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000282DeduceTemplateArguments(Sema &S,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000283 TemplateParameterList *TemplateParams,
284 const TemplateSpecializationType *Param,
285 QualType Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000286 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000287 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCall467b27b2009-10-22 20:10:53 +0000288 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000290 // Check whether the template argument is a dependent template-id.
Mike Stump1eb44332009-09-09 15:08:12 +0000291 if (const TemplateSpecializationType *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000292 = dyn_cast<TemplateSpecializationType>(Arg)) {
293 // Perform template argument deduction for the template name.
294 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000295 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000296 Param->getTemplateName(),
297 SpecArg->getTemplateName(),
298 Info, Deduced))
299 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000302 // Perform template argument deduction on each template
303 // argument.
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000304 unsigned NumArgs = std::min(SpecArg->getNumArgs(), Param->getNumArgs());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000305 for (unsigned I = 0; I != NumArgs; ++I)
306 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000307 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000308 Param->getArg(I),
309 SpecArg->getArg(I),
310 Info, Deduced))
311 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000313 return Sema::TDK_Success;
314 }
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000316 // If the argument type is a class template specialization, we
317 // perform template argument deduction using its template
318 // arguments.
319 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
320 if (!RecordArg)
321 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000322
323 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000324 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
325 if (!SpecArg)
326 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000328 // Perform template argument deduction for the template name.
329 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000330 = DeduceTemplateArguments(S,
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000331 TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000332 Param->getTemplateName(),
333 TemplateName(SpecArg->getSpecializedTemplate()),
334 Info, Deduced))
335 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000337 unsigned NumArgs = Param->getNumArgs();
338 const TemplateArgumentList &ArgArgs = SpecArg->getTemplateArgs();
339 if (NumArgs != ArgArgs.size())
340 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000342 for (unsigned I = 0; I != NumArgs; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +0000343 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000344 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000345 Param->getArg(I),
346 ArgArgs.get(I),
347 Info, Deduced))
348 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000350 return Sema::TDK_Success;
351}
352
John McCallcd05e812010-08-28 22:14:41 +0000353/// \brief Determines whether the given type is an opaque type that
354/// might be more qualified when instantiated.
355static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
356 switch (T->getTypeClass()) {
357 case Type::TypeOfExpr:
358 case Type::TypeOf:
359 case Type::DependentName:
360 case Type::Decltype:
361 case Type::UnresolvedUsing:
362 return true;
363
364 case Type::ConstantArray:
365 case Type::IncompleteArray:
366 case Type::VariableArray:
367 case Type::DependentSizedArray:
368 return IsPossiblyOpaquelyQualifiedType(
369 cast<ArrayType>(T)->getElementType());
370
371 default:
372 return false;
373 }
374}
375
Douglas Gregor500d3312009-06-26 18:27:22 +0000376/// \brief Deduce the template arguments by comparing the parameter type and
377/// the argument type (C++ [temp.deduct.type]).
378///
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000379/// \param S the semantic analysis object within which we are deducing
Douglas Gregor500d3312009-06-26 18:27:22 +0000380///
381/// \param TemplateParams the template parameters that we are deducing
382///
383/// \param ParamIn the parameter type
384///
385/// \param ArgIn the argument type
386///
387/// \param Info information about the template argument deduction itself
388///
389/// \param Deduced the deduced template arguments
390///
Douglas Gregor508f1c82009-06-26 23:10:12 +0000391/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump1eb44332009-09-09 15:08:12 +0000392/// how template argument deduction is performed.
Douglas Gregor500d3312009-06-26 18:27:22 +0000393///
394/// \returns the result of template argument deduction so far. Note that a
395/// "success" result means that template argument deduction has not yet failed,
396/// but it may still fail, later, for other reasons.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000397static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000398DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000399 TemplateParameterList *TemplateParams,
400 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +0000401 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000402 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000403 unsigned TDF) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000404 // We only want to look at the canonical types, since typedefs and
405 // sugar are not part of template argument deduction.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000406 QualType Param = S.Context.getCanonicalType(ParamIn);
407 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000408
Douglas Gregor500d3312009-06-26 18:27:22 +0000409 // C++0x [temp.deduct.call]p4 bullet 1:
410 // - If the original P is a reference type, the deduced A (i.e., the type
Mike Stump1eb44332009-09-09 15:08:12 +0000411 // referred to by the reference) can be more cv-qualified than the
Douglas Gregor500d3312009-06-26 18:27:22 +0000412 // transformed A.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000413 if (TDF & TDF_ParamWithReferenceType) {
Chandler Carruthe7242462009-12-30 04:10:01 +0000414 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000415 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
Chandler Carruthe7242462009-12-30 04:10:01 +0000416 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
417 Arg.getCVRQualifiersThroughArrayTypes());
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000418 Param = S.Context.getQualifiedType(UnqualParam, Quals);
Douglas Gregor500d3312009-06-26 18:27:22 +0000419 }
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000421 // If the parameter type is not dependent, there is nothing to deduce.
Douglas Gregor12820292009-09-14 20:00:47 +0000422 if (!Param->isDependentType()) {
423 if (!(TDF & TDF_SkipNonDependent) && Param != Arg) {
424
425 return Sema::TDK_NonDeducedMismatch;
426 }
427
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000428 return Sema::TDK_Success;
Douglas Gregor12820292009-09-14 20:00:47 +0000429 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000430
Douglas Gregor199d9912009-06-05 00:53:49 +0000431 // C++ [temp.deduct.type]p9:
Mike Stump1eb44332009-09-09 15:08:12 +0000432 // A template type argument T, a template template argument TT or a
433 // template non-type argument i can be deduced if P and A have one of
Douglas Gregor199d9912009-06-05 00:53:49 +0000434 // the following forms:
435 //
436 // T
437 // cv-list T
Mike Stump1eb44332009-09-09 15:08:12 +0000438 if (const TemplateTypeParmType *TemplateTypeParm
John McCall183700f2009-09-21 23:43:11 +0000439 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000440 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000441 bool RecanonicalizeArg = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000442
Douglas Gregor9e9fae42009-07-22 20:02:25 +0000443 // If the argument type is an array type, move the qualifiers up to the
444 // top level, so they can be matched with the qualifiers on the parameter.
445 // FIXME: address spaces, ObjC GC qualifiers
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000446 if (isa<ArrayType>(Arg)) {
John McCall0953e762009-09-24 19:53:00 +0000447 Qualifiers Quals;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000448 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall0953e762009-09-24 19:53:00 +0000449 if (Quals) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000450 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000451 RecanonicalizeArg = true;
452 }
453 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000455 // The argument type can not be less qualified than the parameter
456 // type.
Douglas Gregor508f1c82009-06-26 23:10:12 +0000457 if (Param.isMoreQualifiedThan(Arg) && !(TDF & TDF_IgnoreQualifiers)) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000458 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall57e97782010-08-05 09:05:08 +0000459 Info.FirstArg = TemplateArgument(Param);
John McCall833ca992009-10-29 08:12:44 +0000460 Info.SecondArg = TemplateArgument(Arg);
John McCall57e97782010-08-05 09:05:08 +0000461 return Sema::TDK_Underqualified;
Douglas Gregorf67875d2009-06-12 18:26:56 +0000462 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000463
464 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000465 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall0953e762009-09-24 19:53:00 +0000466 QualType DeducedType = Arg;
John McCall49f4e1c2010-12-10 11:01:00 +0000467
468 // local manipulation is okay because it's canonical
469 DeducedType.removeLocalCVRQualifiers(Param.getCVRQualifiers());
Douglas Gregorf290e0d2009-07-22 21:30:48 +0000470 if (RecanonicalizeArg)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000471 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000473 if (Deduced[Index].isNull())
John McCall833ca992009-10-29 08:12:44 +0000474 Deduced[Index] = TemplateArgument(DeducedType);
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000475 else {
Mike Stump1eb44332009-09-09 15:08:12 +0000476 // C++ [temp.deduct.type]p2:
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000477 // [...] If type deduction cannot be done for any P/A pair, or if for
Mike Stump1eb44332009-09-09 15:08:12 +0000478 // any pair the deduction leads to more than one possible set of
479 // deduced values, or if different pairs yield different deduced
480 // values, or if any template argument remains neither deduced nor
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000481 // explicitly specified, template argument deduction fails.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000482 if (Deduced[Index].getAsType() != DeducedType) {
Mike Stump1eb44332009-09-09 15:08:12 +0000483 Info.Param
Douglas Gregorf67875d2009-06-12 18:26:56 +0000484 = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
485 Info.FirstArg = Deduced[Index];
John McCall833ca992009-10-29 08:12:44 +0000486 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000487 return Sema::TDK_Inconsistent;
488 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000489 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000490 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000491 }
492
Douglas Gregorf67875d2009-06-12 18:26:56 +0000493 // Set up the template argument deduction information for a failure.
John McCall833ca992009-10-29 08:12:44 +0000494 Info.FirstArg = TemplateArgument(ParamIn);
495 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000496
Douglas Gregor508f1c82009-06-26 23:10:12 +0000497 // Check the cv-qualifiers on the parameter and argument types.
498 if (!(TDF & TDF_IgnoreQualifiers)) {
499 if (TDF & TDF_ParamWithReferenceType) {
500 if (Param.isMoreQualifiedThan(Arg))
501 return Sema::TDK_NonDeducedMismatch;
John McCallcd05e812010-08-28 22:14:41 +0000502 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregor508f1c82009-06-26 23:10:12 +0000503 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump1eb44332009-09-09 15:08:12 +0000504 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor508f1c82009-06-26 23:10:12 +0000505 }
506 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000507
Douglas Gregord560d502009-06-04 00:21:18 +0000508 switch (Param->getTypeClass()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000509 // No deduction possible for these types
510 case Type::Builtin:
Douglas Gregorf67875d2009-06-12 18:26:56 +0000511 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregor199d9912009-06-05 00:53:49 +0000513 // T *
Douglas Gregord560d502009-06-04 00:21:18 +0000514 case Type::Pointer: {
John McCallc0008342010-05-13 07:48:05 +0000515 QualType PointeeType;
516 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
517 PointeeType = PointerArg->getPointeeType();
518 } else if (const ObjCObjectPointerType *PointerArg
519 = Arg->getAs<ObjCObjectPointerType>()) {
520 PointeeType = PointerArg->getPointeeType();
521 } else {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000522 return Sema::TDK_NonDeducedMismatch;
John McCallc0008342010-05-13 07:48:05 +0000523 }
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Douglas Gregor41128772009-06-26 23:27:24 +0000525 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000526 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000527 cast<PointerType>(Param)->getPointeeType(),
John McCallc0008342010-05-13 07:48:05 +0000528 PointeeType,
Douglas Gregor41128772009-06-26 23:27:24 +0000529 Info, Deduced, SubTDF);
Douglas Gregord560d502009-06-04 00:21:18 +0000530 }
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Douglas Gregor199d9912009-06-05 00:53:49 +0000532 // T &
Douglas Gregord560d502009-06-04 00:21:18 +0000533 case Type::LValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000534 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000535 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000536 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000538 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000539 cast<LValueReferenceType>(Param)->getPointeeType(),
540 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000541 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000542 }
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000543
Douglas Gregor199d9912009-06-05 00:53:49 +0000544 // T && [C++0x]
Douglas Gregord560d502009-06-04 00:21:18 +0000545 case Type::RValueReference: {
Ted Kremenek6217b802009-07-29 21:53:49 +0000546 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregord560d502009-06-04 00:21:18 +0000547 if (!ReferenceArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000548 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000550 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregord560d502009-06-04 00:21:18 +0000551 cast<RValueReferenceType>(Param)->getPointeeType(),
552 ReferenceArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000553 Info, Deduced, 0);
Douglas Gregord560d502009-06-04 00:21:18 +0000554 }
Mike Stump1eb44332009-09-09 15:08:12 +0000555
Douglas Gregor199d9912009-06-05 00:53:49 +0000556 // T [] (implied, but not stated explicitly)
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000557 case Type::IncompleteArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000558 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000559 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000560 if (!IncompleteArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000561 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000562
John McCalle4f26e52010-08-19 00:20:19 +0000563 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000564 return DeduceTemplateArguments(S, TemplateParams,
565 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000566 IncompleteArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000567 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000568 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000569
570 // T [integer-constant]
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000571 case Type::ConstantArray: {
Mike Stump1eb44332009-09-09 15:08:12 +0000572 const ConstantArrayType *ConstantArrayArg =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000573 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000574 if (!ConstantArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000575 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
577 const ConstantArrayType *ConstantArrayParm =
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000578 S.Context.getAsConstantArrayType(Param);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000579 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000580 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000581
John McCalle4f26e52010-08-19 00:20:19 +0000582 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000583 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000584 ConstantArrayParm->getElementType(),
585 ConstantArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000586 Info, Deduced, SubTDF);
Anders Carlsson4d6fb502009-06-04 04:11:30 +0000587 }
588
Douglas Gregor199d9912009-06-05 00:53:49 +0000589 // type [i]
590 case Type::DependentSizedArray: {
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000591 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregor199d9912009-06-05 00:53:49 +0000592 if (!ArrayArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000593 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000594
John McCalle4f26e52010-08-19 00:20:19 +0000595 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
596
Douglas Gregor199d9912009-06-05 00:53:49 +0000597 // Check the element type of the arrays
598 const DependentSizedArrayType *DependentArrayParm
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000599 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregorf67875d2009-06-12 18:26:56 +0000600 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000601 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000602 DependentArrayParm->getElementType(),
603 ArrayArg->getElementType(),
John McCalle4f26e52010-08-19 00:20:19 +0000604 Info, Deduced, SubTDF))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000605 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Douglas Gregor199d9912009-06-05 00:53:49 +0000607 // Determine the array bound is something we can deduce.
Mike Stump1eb44332009-09-09 15:08:12 +0000608 NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000609 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
610 if (!NTTP)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000611 return Sema::TDK_Success;
Mike Stump1eb44332009-09-09 15:08:12 +0000612
613 // We can perform template argument deduction for the given non-type
Douglas Gregor199d9912009-06-05 00:53:49 +0000614 // template parameter.
Mike Stump1eb44332009-09-09 15:08:12 +0000615 assert(NTTP->getDepth() == 0 &&
Douglas Gregor199d9912009-06-05 00:53:49 +0000616 "Cannot deduce non-type template argument at depth > 0");
Mike Stump1eb44332009-09-09 15:08:12 +0000617 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson335e24a2009-06-16 22:44:31 +0000618 = dyn_cast<ConstantArrayType>(ArrayArg)) {
619 llvm::APSInt Size(ConstantArrayArg->getSize());
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000620 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
621 S.Context.getSizeType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000622 /*ArrayBound=*/true,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000623 Info, Deduced);
Anders Carlsson335e24a2009-06-16 22:44:31 +0000624 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000625 if (const DependentSizedArrayType *DependentArrayArg
626 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000627 return DeduceNonTypeTemplateArgument(S, NTTP,
Douglas Gregor199d9912009-06-05 00:53:49 +0000628 DependentArrayArg->getSizeExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000629 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Douglas Gregor199d9912009-06-05 00:53:49 +0000631 // Incomplete type does not match a dependently-sized array type
Douglas Gregorf67875d2009-06-12 18:26:56 +0000632 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000633 }
Mike Stump1eb44332009-09-09 15:08:12 +0000634
635 // type(*)(T)
636 // T(*)()
637 // T(*)(T)
Anders Carlssona27fad52009-06-08 15:19:08 +0000638 case Type::FunctionProto: {
Mike Stump1eb44332009-09-09 15:08:12 +0000639 const FunctionProtoType *FunctionProtoArg =
Anders Carlssona27fad52009-06-08 15:19:08 +0000640 dyn_cast<FunctionProtoType>(Arg);
641 if (!FunctionProtoArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000642 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000643
644 const FunctionProtoType *FunctionProtoParam =
Anders Carlssona27fad52009-06-08 15:19:08 +0000645 cast<FunctionProtoType>(Param);
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000646
Mike Stump1eb44332009-09-09 15:08:12 +0000647 if (FunctionProtoParam->getTypeQuals() !=
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000648 FunctionProtoArg->getTypeQuals())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000649 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000650
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000651 if (FunctionProtoParam->getNumArgs() != FunctionProtoArg->getNumArgs())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000652 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000654 if (FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregorf67875d2009-06-12 18:26:56 +0000655 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson994b6cb2009-06-08 19:22:23 +0000656
Anders Carlssona27fad52009-06-08 15:19:08 +0000657 // Check return types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000658 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000659 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000660 FunctionProtoParam->getResultType(),
661 FunctionProtoArg->getResultType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000662 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000663 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Anders Carlssona27fad52009-06-08 15:19:08 +0000665 for (unsigned I = 0, N = FunctionProtoParam->getNumArgs(); I != N; ++I) {
666 // Check argument types.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000667 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000668 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000669 FunctionProtoParam->getArgType(I),
670 FunctionProtoArg->getArgType(I),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000671 Info, Deduced, 0))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000672 return Result;
Anders Carlssona27fad52009-06-08 15:19:08 +0000673 }
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Douglas Gregorf67875d2009-06-12 18:26:56 +0000675 return Sema::TDK_Success;
Anders Carlssona27fad52009-06-08 15:19:08 +0000676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
John McCall3cb0ebd2010-03-10 03:28:59 +0000678 case Type::InjectedClassName: {
679 // Treat a template's injected-class-name as if the template
680 // specialization type had been used.
John McCall31f17ec2010-04-27 00:57:59 +0000681 Param = cast<InjectedClassNameType>(Param)
682 ->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +0000683 assert(isa<TemplateSpecializationType>(Param) &&
684 "injected class name is not a template specialization type");
685 // fall through
686 }
687
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000688 // template-name<T> (where template-name refers to a class template)
Douglas Gregord708c722009-06-09 16:35:58 +0000689 // template-name<i>
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000690 // TT<T>
691 // TT<i>
692 // TT<>
Douglas Gregord708c722009-06-09 16:35:58 +0000693 case Type::TemplateSpecialization: {
694 const TemplateSpecializationType *SpecParam
695 = cast<TemplateSpecializationType>(Param);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000697 // Try to deduce template arguments from the template-id.
698 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000699 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000700 Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Douglas Gregor4a5c15f2009-09-30 22:13:51 +0000702 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000703 // C++ [temp.deduct.call]p3b3:
704 // If P is a class, and P has the form template-id, then A can be a
705 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump1eb44332009-09-09 15:08:12 +0000706 // class of the form template-id, A can be a pointer to a derived
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000707 // class pointed to by the deduced A.
708 //
709 // More importantly:
Mike Stump1eb44332009-09-09 15:08:12 +0000710 // These alternatives are considered only if type deduction would
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000711 // otherwise fail.
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000712 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
713 // We cannot inspect base classes as part of deduction when the type
714 // is incomplete, so either instantiate any templates necessary to
715 // complete the type, or skip over it if it cannot be completed.
John McCall5769d612010-02-08 23:07:23 +0000716 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000717 return Result;
718
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000719 // Use data recursion to crawl through the list of base classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000720 // Visited contains the set of nodes we have already visited, while
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000721 // ToVisit is our stack of records that we still need to visit.
722 llvm::SmallPtrSet<const RecordType *, 8> Visited;
723 llvm::SmallVector<const RecordType *, 8> ToVisit;
724 ToVisit.push_back(RecordT);
725 bool Successful = false;
Douglas Gregor053105d2010-11-02 00:02:34 +0000726 llvm::SmallVectorImpl<DeducedTemplateArgument> DeducedOrig(0);
727 DeducedOrig = Deduced;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000728 while (!ToVisit.empty()) {
729 // Retrieve the next class in the inheritance hierarchy.
730 const RecordType *NextT = ToVisit.back();
731 ToVisit.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000733 // If we have already seen this type, skip it.
734 if (!Visited.insert(NextT))
735 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000737 // If this is a base class, try to perform template argument
738 // deduction from it.
739 if (NextT != RecordT) {
740 Sema::TemplateDeductionResult BaseResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000741 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000742 QualType(NextT, 0), Info, Deduced);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000744 // If template argument deduction for this base was successful,
Douglas Gregor053105d2010-11-02 00:02:34 +0000745 // note that we had some success. Otherwise, ignore any deductions
746 // from this base class.
747 if (BaseResult == Sema::TDK_Success) {
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000748 Successful = true;
Douglas Gregor053105d2010-11-02 00:02:34 +0000749 DeducedOrig = Deduced;
750 }
751 else
752 Deduced = DeducedOrig;
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000753 }
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000755 // Visit base classes
756 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
757 for (CXXRecordDecl::base_class_iterator Base = Next->bases_begin(),
758 BaseEnd = Next->bases_end();
Sebastian Redl9994a342009-10-25 17:03:50 +0000759 Base != BaseEnd; ++Base) {
Mike Stump1eb44332009-09-09 15:08:12 +0000760 assert(Base->getType()->isRecordType() &&
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000761 "Base class that isn't a record?");
Ted Kremenek6217b802009-07-29 21:53:49 +0000762 ToVisit.push_back(Base->getType()->getAs<RecordType>());
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000763 }
764 }
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000766 if (Successful)
767 return Sema::TDK_Success;
768 }
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000770 }
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Douglas Gregorde0cb8b2009-07-07 23:09:34 +0000772 return Result;
Douglas Gregord708c722009-06-09 16:35:58 +0000773 }
774
Douglas Gregor637a4092009-06-10 23:47:09 +0000775 // T type::*
776 // T T::*
777 // T (type::*)()
778 // type (T::*)()
779 // type (type::*)(T)
780 // type (T::*)(T)
781 // T (type::*)(T)
782 // T (T::*)()
783 // T (T::*)(T)
784 case Type::MemberPointer: {
785 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
786 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
787 if (!MemPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000788 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637a4092009-06-10 23:47:09 +0000789
Douglas Gregorf67875d2009-06-12 18:26:56 +0000790 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000791 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000792 MemPtrParam->getPointeeType(),
793 MemPtrArg->getPointeeType(),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000794 Info, Deduced,
795 TDF & TDF_IgnoreQualifiers))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000796 return Result;
797
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000798 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000799 QualType(MemPtrParam->getClass(), 0),
800 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor508f1c82009-06-26 23:10:12 +0000801 Info, Deduced, 0);
Douglas Gregor637a4092009-06-10 23:47:09 +0000802 }
803
Anders Carlsson9a917e42009-06-12 22:56:54 +0000804 // (clang extension)
805 //
Mike Stump1eb44332009-09-09 15:08:12 +0000806 // type(^)(T)
807 // T(^)()
808 // T(^)(T)
Anders Carlsson859ba502009-06-12 16:23:10 +0000809 case Type::BlockPointer: {
810 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
811 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Anders Carlsson859ba502009-06-12 16:23:10 +0000813 if (!BlockPtrArg)
Douglas Gregorf67875d2009-06-12 18:26:56 +0000814 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000816 return DeduceTemplateArguments(S, TemplateParams,
Anders Carlsson859ba502009-06-12 16:23:10 +0000817 BlockPtrParam->getPointeeType(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000818 BlockPtrArg->getPointeeType(), Info,
Douglas Gregor508f1c82009-06-26 23:10:12 +0000819 Deduced, 0);
Anders Carlsson859ba502009-06-12 16:23:10 +0000820 }
821
Douglas Gregor637a4092009-06-10 23:47:09 +0000822 case Type::TypeOfExpr:
823 case Type::TypeOf:
Douglas Gregor4714c122010-03-31 17:34:00 +0000824 case Type::DependentName:
Douglas Gregor637a4092009-06-10 23:47:09 +0000825 // No template argument deduction for these types
Douglas Gregorf67875d2009-06-12 18:26:56 +0000826 return Sema::TDK_Success;
Douglas Gregor637a4092009-06-10 23:47:09 +0000827
Douglas Gregord560d502009-06-04 00:21:18 +0000828 default:
829 break;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000830 }
831
832 // FIXME: Many more cases to go (to go).
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000833 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000834}
835
Douglas Gregorf67875d2009-06-12 18:26:56 +0000836static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000837DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000838 TemplateParameterList *TemplateParams,
839 const TemplateArgument &Param,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000840 const TemplateArgument &Arg,
John McCall2a7fb272010-08-25 05:32:35 +0000841 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000842 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000843 switch (Param.getKind()) {
Douglas Gregor199d9912009-06-05 00:53:49 +0000844 case TemplateArgument::Null:
845 assert(false && "Null template argument in parameter list");
846 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000847
848 case TemplateArgument::Type:
Douglas Gregor788cd062009-11-11 01:00:40 +0000849 if (Arg.getKind() == TemplateArgument::Type)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000850 return DeduceTemplateArguments(S, TemplateParams, Param.getAsType(),
Douglas Gregor788cd062009-11-11 01:00:40 +0000851 Arg.getAsType(), Info, Deduced, 0);
852 Info.FirstArg = Param;
853 Info.SecondArg = Arg;
854 return Sema::TDK_NonDeducedMismatch;
855
856 case TemplateArgument::Template:
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000857 if (Arg.getKind() == TemplateArgument::Template)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000858 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor788cd062009-11-11 01:00:40 +0000859 Param.getAsTemplate(),
Douglas Gregordb0d4b72009-11-11 23:06:43 +0000860 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor788cd062009-11-11 01:00:40 +0000861 Info.FirstArg = Param;
862 Info.SecondArg = Arg;
863 return Sema::TDK_NonDeducedMismatch;
864
Douglas Gregor199d9912009-06-05 00:53:49 +0000865 case TemplateArgument::Declaration:
Douglas Gregor788cd062009-11-11 01:00:40 +0000866 if (Arg.getKind() == TemplateArgument::Declaration &&
867 Param.getAsDecl()->getCanonicalDecl() ==
868 Arg.getAsDecl()->getCanonicalDecl())
869 return Sema::TDK_Success;
870
Douglas Gregorf67875d2009-06-12 18:26:56 +0000871 Info.FirstArg = Param;
872 Info.SecondArg = Arg;
873 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Douglas Gregor199d9912009-06-05 00:53:49 +0000875 case TemplateArgument::Integral:
876 if (Arg.getKind() == TemplateArgument::Integral) {
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000877 if (hasSameExtendedValue(*Param.getAsIntegral(), *Arg.getAsIntegral()))
Douglas Gregorf67875d2009-06-12 18:26:56 +0000878 return Sema::TDK_Success;
879
880 Info.FirstArg = Param;
881 Info.SecondArg = Arg;
882 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000883 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000884
885 if (Arg.getKind() == TemplateArgument::Expression) {
886 Info.FirstArg = Param;
887 Info.SecondArg = Arg;
888 return Sema::TDK_NonDeducedMismatch;
889 }
Douglas Gregor199d9912009-06-05 00:53:49 +0000890
Douglas Gregorf67875d2009-06-12 18:26:56 +0000891 Info.FirstArg = Param;
892 Info.SecondArg = Arg;
893 return Sema::TDK_NonDeducedMismatch;
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Douglas Gregor199d9912009-06-05 00:53:49 +0000895 case TemplateArgument::Expression: {
Mike Stump1eb44332009-09-09 15:08:12 +0000896 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor199d9912009-06-05 00:53:49 +0000897 = getDeducedParameterFromExpr(Param.getAsExpr())) {
898 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000899 return DeduceNonTypeTemplateArgument(S, NTTP,
Mike Stump1eb44332009-09-09 15:08:12 +0000900 *Arg.getAsIntegral(),
Douglas Gregor9d0e4412010-03-26 05:50:28 +0000901 Arg.getIntegralType(),
Douglas Gregor02024a92010-03-28 02:42:43 +0000902 /*ArrayBound=*/false,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000903 Info, Deduced);
Douglas Gregor199d9912009-06-05 00:53:49 +0000904 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000905 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregorf67875d2009-06-12 18:26:56 +0000906 Info, Deduced);
Douglas Gregor15755cb2009-11-13 23:45:44 +0000907 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000908 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor15755cb2009-11-13 23:45:44 +0000909 Info, Deduced);
910
Douglas Gregorf67875d2009-06-12 18:26:56 +0000911 Info.FirstArg = Param;
912 Info.SecondArg = Arg;
913 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor199d9912009-06-05 00:53:49 +0000914 }
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregor199d9912009-06-05 00:53:49 +0000916 // Can't deduce anything, but that's okay.
Douglas Gregorf67875d2009-06-12 18:26:56 +0000917 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000918 }
Anders Carlssond01b1da2009-06-15 17:04:53 +0000919 case TemplateArgument::Pack:
920 assert(0 && "FIXME: Implement!");
921 break;
Douglas Gregor199d9912009-06-05 00:53:49 +0000922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Douglas Gregorf67875d2009-06-12 18:26:56 +0000924 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000925}
926
Mike Stump1eb44332009-09-09 15:08:12 +0000927static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000928DeduceTemplateArguments(Sema &S,
Douglas Gregorf67875d2009-06-12 18:26:56 +0000929 TemplateParameterList *TemplateParams,
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000930 const TemplateArgumentList &ParamList,
931 const TemplateArgumentList &ArgList,
John McCall2a7fb272010-08-25 05:32:35 +0000932 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +0000933 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000934 assert(ParamList.size() == ArgList.size());
935 for (unsigned I = 0, N = ParamList.size(); I != N; ++I) {
Douglas Gregorf67875d2009-06-12 18:26:56 +0000936 if (Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +0000937 = DeduceTemplateArguments(S, TemplateParams,
Mike Stump1eb44332009-09-09 15:08:12 +0000938 ParamList[I], ArgList[I],
Douglas Gregorf67875d2009-06-12 18:26:56 +0000939 Info, Deduced))
940 return Result;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000941 }
Douglas Gregorf67875d2009-06-12 18:26:56 +0000942 return Sema::TDK_Success;
Douglas Gregor0b9247f2009-06-04 00:03:07 +0000943}
944
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000945/// \brief Determine whether two template arguments are the same.
Mike Stump1eb44332009-09-09 15:08:12 +0000946static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000947 const TemplateArgument &X,
948 const TemplateArgument &Y) {
949 if (X.getKind() != Y.getKind())
950 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000952 switch (X.getKind()) {
953 case TemplateArgument::Null:
954 assert(false && "Comparing NULL template argument");
955 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000957 case TemplateArgument::Type:
958 return Context.getCanonicalType(X.getAsType()) ==
959 Context.getCanonicalType(Y.getAsType());
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000961 case TemplateArgument::Declaration:
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +0000962 return X.getAsDecl()->getCanonicalDecl() ==
963 Y.getAsDecl()->getCanonicalDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Douglas Gregor788cd062009-11-11 01:00:40 +0000965 case TemplateArgument::Template:
966 return Context.getCanonicalTemplateName(X.getAsTemplate())
967 .getAsVoidPointer() ==
968 Context.getCanonicalTemplateName(Y.getAsTemplate())
969 .getAsVoidPointer();
970
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000971 case TemplateArgument::Integral:
972 return *X.getAsIntegral() == *Y.getAsIntegral();
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Douglas Gregor788cd062009-11-11 01:00:40 +0000974 case TemplateArgument::Expression: {
975 llvm::FoldingSetNodeID XID, YID;
976 X.getAsExpr()->Profile(XID, Context, true);
977 Y.getAsExpr()->Profile(YID, Context, true);
978 return XID == YID;
979 }
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000981 case TemplateArgument::Pack:
982 if (X.pack_size() != Y.pack_size())
983 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000984
985 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
986 XPEnd = X.pack_end(),
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000987 YP = Y.pack_begin();
Mike Stump1eb44332009-09-09 15:08:12 +0000988 XP != XPEnd; ++XP, ++YP)
Douglas Gregorf670c8c2009-06-26 20:57:09 +0000989 if (!isSameTemplateArg(Context, *XP, *YP))
990 return false;
991
992 return true;
993 }
994
995 return false;
996}
997
998/// \brief Helper function to build a TemplateParameter when we don't
999/// know its type statically.
1000static TemplateParameter makeTemplateParameter(Decl *D) {
1001 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
1002 return TemplateParameter(TTP);
1003 else if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
1004 return TemplateParameter(NTTP);
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Douglas Gregorf670c8c2009-06-26 20:57:09 +00001006 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
1007}
1008
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001009/// Complete template argument deduction for a class template partial
1010/// specialization.
1011static Sema::TemplateDeductionResult
1012FinishTemplateArgumentDeduction(Sema &S,
1013 ClassTemplatePartialSpecializationDecl *Partial,
1014 const TemplateArgumentList &TemplateArgs,
1015 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall2a7fb272010-08-25 05:32:35 +00001016 TemplateDeductionInfo &Info) {
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001017 // Trap errors.
1018 Sema::SFINAETrap Trap(S);
1019
1020 Sema::ContextRAII SavedContext(S, Partial);
1021
1022 // C++ [temp.deduct.type]p2:
1023 // [...] or if any template argument remains neither deduced nor
1024 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001025 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001026 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
1027 if (Deduced[I].isNull()) {
1028 Decl *Param
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001029 = const_cast<NamedDecl *>(
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001030 Partial->getTemplateParameters()->getParam(I));
1031 Info.Param = makeTemplateParameter(Param);
1032 return Sema::TDK_Incomplete;
1033 }
1034
Douglas Gregor910f8002010-11-07 23:05:16 +00001035 Builder.push_back(Deduced[I]);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001036 }
1037
1038 // Form the template argument list from the deduced template arguments.
1039 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001040 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
1041 Builder.size());
1042
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001043 Info.reset(DeducedArgumentList);
1044
1045 // Substitute the deduced template arguments into the template
1046 // arguments of the class template partial specialization, and
1047 // verify that the instantiated template arguments are both valid
1048 // and are equivalent to the template arguments originally provided
1049 // to the class template.
1050 // FIXME: Do we have to correct the types of deduced non-type template
1051 // arguments (in particular, integral non-type template arguments?).
John McCall2a7fb272010-08-25 05:32:35 +00001052 LocalInstantiationScope InstScope(S);
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001053 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
1054 const TemplateArgumentLoc *PartialTemplateArgs
1055 = Partial->getTemplateArgsAsWritten();
1056 unsigned N = Partial->getNumTemplateArgsAsWritten();
1057
1058 // Note that we don't provide the langle and rangle locations.
1059 TemplateArgumentListInfo InstArgs;
1060
1061 for (unsigned I = 0; I != N; ++I) {
1062 Decl *Param = const_cast<NamedDecl *>(
1063 ClassTemplate->getTemplateParameters()->getParam(I));
1064 TemplateArgumentLoc InstArg;
1065 if (S.Subst(PartialTemplateArgs[I], InstArg,
1066 MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
1067 Info.Param = makeTemplateParameter(Param);
1068 Info.FirstArg = PartialTemplateArgs[I].getArgument();
1069 return Sema::TDK_SubstitutionFailure;
1070 }
1071 InstArgs.addArgument(InstArg);
1072 }
1073
Douglas Gregor910f8002010-11-07 23:05:16 +00001074 llvm::SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001075 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorec20f462010-05-08 20:07:26 +00001076 InstArgs, false, ConvertedInstArgs))
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001077 return Sema::TDK_SubstitutionFailure;
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001078
Douglas Gregor910f8002010-11-07 23:05:16 +00001079 for (unsigned I = 0, E = ConvertedInstArgs.size(); I != E; ++I) {
1080 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001081
1082 Decl *Param = const_cast<NamedDecl *>(
1083 ClassTemplate->getTemplateParameters()->getParam(I));
1084
1085 if (InstArg.getKind() == TemplateArgument::Expression) {
1086 // When the argument is an expression, check the expression result
1087 // against the actual template parameter to get down to the canonical
1088 // template argument.
1089 Expr *InstExpr = InstArg.getAsExpr();
1090 if (NonTypeTemplateParmDecl *NTTP
1091 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1092 if (S.CheckTemplateArgument(NTTP, NTTP->getType(), InstExpr, InstArg)) {
1093 Info.Param = makeTemplateParameter(Param);
1094 Info.FirstArg = Partial->getTemplateArgs()[I];
1095 return Sema::TDK_SubstitutionFailure;
1096 }
1097 }
1098 }
1099
1100 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
1101 Info.Param = makeTemplateParameter(Param);
1102 Info.FirstArg = TemplateArgs[I];
1103 Info.SecondArg = InstArg;
1104 return Sema::TDK_NonDeducedMismatch;
1105 }
1106 }
1107
1108 if (Trap.hasErrorOccurred())
1109 return Sema::TDK_SubstitutionFailure;
1110
1111 return Sema::TDK_Success;
1112}
1113
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001114/// \brief Perform template argument deduction to determine whether
1115/// the given template arguments match the given class template
1116/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregorf67875d2009-06-12 18:26:56 +00001117Sema::TemplateDeductionResult
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001118Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001119 const TemplateArgumentList &TemplateArgs,
1120 TemplateDeductionInfo &Info) {
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001121 // C++ [temp.class.spec.match]p2:
1122 // A partial specialization matches a given actual template
1123 // argument list if the template arguments of the partial
1124 // specialization can be deduced from the actual template argument
1125 // list (14.8.2).
Douglas Gregorbb260412009-06-14 08:02:22 +00001126 SFINAETrap Trap(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001127 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001128 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregorf67875d2009-06-12 18:26:56 +00001129 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001130 = ::DeduceTemplateArguments(*this,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001131 Partial->getTemplateParameters(),
Mike Stump1eb44332009-09-09 15:08:12 +00001132 Partial->getTemplateArgs(),
Douglas Gregorf67875d2009-06-12 18:26:56 +00001133 TemplateArgs, Info, Deduced))
1134 return Result;
Douglas Gregor637a4092009-06-10 23:47:09 +00001135
Douglas Gregor637a4092009-06-10 23:47:09 +00001136 InstantiatingTemplate Inst(*this, Partial->getLocation(), Partial,
Douglas Gregor9b623632010-10-12 23:32:35 +00001137 Deduced.data(), Deduced.size(), Info);
Douglas Gregor637a4092009-06-10 23:47:09 +00001138 if (Inst)
Douglas Gregorf67875d2009-06-12 18:26:56 +00001139 return TDK_InstantiationDepth;
Douglas Gregor199d9912009-06-05 00:53:49 +00001140
Douglas Gregorbb260412009-06-14 08:02:22 +00001141 if (Trap.hasErrorOccurred())
Douglas Gregor31dce8f2010-04-29 06:21:43 +00001142 return Sema::TDK_SubstitutionFailure;
1143
1144 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
1145 Deduced, Info);
Douglas Gregor0b9247f2009-06-04 00:03:07 +00001146}
Douglas Gregor031a5882009-06-13 00:26:55 +00001147
Douglas Gregor41128772009-06-26 23:27:24 +00001148/// \brief Determine whether the given type T is a simple-template-id type.
1149static bool isSimpleTemplateIdType(QualType T) {
Mike Stump1eb44332009-09-09 15:08:12 +00001150 if (const TemplateSpecializationType *Spec
John McCall183700f2009-09-21 23:43:11 +00001151 = T->getAs<TemplateSpecializationType>())
Douglas Gregor41128772009-06-26 23:27:24 +00001152 return Spec->getTemplateName().getAsTemplateDecl() != 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Douglas Gregor41128772009-06-26 23:27:24 +00001154 return false;
1155}
Douglas Gregor83314aa2009-07-08 20:55:45 +00001156
1157/// \brief Substitute the explicitly-provided template arguments into the
1158/// given function template according to C++ [temp.arg.explicit].
1159///
1160/// \param FunctionTemplate the function template into which the explicit
1161/// template arguments will be substituted.
1162///
Mike Stump1eb44332009-09-09 15:08:12 +00001163/// \param ExplicitTemplateArguments the explicitly-specified template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001164/// arguments.
1165///
Mike Stump1eb44332009-09-09 15:08:12 +00001166/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor83314aa2009-07-08 20:55:45 +00001167/// with the converted and checked explicit template arguments.
1168///
Mike Stump1eb44332009-09-09 15:08:12 +00001169/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor83314aa2009-07-08 20:55:45 +00001170/// parameters.
1171///
1172/// \param FunctionType if non-NULL, the result type of the function template
1173/// will also be instantiated and the pointed-to value will be updated with
1174/// the instantiated function type.
1175///
1176/// \param Info if substitution fails for any reason, this object will be
1177/// populated with more information about the failure.
1178///
1179/// \returns TDK_Success if substitution was successful, or some failure
1180/// condition.
1181Sema::TemplateDeductionResult
1182Sema::SubstituteExplicitTemplateArguments(
1183 FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001184 const TemplateArgumentListInfo &ExplicitTemplateArgs,
Douglas Gregor02024a92010-03-28 02:42:43 +00001185 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001186 llvm::SmallVectorImpl<QualType> &ParamTypes,
1187 QualType *FunctionType,
1188 TemplateDeductionInfo &Info) {
1189 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1190 TemplateParameterList *TemplateParams
1191 = FunctionTemplate->getTemplateParameters();
1192
John McCalld5532b62009-11-23 01:53:49 +00001193 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001194 // No arguments to substitute; just copy over the parameter types and
1195 // fill in the function type.
1196 for (FunctionDecl::param_iterator P = Function->param_begin(),
1197 PEnd = Function->param_end();
1198 P != PEnd;
1199 ++P)
1200 ParamTypes.push_back((*P)->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Douglas Gregor83314aa2009-07-08 20:55:45 +00001202 if (FunctionType)
1203 *FunctionType = Function->getType();
1204 return TDK_Success;
1205 }
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Douglas Gregor83314aa2009-07-08 20:55:45 +00001207 // Substitution of the explicit template arguments into a function template
1208 /// is a SFINAE context. Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001209 SFINAETrap Trap(*this);
1210
Douglas Gregor83314aa2009-07-08 20:55:45 +00001211 // C++ [temp.arg.explicit]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001212 // Template arguments that are present shall be specified in the
1213 // declaration order of their corresponding template-parameters. The
Douglas Gregor83314aa2009-07-08 20:55:45 +00001214 // template argument list shall not specify more template-arguments than
Mike Stump1eb44332009-09-09 15:08:12 +00001215 // there are corresponding template-parameters.
Douglas Gregor910f8002010-11-07 23:05:16 +00001216 llvm::SmallVector<TemplateArgument, 4> Builder;
Mike Stump1eb44332009-09-09 15:08:12 +00001217
1218 // Enter a new template instantiation context where we check the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001219 // explicitly-specified template arguments against this function template,
1220 // and then substitute them into the function parameter types.
Mike Stump1eb44332009-09-09 15:08:12 +00001221 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001222 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001223 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
1224 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001225 if (Inst)
1226 return TDK_InstantiationDepth;
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregor83314aa2009-07-08 20:55:45 +00001228 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001229 SourceLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001230 ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001231 true,
Douglas Gregorf1a84452010-05-08 19:15:54 +00001232 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001233 unsigned Index = Builder.size();
Douglas Gregorfe52c912010-05-09 01:26:06 +00001234 if (Index >= TemplateParams->size())
1235 Index = TemplateParams->size() - 1;
1236 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001237 return TDK_InvalidExplicitArguments;
Douglas Gregorf1a84452010-05-08 19:15:54 +00001238 }
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Douglas Gregor83314aa2009-07-08 20:55:45 +00001240 // Form the template argument list from the explicitly-specified
1241 // template arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00001242 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001243 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001244 Info.reset(ExplicitArgumentList);
Mike Stump1eb44332009-09-09 15:08:12 +00001245
John McCalldf41f182010-10-12 19:40:14 +00001246 // Template argument deduction and the final substitution should be
1247 // done in the context of the templated declaration. Explicit
1248 // argument substitution, on the other hand, needs to happen in the
1249 // calling context.
1250 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
1251
Douglas Gregor83314aa2009-07-08 20:55:45 +00001252 // Instantiate the types of each of the function parameters given the
1253 // explicitly-specified template arguments.
1254 for (FunctionDecl::param_iterator P = Function->param_begin(),
1255 PEnd = Function->param_end();
1256 P != PEnd;
1257 ++P) {
Mike Stump1eb44332009-09-09 15:08:12 +00001258 QualType ParamType
1259 = SubstType((*P)->getType(),
Douglas Gregor357bbd02009-08-28 20:50:45 +00001260 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1261 (*P)->getLocation(), (*P)->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001262 if (ParamType.isNull() || Trap.hasErrorOccurred())
1263 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Douglas Gregor83314aa2009-07-08 20:55:45 +00001265 ParamTypes.push_back(ParamType);
1266 }
1267
1268 // If the caller wants a full function type back, instantiate the return
1269 // type and form that function type.
1270 if (FunctionType) {
1271 // FIXME: exception-specifications?
Mike Stump1eb44332009-09-09 15:08:12 +00001272 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001273 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001274 assert(Proto && "Function template does not have a prototype?");
Mike Stump1eb44332009-09-09 15:08:12 +00001275
1276 QualType ResultType
Douglas Gregor357bbd02009-08-28 20:50:45 +00001277 = SubstType(Proto->getResultType(),
1278 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
1279 Function->getTypeSpecStartLoc(),
1280 Function->getDeclName());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001281 if (ResultType.isNull() || Trap.hasErrorOccurred())
1282 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001283
1284 *FunctionType = BuildFunctionType(ResultType,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001285 ParamTypes.data(), ParamTypes.size(),
1286 Proto->isVariadic(),
1287 Proto->getTypeQuals(),
1288 Function->getLocation(),
Eli Friedmanfa869542010-08-05 02:54:05 +00001289 Function->getDeclName(),
1290 Proto->getExtInfo());
Douglas Gregor83314aa2009-07-08 20:55:45 +00001291 if (FunctionType->isNull() || Trap.hasErrorOccurred())
1292 return TDK_SubstitutionFailure;
1293 }
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Douglas Gregor83314aa2009-07-08 20:55:45 +00001295 // C++ [temp.arg.explicit]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00001296 // Trailing template arguments that can be deduced (14.8.2) may be
1297 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor83314aa2009-07-08 20:55:45 +00001298 // template arguments can be deduced, they may all be omitted; in this
1299 // case, the empty template argument list <> itself may also be omitted.
1300 //
1301 // Take all of the explicitly-specified arguments and put them into the
Mike Stump1eb44332009-09-09 15:08:12 +00001302 // set of deduced template arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001303 Deduced.reserve(TemplateParams->size());
1304 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I)
Mike Stump1eb44332009-09-09 15:08:12 +00001305 Deduced.push_back(ExplicitArgumentList->get(I));
1306
Douglas Gregor83314aa2009-07-08 20:55:45 +00001307 return TDK_Success;
1308}
1309
Douglas Gregor02024a92010-03-28 02:42:43 +00001310/// \brief Allocate a TemplateArgumentLoc where all locations have
1311/// been initialized to the given location.
1312///
1313/// \param S The semantic analysis object.
1314///
1315/// \param The template argument we are producing template argument
1316/// location information for.
1317///
1318/// \param NTTPType For a declaration template argument, the type of
1319/// the non-type template parameter that corresponds to this template
1320/// argument.
1321///
1322/// \param Loc The source location to use for the resulting template
1323/// argument.
1324static TemplateArgumentLoc
1325getTrivialTemplateArgumentLoc(Sema &S,
1326 const TemplateArgument &Arg,
1327 QualType NTTPType,
1328 SourceLocation Loc) {
1329 switch (Arg.getKind()) {
1330 case TemplateArgument::Null:
1331 llvm_unreachable("Can't get a NULL template argument here");
1332 break;
1333
1334 case TemplateArgument::Type:
1335 return TemplateArgumentLoc(Arg,
1336 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
1337
1338 case TemplateArgument::Declaration: {
1339 Expr *E
1340 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
1341 .takeAs<Expr>();
1342 return TemplateArgumentLoc(TemplateArgument(E), E);
1343 }
1344
1345 case TemplateArgument::Integral: {
1346 Expr *E
1347 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).takeAs<Expr>();
1348 return TemplateArgumentLoc(TemplateArgument(E), E);
1349 }
1350
1351 case TemplateArgument::Template:
1352 return TemplateArgumentLoc(Arg, SourceRange(), Loc);
1353
1354 case TemplateArgument::Expression:
1355 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
1356
1357 case TemplateArgument::Pack:
1358 llvm_unreachable("Template parameter packs are not yet supported");
1359 }
1360
1361 return TemplateArgumentLoc();
1362}
1363
Mike Stump1eb44332009-09-09 15:08:12 +00001364/// \brief Finish template argument deduction for a function template,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001365/// checking the deduced template arguments for completeness and forming
1366/// the function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00001367Sema::TemplateDeductionResult
Douglas Gregor83314aa2009-07-08 20:55:45 +00001368Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor02024a92010-03-28 02:42:43 +00001369 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1370 unsigned NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001371 FunctionDecl *&Specialization,
1372 TemplateDeductionInfo &Info) {
1373 TemplateParameterList *TemplateParams
1374 = FunctionTemplate->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Douglas Gregor83314aa2009-07-08 20:55:45 +00001376 // Template argument deduction for function templates in a SFINAE context.
1377 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001378 SFINAETrap Trap(*this);
1379
Douglas Gregor83314aa2009-07-08 20:55:45 +00001380 // Enter a new template instantiation context while we instantiate the
1381 // actual function declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00001382 InstantiatingTemplate Inst(*this, FunctionTemplate->getLocation(),
Douglas Gregor83314aa2009-07-08 20:55:45 +00001383 FunctionTemplate, Deduced.data(), Deduced.size(),
Douglas Gregor9b623632010-10-12 23:32:35 +00001384 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
1385 Info);
Douglas Gregor83314aa2009-07-08 20:55:45 +00001386 if (Inst)
Mike Stump1eb44332009-09-09 15:08:12 +00001387 return TDK_InstantiationDepth;
1388
John McCall96db3102010-04-29 01:18:58 +00001389 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCallf5813822010-04-29 00:35:03 +00001390
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001391 // C++ [temp.deduct.type]p2:
1392 // [...] or if any template argument remains neither deduced nor
1393 // explicitly specified, template argument deduction fails.
Douglas Gregor910f8002010-11-07 23:05:16 +00001394 llvm::SmallVector<TemplateArgument, 4> Builder;
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001395 for (unsigned I = 0, N = Deduced.size(); I != N; ++I) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001396 NamedDecl *Param = FunctionTemplate->getTemplateParameters()->getParam(I);
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001397 if (!Deduced[I].isNull()) {
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001398 if (I < NumExplicitlySpecified) {
Douglas Gregor02024a92010-03-28 02:42:43 +00001399 // We have already fully type-checked and converted this
Douglas Gregor3273b0c2010-10-12 18:51:08 +00001400 // argument, because it was explicitly-specified. Just record the
1401 // presence of this argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001402 Builder.push_back(Deduced[I]);
Douglas Gregor02024a92010-03-28 02:42:43 +00001403 continue;
1404 }
1405
1406 // We have deduced this argument, so it still needs to be
1407 // checked and converted.
1408
1409 // First, for a non-type template parameter type that is
1410 // initialized by a declaration, we need the type of the
1411 // corresponding non-type template parameter.
1412 QualType NTTPType;
1413 if (NonTypeTemplateParmDecl *NTTP
1414 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1415 if (Deduced[I].getKind() == TemplateArgument::Declaration) {
1416 NTTPType = NTTP->getType();
1417 if (NTTPType->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001418 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1419 Builder.data(), Builder.size());
Douglas Gregor02024a92010-03-28 02:42:43 +00001420 NTTPType = SubstType(NTTPType,
1421 MultiLevelTemplateArgumentList(TemplateArgs),
1422 NTTP->getLocation(),
1423 NTTP->getDeclName());
1424 if (NTTPType.isNull()) {
1425 Info.Param = makeTemplateParameter(Param);
Douglas Gregor910f8002010-11-07 23:05:16 +00001426 // FIXME: These template arguments are temporary. Free them!
1427 Info.reset(TemplateArgumentList::CreateCopy(Context,
1428 Builder.data(),
1429 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001430 return TDK_SubstitutionFailure;
1431 }
1432 }
1433 }
1434 }
1435
1436 // Convert the deduced template argument into a template
1437 // argument that we can check, almost as if the user had written
1438 // the template argument explicitly.
1439 TemplateArgumentLoc Arg = getTrivialTemplateArgumentLoc(*this,
1440 Deduced[I],
1441 NTTPType,
Douglas Gregor9b623632010-10-12 23:32:35 +00001442 Info.getLocation());
Douglas Gregor02024a92010-03-28 02:42:43 +00001443
1444 // Check the template argument, converting it as necessary.
1445 if (CheckTemplateArgument(Param, Arg,
1446 FunctionTemplate,
1447 FunctionTemplate->getLocation(),
1448 FunctionTemplate->getSourceRange().getEnd(),
1449 Builder,
1450 Deduced[I].wasDeducedFromArrayBound()
1451 ? CTAK_DeducedFromArrayBound
1452 : CTAK_Deduced)) {
1453 Info.Param = makeTemplateParameter(
1454 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001455 // FIXME: These template arguments are temporary. Free them!
1456 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1457 Builder.size()));
Douglas Gregor02024a92010-03-28 02:42:43 +00001458 return TDK_SubstitutionFailure;
1459 }
1460
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001461 continue;
1462 }
1463
1464 // Substitute into the default template argument, if available.
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001465 TemplateArgumentLoc DefArg
1466 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
1467 FunctionTemplate->getLocation(),
1468 FunctionTemplate->getSourceRange().getEnd(),
1469 Param,
1470 Builder);
1471
1472 // If there was no default argument, deduction is incomplete.
1473 if (DefArg.getArgument().isNull()) {
1474 Info.Param = makeTemplateParameter(
1475 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
1476 return TDK_Incomplete;
1477 }
1478
1479 // Check whether we can actually use the default argument.
1480 if (CheckTemplateArgument(Param, DefArg,
1481 FunctionTemplate,
1482 FunctionTemplate->getLocation(),
1483 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor02024a92010-03-28 02:42:43 +00001484 Builder,
1485 CTAK_Deduced)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001486 Info.Param = makeTemplateParameter(
1487 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor910f8002010-11-07 23:05:16 +00001488 // FIXME: These template arguments are temporary. Free them!
1489 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
1490 Builder.size()));
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001491 return TDK_SubstitutionFailure;
1492 }
1493
1494 // If we get here, we successfully used the default template argument.
1495 }
1496
1497 // Form the template argument list from the deduced template arguments.
1498 TemplateArgumentList *DeducedArgumentList
Douglas Gregor910f8002010-11-07 23:05:16 +00001499 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001500 Info.reset(DeducedArgumentList);
1501
Mike Stump1eb44332009-09-09 15:08:12 +00001502 // Substitute the deduced template arguments into the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001503 // declaration to produce the function template specialization.
Douglas Gregord4598a22010-04-28 04:52:24 +00001504 DeclContext *Owner = FunctionTemplate->getDeclContext();
1505 if (FunctionTemplate->getFriendObjectKind())
1506 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001507 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregord4598a22010-04-28 04:52:24 +00001508 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor357bbd02009-08-28 20:50:45 +00001509 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregor83314aa2009-07-08 20:55:45 +00001510 if (!Specialization)
1511 return TDK_SubstitutionFailure;
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Douglas Gregorf8825742009-09-15 18:26:13 +00001513 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
1514 FunctionTemplate->getCanonicalDecl());
1515
Mike Stump1eb44332009-09-09 15:08:12 +00001516 // If the template argument list is owned by the function template
Douglas Gregor83314aa2009-07-08 20:55:45 +00001517 // specialization, release it.
Douglas Gregorec20f462010-05-08 20:07:26 +00001518 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
1519 !Trap.hasErrorOccurred())
Douglas Gregor83314aa2009-07-08 20:55:45 +00001520 Info.take();
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Douglas Gregor83314aa2009-07-08 20:55:45 +00001522 // There may have been an error that did not prevent us from constructing a
1523 // declaration. Mark the declaration invalid and return with a substitution
1524 // failure.
1525 if (Trap.hasErrorOccurred()) {
1526 Specialization->setInvalidDecl(true);
1527 return TDK_SubstitutionFailure;
1528 }
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Douglas Gregor9b623632010-10-12 23:32:35 +00001530 // If we suppressed any diagnostics while performing template argument
1531 // deduction, and if we haven't already instantiated this declaration,
1532 // keep track of these diagnostics. They'll be emitted if this specialization
1533 // is actually used.
1534 if (Info.diag_begin() != Info.diag_end()) {
1535 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
1536 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
1537 if (Pos == SuppressedDiagnostics.end())
1538 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
1539 .append(Info.diag_begin(), Info.diag_end());
1540 }
1541
Mike Stump1eb44332009-09-09 15:08:12 +00001542 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001543}
1544
John McCall9c72c602010-08-27 09:08:28 +00001545/// Gets the type of a function for template-argument-deducton
1546/// purposes when it's considered as part of an overload set.
John McCalleff92132010-02-02 02:21:27 +00001547static QualType GetTypeOfFunction(ASTContext &Context,
John McCall9c72c602010-08-27 09:08:28 +00001548 const OverloadExpr::FindResult &R,
John McCalleff92132010-02-02 02:21:27 +00001549 FunctionDecl *Fn) {
John McCalleff92132010-02-02 02:21:27 +00001550 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall9c72c602010-08-27 09:08:28 +00001551 if (Method->isInstance()) {
1552 // An instance method that's referenced in a form that doesn't
1553 // look like a member pointer is just invalid.
1554 if (!R.HasFormOfMemberPointer) return QualType();
1555
John McCalleff92132010-02-02 02:21:27 +00001556 return Context.getMemberPointerType(Fn->getType(),
1557 Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall9c72c602010-08-27 09:08:28 +00001558 }
1559
1560 if (!R.IsAddressOfOperand) return Fn->getType();
John McCalleff92132010-02-02 02:21:27 +00001561 return Context.getPointerType(Fn->getType());
1562}
1563
1564/// Apply the deduction rules for overload sets.
1565///
1566/// \return the null type if this argument should be treated as an
1567/// undeduced context
1568static QualType
1569ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001570 Expr *Arg, QualType ParamType,
1571 bool ParamWasReference) {
John McCall9c72c602010-08-27 09:08:28 +00001572
1573 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCalleff92132010-02-02 02:21:27 +00001574
John McCall9c72c602010-08-27 09:08:28 +00001575 OverloadExpr *Ovl = R.Expression;
John McCalleff92132010-02-02 02:21:27 +00001576
Douglas Gregor75f21af2010-08-30 21:04:23 +00001577 // C++0x [temp.deduct.call]p4
1578 unsigned TDF = 0;
1579 if (ParamWasReference)
1580 TDF |= TDF_ParamWithReferenceType;
1581 if (R.IsAddressOfOperand)
1582 TDF |= TDF_IgnoreQualifiers;
1583
John McCalleff92132010-02-02 02:21:27 +00001584 // If there were explicit template arguments, we can only find
1585 // something via C++ [temp.arg.explicit]p3, i.e. if the arguments
1586 // unambiguously name a full specialization.
John McCall7bb12da2010-02-02 06:20:04 +00001587 if (Ovl->hasExplicitTemplateArgs()) {
John McCalleff92132010-02-02 02:21:27 +00001588 // But we can still look for an explicit specialization.
1589 if (FunctionDecl *ExplicitSpec
John McCall7bb12da2010-02-02 06:20:04 +00001590 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
John McCall9c72c602010-08-27 09:08:28 +00001591 return GetTypeOfFunction(S.Context, R, ExplicitSpec);
John McCalleff92132010-02-02 02:21:27 +00001592 return QualType();
1593 }
1594
1595 // C++0x [temp.deduct.call]p6:
1596 // When P is a function type, pointer to function type, or pointer
1597 // to member function type:
1598
1599 if (!ParamType->isFunctionType() &&
1600 !ParamType->isFunctionPointerType() &&
1601 !ParamType->isMemberFunctionPointerType())
1602 return QualType();
1603
1604 QualType Match;
John McCall7bb12da2010-02-02 06:20:04 +00001605 for (UnresolvedSetIterator I = Ovl->decls_begin(),
1606 E = Ovl->decls_end(); I != E; ++I) {
John McCalleff92132010-02-02 02:21:27 +00001607 NamedDecl *D = (*I)->getUnderlyingDecl();
1608
1609 // - If the argument is an overload set containing one or more
1610 // function templates, the parameter is treated as a
1611 // non-deduced context.
1612 if (isa<FunctionTemplateDecl>(D))
1613 return QualType();
1614
1615 FunctionDecl *Fn = cast<FunctionDecl>(D);
John McCall9c72c602010-08-27 09:08:28 +00001616 QualType ArgType = GetTypeOfFunction(S.Context, R, Fn);
1617 if (ArgType.isNull()) continue;
John McCalleff92132010-02-02 02:21:27 +00001618
Douglas Gregor75f21af2010-08-30 21:04:23 +00001619 // Function-to-pointer conversion.
1620 if (!ParamWasReference && ParamType->isPointerType() &&
1621 ArgType->isFunctionType())
1622 ArgType = S.Context.getPointerType(ArgType);
1623
John McCalleff92132010-02-02 02:21:27 +00001624 // - If the argument is an overload set (not containing function
1625 // templates), trial argument deduction is attempted using each
1626 // of the members of the set. If deduction succeeds for only one
1627 // of the overload set members, that member is used as the
1628 // argument value for the deduction. If deduction succeeds for
1629 // more than one member of the overload set the parameter is
1630 // treated as a non-deduced context.
1631
1632 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
1633 // Type deduction is done independently for each P/A pair, and
1634 // the deduced template argument values are then combined.
1635 // So we do not reject deductions which were made elsewhere.
Douglas Gregor02024a92010-03-28 02:42:43 +00001636 llvm::SmallVector<DeducedTemplateArgument, 8>
1637 Deduced(TemplateParams->size());
John McCall2a7fb272010-08-25 05:32:35 +00001638 TemplateDeductionInfo Info(S.Context, Ovl->getNameLoc());
John McCalleff92132010-02-02 02:21:27 +00001639 Sema::TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001640 = DeduceTemplateArguments(S, TemplateParams,
John McCalleff92132010-02-02 02:21:27 +00001641 ParamType, ArgType,
1642 Info, Deduced, TDF);
1643 if (Result) continue;
1644 if (!Match.isNull()) return QualType();
1645 Match = ArgType;
1646 }
1647
1648 return Match;
1649}
1650
Douglas Gregore53060f2009-06-25 22:08:12 +00001651/// \brief Perform template argument deduction from a function call
1652/// (C++ [temp.deduct.call]).
1653///
1654/// \param FunctionTemplate the function template for which we are performing
1655/// template argument deduction.
1656///
Douglas Gregor48026d22010-01-11 18:40:55 +00001657/// \param ExplicitTemplateArguments the explicit template arguments provided
1658/// for this call.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001659///
Douglas Gregore53060f2009-06-25 22:08:12 +00001660/// \param Args the function call arguments
1661///
1662/// \param NumArgs the number of arguments in Args
1663///
Douglas Gregor48026d22010-01-11 18:40:55 +00001664/// \param Name the name of the function being called. This is only significant
1665/// when the function template is a conversion function template, in which
1666/// case this routine will also perform template argument deduction based on
1667/// the function to which
1668///
Douglas Gregore53060f2009-06-25 22:08:12 +00001669/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00001670/// this will be set to the function template specialization produced by
Douglas Gregore53060f2009-06-25 22:08:12 +00001671/// template argument deduction.
1672///
1673/// \param Info the argument will be updated to provide additional information
1674/// about template argument deduction.
1675///
1676/// \returns the result of template argument deduction.
Douglas Gregore53060f2009-06-25 22:08:12 +00001677Sema::TemplateDeductionResult
1678Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor48026d22010-01-11 18:40:55 +00001679 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00001680 Expr **Args, unsigned NumArgs,
1681 FunctionDecl *&Specialization,
1682 TemplateDeductionInfo &Info) {
1683 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001684
Douglas Gregore53060f2009-06-25 22:08:12 +00001685 // C++ [temp.deduct.call]p1:
1686 // Template argument deduction is done by comparing each function template
1687 // parameter type (call it P) with the type of the corresponding argument
1688 // of the call (call it A) as described below.
1689 unsigned CheckArgs = NumArgs;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001690 if (NumArgs < Function->getMinRequiredArguments())
Douglas Gregore53060f2009-06-25 22:08:12 +00001691 return TDK_TooFewArguments;
1692 else if (NumArgs > Function->getNumParams()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001693 const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +00001694 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregore53060f2009-06-25 22:08:12 +00001695 if (!Proto->isVariadic())
1696 return TDK_TooManyArguments;
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Douglas Gregore53060f2009-06-25 22:08:12 +00001698 CheckArgs = Function->getNumParams();
1699 }
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001701 // The types of the parameters from which we will perform template argument
1702 // deduction.
John McCall2a7fb272010-08-25 05:32:35 +00001703 LocalInstantiationScope InstScope(*this);
Douglas Gregore53060f2009-06-25 22:08:12 +00001704 TemplateParameterList *TemplateParams
1705 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00001706 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001707 llvm::SmallVector<QualType, 4> ParamTypes;
Douglas Gregor02024a92010-03-28 02:42:43 +00001708 unsigned NumExplicitlySpecified = 0;
John McCalld5532b62009-11-23 01:53:49 +00001709 if (ExplicitTemplateArgs) {
Douglas Gregor83314aa2009-07-08 20:55:45 +00001710 TemplateDeductionResult Result =
1711 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001712 *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001713 Deduced,
1714 ParamTypes,
1715 0,
1716 Info);
1717 if (Result)
1718 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00001719
1720 NumExplicitlySpecified = Deduced.size();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001721 } else {
1722 // Just fill in the parameter types from the function declaration.
1723 for (unsigned I = 0; I != CheckArgs; ++I)
1724 ParamTypes.push_back(Function->getParamDecl(I)->getType());
1725 }
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001727 // Deduce template arguments from the function parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001728 Deduced.resize(TemplateParams->size());
Douglas Gregore53060f2009-06-25 22:08:12 +00001729 for (unsigned I = 0; I != CheckArgs; ++I) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00001730 QualType ParamType = ParamTypes[I];
Douglas Gregore53060f2009-06-25 22:08:12 +00001731 QualType ArgType = Args[I]->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Douglas Gregor75f21af2010-08-30 21:04:23 +00001733 // C++0x [temp.deduct.call]p3:
1734 // If P is a cv-qualified type, the top level cv-qualifiers of P’s type
1735 // are ignored for type deduction.
1736 if (ParamType.getCVRQualifiers())
1737 ParamType = ParamType.getLocalUnqualifiedType();
1738 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
1739 if (ParamRefType) {
1740 // [...] If P is a reference type, the type referred to by P is used
1741 // for type deduction.
1742 ParamType = ParamRefType->getPointeeType();
1743 }
1744
John McCalleff92132010-02-02 02:21:27 +00001745 // Overload sets usually make this parameter an undeduced
1746 // context, but there are sometimes special circumstances.
1747 if (ArgType == Context.OverloadTy) {
1748 ArgType = ResolveOverloadForDeduction(*this, TemplateParams,
Douglas Gregor75f21af2010-08-30 21:04:23 +00001749 Args[I], ParamType,
1750 ParamRefType != 0);
John McCalleff92132010-02-02 02:21:27 +00001751 if (ArgType.isNull())
1752 continue;
1753 }
1754
Douglas Gregor75f21af2010-08-30 21:04:23 +00001755 if (ParamRefType) {
1756 // C++0x [temp.deduct.call]p3:
1757 // [...] If P is of the form T&&, where T is a template parameter, and
1758 // the argument is an lvalue, the type A& is used in place of A for
1759 // type deduction.
1760 if (ParamRefType->isRValueReferenceType() &&
1761 ParamRefType->getAs<TemplateTypeParmType>() &&
John McCall7eb0a9e2010-11-24 05:12:34 +00001762 Args[I]->isLValue())
Douglas Gregor75f21af2010-08-30 21:04:23 +00001763 ArgType = Context.getLValueReferenceType(ArgType);
1764 } else {
1765 // C++ [temp.deduct.call]p2:
1766 // If P is not a reference type:
Mike Stump1eb44332009-09-09 15:08:12 +00001767 // - If A is an array type, the pointer type produced by the
1768 // array-to-pointer standard conversion (4.2) is used in place of
Douglas Gregore53060f2009-06-25 22:08:12 +00001769 // A for type deduction; otherwise,
1770 if (ArgType->isArrayType())
1771 ArgType = Context.getArrayDecayedType(ArgType);
Mike Stump1eb44332009-09-09 15:08:12 +00001772 // - If A is a function type, the pointer type produced by the
1773 // function-to-pointer standard conversion (4.3) is used in place
Douglas Gregore53060f2009-06-25 22:08:12 +00001774 // of A for type deduction; otherwise,
1775 else if (ArgType->isFunctionType())
1776 ArgType = Context.getPointerType(ArgType);
1777 else {
1778 // - If A is a cv-qualified type, the top level cv-qualifiers of A’s
1779 // type are ignored for type deduction.
1780 QualType CanonArgType = Context.getCanonicalType(ArgType);
Douglas Gregor75f21af2010-08-30 21:04:23 +00001781 if (ArgType.getCVRQualifiers())
1782 ArgType = ArgType.getUnqualifiedType();
Douglas Gregore53060f2009-06-25 22:08:12 +00001783 }
1784 }
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Douglas Gregore53060f2009-06-25 22:08:12 +00001786 // C++0x [temp.deduct.call]p4:
1787 // In general, the deduction process attempts to find template argument
1788 // values that will make the deduced A identical to A (after the type A
1789 // is transformed as described above). [...]
Douglas Gregor12820292009-09-14 20:00:47 +00001790 unsigned TDF = TDF_SkipNonDependent;
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Douglas Gregor508f1c82009-06-26 23:10:12 +00001792 // - If the original P is a reference type, the deduced A (i.e., the
1793 // type referred to by the reference) can be more cv-qualified than
1794 // the transformed A.
Douglas Gregor75f21af2010-08-30 21:04:23 +00001795 if (ParamRefType)
Douglas Gregor508f1c82009-06-26 23:10:12 +00001796 TDF |= TDF_ParamWithReferenceType;
Mike Stump1eb44332009-09-09 15:08:12 +00001797 // - The transformed A can be another pointer or pointer to member
1798 // type that can be converted to the deduced A via a qualification
Douglas Gregor508f1c82009-06-26 23:10:12 +00001799 // conversion (4.4).
John McCalldb0bc472010-08-05 05:30:45 +00001800 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
1801 ArgType->isObjCObjectPointerType())
Douglas Gregor508f1c82009-06-26 23:10:12 +00001802 TDF |= TDF_IgnoreQualifiers;
Mike Stump1eb44332009-09-09 15:08:12 +00001803 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor41128772009-06-26 23:27:24 +00001804 // transformed A can be a derived class of the deduced A. Likewise,
1805 // if P is a pointer to a class of the form simple-template-id, the
1806 // transformed A can be a pointer to a derived class pointed to by
1807 // the deduced A.
1808 if (isSimpleTemplateIdType(ParamType) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001809 (isa<PointerType>(ParamType) &&
Douglas Gregor41128772009-06-26 23:27:24 +00001810 isSimpleTemplateIdType(
Ted Kremenek6217b802009-07-29 21:53:49 +00001811 ParamType->getAs<PointerType>()->getPointeeType())))
Douglas Gregor41128772009-06-26 23:27:24 +00001812 TDF |= TDF_DerivedClass;
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregore53060f2009-06-25 22:08:12 +00001814 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001815 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor500d3312009-06-26 18:27:22 +00001816 ParamType, ArgType, Info, Deduced,
Douglas Gregor508f1c82009-06-26 23:10:12 +00001817 TDF))
Douglas Gregore53060f2009-06-25 22:08:12 +00001818 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001820 // FIXME: we need to check that the deduced A is the same as A,
1821 // modulo the various allowed differences.
Douglas Gregore53060f2009-06-25 22:08:12 +00001822 }
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001823
Mike Stump1eb44332009-09-09 15:08:12 +00001824 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregor02024a92010-03-28 02:42:43 +00001825 NumExplicitlySpecified,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001826 Specialization, Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00001827}
1828
Douglas Gregor83314aa2009-07-08 20:55:45 +00001829/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor4b52e252009-12-21 23:17:24 +00001830/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
1831/// a template.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001832///
1833/// \param FunctionTemplate the function template for which we are performing
1834/// template argument deduction.
1835///
Douglas Gregor4b52e252009-12-21 23:17:24 +00001836/// \param ExplicitTemplateArguments the explicitly-specified template
1837/// arguments.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001838///
1839/// \param ArgFunctionType the function type that will be used as the
1840/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor4b52e252009-12-21 23:17:24 +00001841/// function template's function type. This type may be NULL, if there is no
1842/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor83314aa2009-07-08 20:55:45 +00001843///
1844/// \param Specialization if template argument deduction was successful,
Mike Stump1eb44332009-09-09 15:08:12 +00001845/// this will be set to the function template specialization produced by
Douglas Gregor83314aa2009-07-08 20:55:45 +00001846/// template argument deduction.
1847///
1848/// \param Info the argument will be updated to provide additional information
1849/// about template argument deduction.
1850///
1851/// \returns the result of template argument deduction.
1852Sema::TemplateDeductionResult
1853Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001854 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001855 QualType ArgFunctionType,
1856 FunctionDecl *&Specialization,
1857 TemplateDeductionInfo &Info) {
1858 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
1859 TemplateParameterList *TemplateParams
1860 = FunctionTemplate->getTemplateParameters();
1861 QualType FunctionType = Function->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor83314aa2009-07-08 20:55:45 +00001863 // Substitute any explicit template arguments.
John McCall2a7fb272010-08-25 05:32:35 +00001864 LocalInstantiationScope InstScope(*this);
Douglas Gregor02024a92010-03-28 02:42:43 +00001865 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
1866 unsigned NumExplicitlySpecified = 0;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001867 llvm::SmallVector<QualType, 4> ParamTypes;
John McCalld5532b62009-11-23 01:53:49 +00001868 if (ExplicitTemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001869 if (TemplateDeductionResult Result
1870 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCalld5532b62009-11-23 01:53:49 +00001871 *ExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00001872 Deduced, ParamTypes,
Douglas Gregor83314aa2009-07-08 20:55:45 +00001873 &FunctionType, Info))
1874 return Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00001875
1876 NumExplicitlySpecified = Deduced.size();
Douglas Gregor83314aa2009-07-08 20:55:45 +00001877 }
1878
1879 // Template argument deduction for function templates in a SFINAE context.
1880 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001881 SFINAETrap Trap(*this);
1882
John McCalleff92132010-02-02 02:21:27 +00001883 Deduced.resize(TemplateParams->size());
1884
Douglas Gregor4b52e252009-12-21 23:17:24 +00001885 if (!ArgFunctionType.isNull()) {
1886 // Deduce template arguments from the function type.
Douglas Gregor4b52e252009-12-21 23:17:24 +00001887 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001888 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor4b52e252009-12-21 23:17:24 +00001889 FunctionType, ArgFunctionType, Info,
1890 Deduced, 0))
1891 return Result;
1892 }
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00001893
1894 if (TemplateDeductionResult Result
1895 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
1896 NumExplicitlySpecified,
1897 Specialization, Info))
1898 return Result;
1899
1900 // If the requested function type does not match the actual type of the
1901 // specialization, template argument deduction fails.
1902 if (!ArgFunctionType.isNull() &&
1903 !Context.hasSameType(ArgFunctionType, Specialization->getType()))
1904 return TDK_NonDeducedMismatch;
1905
1906 return TDK_Success;
Douglas Gregor83314aa2009-07-08 20:55:45 +00001907}
1908
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001909/// \brief Deduce template arguments for a templated conversion
1910/// function (C++ [temp.deduct.conv]) and, if successful, produce a
1911/// conversion function template specialization.
1912Sema::TemplateDeductionResult
1913Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
1914 QualType ToType,
1915 CXXConversionDecl *&Specialization,
1916 TemplateDeductionInfo &Info) {
Mike Stump1eb44332009-09-09 15:08:12 +00001917 CXXConversionDecl *Conv
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001918 = cast<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl());
1919 QualType FromType = Conv->getConversionType();
1920
1921 // Canonicalize the types for deduction.
1922 QualType P = Context.getCanonicalType(FromType);
1923 QualType A = Context.getCanonicalType(ToType);
1924
1925 // C++0x [temp.deduct.conv]p3:
1926 // If P is a reference type, the type referred to by P is used for
1927 // type deduction.
1928 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
1929 P = PRef->getPointeeType();
1930
1931 // C++0x [temp.deduct.conv]p3:
1932 // If A is a reference type, the type referred to by A is used
1933 // for type deduction.
1934 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
1935 A = ARef->getPointeeType();
1936 // C++ [temp.deduct.conv]p2:
1937 //
Mike Stump1eb44332009-09-09 15:08:12 +00001938 // If A is not a reference type:
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001939 else {
1940 assert(!A->isReferenceType() && "Reference types were handled above");
1941
1942 // - If P is an array type, the pointer type produced by the
Mike Stump1eb44332009-09-09 15:08:12 +00001943 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001944 // of P for type deduction; otherwise,
1945 if (P->isArrayType())
1946 P = Context.getArrayDecayedType(P);
1947 // - If P is a function type, the pointer type produced by the
1948 // function-to-pointer standard conversion (4.3) is used in
1949 // place of P for type deduction; otherwise,
1950 else if (P->isFunctionType())
1951 P = Context.getPointerType(P);
1952 // - If P is a cv-qualified type, the top level cv-qualifiers of
1953 // P’s type are ignored for type deduction.
1954 else
1955 P = P.getUnqualifiedType();
1956
1957 // C++0x [temp.deduct.conv]p3:
1958 // If A is a cv-qualified type, the top level cv-qualifiers of A’s
1959 // type are ignored for type deduction.
1960 A = A.getUnqualifiedType();
1961 }
1962
1963 // Template argument deduction for function templates in a SFINAE context.
1964 // Trap any errors that might occur.
Mike Stump1eb44332009-09-09 15:08:12 +00001965 SFINAETrap Trap(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001966
1967 // C++ [temp.deduct.conv]p1:
1968 // Template argument deduction is done by comparing the return
1969 // type of the template conversion function (call it P) with the
1970 // type that is required as the result of the conversion (call it
1971 // A) as described in 14.8.2.4.
1972 TemplateParameterList *TemplateParams
1973 = FunctionTemplate->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00001974 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump1eb44332009-09-09 15:08:12 +00001975 Deduced.resize(TemplateParams->size());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001976
1977 // C++0x [temp.deduct.conv]p4:
1978 // In general, the deduction process attempts to find template
1979 // argument values that will make the deduced A identical to
1980 // A. However, there are two cases that allow a difference:
1981 unsigned TDF = 0;
1982 // - If the original A is a reference type, A can be more
1983 // cv-qualified than the deduced A (i.e., the type referred to
1984 // by the reference)
1985 if (ToType->isReferenceType())
1986 TDF |= TDF_ParamWithReferenceType;
1987 // - The deduced A can be another pointer or pointer to member
1988 // type that can be converted to A via a qualification
1989 // conversion.
1990 //
1991 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
1992 // both P and A are pointers or member pointers. In this case, we
1993 // just ignore cv-qualifiers completely).
1994 if ((P->isPointerType() && A->isPointerType()) ||
1995 (P->isMemberPointerType() && P->isMemberPointerType()))
1996 TDF |= TDF_IgnoreQualifiers;
1997 if (TemplateDeductionResult Result
Chandler Carrutha7ef1302010-02-07 21:33:28 +00001998 = ::DeduceTemplateArguments(*this, TemplateParams,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001999 P, A, Info, Deduced, TDF))
2000 return Result;
2001
2002 // FIXME: we need to check that the deduced A is the same as A,
2003 // modulo the various allowed differences.
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002005 // Finish template argument deduction.
John McCall2a7fb272010-08-25 05:32:35 +00002006 LocalInstantiationScope InstScope(*this);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002007 FunctionDecl *Spec = 0;
2008 TemplateDeductionResult Result
Douglas Gregor02024a92010-03-28 02:42:43 +00002009 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced, 0, Spec,
2010 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002011 Specialization = cast_or_null<CXXConversionDecl>(Spec);
2012 return Result;
2013}
2014
Douglas Gregor4b52e252009-12-21 23:17:24 +00002015/// \brief Deduce template arguments for a function template when there is
2016/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
2017///
2018/// \param FunctionTemplate the function template for which we are performing
2019/// template argument deduction.
2020///
2021/// \param ExplicitTemplateArguments the explicitly-specified template
2022/// arguments.
2023///
2024/// \param Specialization if template argument deduction was successful,
2025/// this will be set to the function template specialization produced by
2026/// template argument deduction.
2027///
2028/// \param Info the argument will be updated to provide additional information
2029/// about template argument deduction.
2030///
2031/// \returns the result of template argument deduction.
2032Sema::TemplateDeductionResult
2033Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
2034 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2035 FunctionDecl *&Specialization,
2036 TemplateDeductionInfo &Info) {
2037 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2038 QualType(), Specialization, Info);
2039}
2040
Douglas Gregor8a514912009-09-14 18:39:43 +00002041/// \brief Stores the result of comparing the qualifiers of two types.
2042enum DeductionQualifierComparison {
2043 NeitherMoreQualified = 0,
2044 ParamMoreQualified,
2045 ArgMoreQualified
2046};
2047
2048/// \brief Deduce the template arguments during partial ordering by comparing
2049/// the parameter type and the argument type (C++0x [temp.deduct.partial]).
2050///
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002051/// \param S the semantic analysis object within which we are deducing
Douglas Gregor8a514912009-09-14 18:39:43 +00002052///
2053/// \param TemplateParams the template parameters that we are deducing
2054///
2055/// \param ParamIn the parameter type
2056///
2057/// \param ArgIn the argument type
2058///
2059/// \param Info information about the template argument deduction itself
2060///
2061/// \param Deduced the deduced template arguments
2062///
2063/// \returns the result of template argument deduction so far. Note that a
2064/// "success" result means that template argument deduction has not yet failed,
2065/// but it may still fail, later, for other reasons.
2066static Sema::TemplateDeductionResult
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002067DeduceTemplateArgumentsDuringPartialOrdering(Sema &S,
Douglas Gregor02024a92010-03-28 02:42:43 +00002068 TemplateParameterList *TemplateParams,
Douglas Gregor8a514912009-09-14 18:39:43 +00002069 QualType ParamIn, QualType ArgIn,
John McCall2a7fb272010-08-25 05:32:35 +00002070 TemplateDeductionInfo &Info,
Douglas Gregor02024a92010-03-28 02:42:43 +00002071 llvm::SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2072 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002073 CanQualType Param = S.Context.getCanonicalType(ParamIn);
2074 CanQualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor8a514912009-09-14 18:39:43 +00002075
2076 // C++0x [temp.deduct.partial]p5:
2077 // Before the partial ordering is done, certain transformations are
2078 // performed on the types used for partial ordering:
2079 // - If P is a reference type, P is replaced by the type referred to.
2080 CanQual<ReferenceType> ParamRef = Param->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002081 if (!ParamRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002082 Param = ParamRef->getPointeeType();
2083
2084 // - If A is a reference type, A is replaced by the type referred to.
2085 CanQual<ReferenceType> ArgRef = Arg->getAs<ReferenceType>();
John McCalle27ec8a2009-10-23 23:03:21 +00002086 if (!ArgRef.isNull())
Douglas Gregor8a514912009-09-14 18:39:43 +00002087 Arg = ArgRef->getPointeeType();
2088
John McCalle27ec8a2009-10-23 23:03:21 +00002089 if (QualifierComparisons && !ParamRef.isNull() && !ArgRef.isNull()) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002090 // C++0x [temp.deduct.partial]p6:
2091 // If both P and A were reference types (before being replaced with the
2092 // type referred to above), determine which of the two types (if any) is
2093 // more cv-qualified than the other; otherwise the types are considered to
2094 // be equally cv-qualified for partial ordering purposes. The result of this
2095 // determination will be used below.
2096 //
2097 // We save this information for later, using it only when deduction
2098 // succeeds in both directions.
2099 DeductionQualifierComparison QualifierResult = NeitherMoreQualified;
2100 if (Param.isMoreQualifiedThan(Arg))
2101 QualifierResult = ParamMoreQualified;
2102 else if (Arg.isMoreQualifiedThan(Param))
2103 QualifierResult = ArgMoreQualified;
2104 QualifierComparisons->push_back(QualifierResult);
2105 }
2106
2107 // C++0x [temp.deduct.partial]p7:
2108 // Remove any top-level cv-qualifiers:
2109 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
2110 // version of P.
2111 Param = Param.getUnqualifiedType();
2112 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
2113 // version of A.
2114 Arg = Arg.getUnqualifiedType();
2115
2116 // C++0x [temp.deduct.partial]p8:
2117 // Using the resulting types P and A the deduction is then done as
2118 // described in 14.9.2.5. If deduction succeeds for a given type, the type
2119 // from the argument template is considered to be at least as specialized
2120 // as the type from the parameter template.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002121 return DeduceTemplateArguments(S, TemplateParams, Param, Arg, Info,
Douglas Gregor8a514912009-09-14 18:39:43 +00002122 Deduced, TDF_None);
2123}
2124
2125static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002126MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2127 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002128 unsigned Level,
Douglas Gregore73bb602009-09-14 21:25:05 +00002129 llvm::SmallVectorImpl<bool> &Deduced);
Douglas Gregor77bc5722010-11-12 23:44:13 +00002130
2131/// \brief If this is a non-static member function,
2132static void MaybeAddImplicitObjectParameterType(ASTContext &Context,
2133 CXXMethodDecl *Method,
2134 llvm::SmallVectorImpl<QualType> &ArgTypes) {
2135 if (Method->isStatic())
2136 return;
2137
2138 // C++ [over.match.funcs]p4:
2139 //
2140 // For non-static member functions, the type of the implicit
2141 // object parameter is
2142 // — "lvalue reference to cv X" for functions declared without a
2143 // ref-qualifier or with the & ref-qualifier
2144 // - "rvalue reference to cv X" for functions declared with the
2145 // && ref-qualifier
2146 //
2147 // FIXME: We don't have ref-qualifiers yet, so we don't do that part.
2148 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
2149 ArgTy = Context.getQualifiedType(ArgTy,
2150 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
2151 ArgTy = Context.getLValueReferenceType(ArgTy);
2152 ArgTypes.push_back(ArgTy);
2153}
2154
Douglas Gregor8a514912009-09-14 18:39:43 +00002155/// \brief Determine whether the function template \p FT1 is at least as
2156/// specialized as \p FT2.
2157static bool isAtLeastAsSpecializedAs(Sema &S,
John McCall5769d612010-02-08 23:07:23 +00002158 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002159 FunctionTemplateDecl *FT1,
2160 FunctionTemplateDecl *FT2,
2161 TemplatePartialOrderingContext TPOC,
2162 llvm::SmallVectorImpl<DeductionQualifierComparison> *QualifierComparisons) {
2163 FunctionDecl *FD1 = FT1->getTemplatedDecl();
2164 FunctionDecl *FD2 = FT2->getTemplatedDecl();
2165 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
2166 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
2167
2168 assert(Proto1 && Proto2 && "Function templates must have prototypes");
2169 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Douglas Gregor02024a92010-03-28 02:42:43 +00002170 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor8a514912009-09-14 18:39:43 +00002171 Deduced.resize(TemplateParams->size());
2172
2173 // C++0x [temp.deduct.partial]p3:
2174 // The types used to determine the ordering depend on the context in which
2175 // the partial ordering is done:
John McCall2a7fb272010-08-25 05:32:35 +00002176 TemplateDeductionInfo Info(S.Context, Loc);
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002177 CXXMethodDecl *Method1 = 0;
2178 CXXMethodDecl *Method2 = 0;
2179 bool IsNonStatic2 = false;
2180 bool IsNonStatic1 = false;
2181 unsigned Skip2 = 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002182 switch (TPOC) {
2183 case TPOC_Call: {
2184 // - In the context of a function call, the function parameter types are
2185 // used.
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002186 Method1 = dyn_cast<CXXMethodDecl>(FD1);
2187 Method2 = dyn_cast<CXXMethodDecl>(FD2);
2188 IsNonStatic1 = Method1 && !Method1->isStatic();
2189 IsNonStatic2 = Method2 && !Method2->isStatic();
2190
2191 // C++0x [temp.func.order]p3:
2192 // [...] If only one of the function templates is a non-static
2193 // member, that function template is considered to have a new
2194 // first parameter inserted in its function parameter list. The
2195 // new parameter is of type "reference to cv A," where cv are
2196 // the cv-qualifiers of the function template (if any) and A is
2197 // the class of which the function template is a member.
2198 //
2199 // C++98/03 doesn't have this provision, so instead we drop the
2200 // first argument of the free function or static member, which
2201 // seems to match existing practice.
Douglas Gregor77bc5722010-11-12 23:44:13 +00002202 llvm::SmallVector<QualType, 4> Args1;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002203 unsigned Skip1 = !S.getLangOptions().CPlusPlus0x &&
2204 IsNonStatic2 && !IsNonStatic1;
2205 if (S.getLangOptions().CPlusPlus0x && IsNonStatic1 && !IsNonStatic2)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002206 MaybeAddImplicitObjectParameterType(S.Context, Method1, Args1);
2207 Args1.insert(Args1.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002208 Proto1->arg_type_begin() + Skip1, Proto1->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002209
2210 llvm::SmallVector<QualType, 4> Args2;
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002211 Skip2 = !S.getLangOptions().CPlusPlus0x &&
2212 IsNonStatic1 && !IsNonStatic2;
2213 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
Douglas Gregor77bc5722010-11-12 23:44:13 +00002214 MaybeAddImplicitObjectParameterType(S.Context, Method2, Args2);
2215 Args2.insert(Args2.end(),
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002216 Proto2->arg_type_begin() + Skip2, Proto2->arg_type_end());
Douglas Gregor77bc5722010-11-12 23:44:13 +00002217
2218 unsigned NumParams = std::min(Args1.size(), Args2.size());
Douglas Gregor8a514912009-09-14 18:39:43 +00002219 for (unsigned I = 0; I != NumParams; ++I)
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002220 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002221 TemplateParams,
Douglas Gregor77bc5722010-11-12 23:44:13 +00002222 Args2[I],
2223 Args1[I],
Douglas Gregor8a514912009-09-14 18:39:43 +00002224 Info,
2225 Deduced,
2226 QualifierComparisons))
2227 return false;
2228
2229 break;
2230 }
2231
2232 case TPOC_Conversion:
2233 // - In the context of a call to a conversion operator, the return types
2234 // of the conversion function templates are used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002235 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002236 TemplateParams,
2237 Proto2->getResultType(),
2238 Proto1->getResultType(),
2239 Info,
2240 Deduced,
2241 QualifierComparisons))
2242 return false;
2243 break;
2244
2245 case TPOC_Other:
2246 // - In other contexts (14.6.6.2) the function template’s function type
2247 // is used.
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002248 if (DeduceTemplateArgumentsDuringPartialOrdering(S,
Douglas Gregor8a514912009-09-14 18:39:43 +00002249 TemplateParams,
2250 FD2->getType(),
2251 FD1->getType(),
2252 Info,
2253 Deduced,
2254 QualifierComparisons))
2255 return false;
2256 break;
2257 }
2258
2259 // C++0x [temp.deduct.partial]p11:
2260 // In most cases, all template parameters must have values in order for
2261 // deduction to succeed, but for partial ordering purposes a template
2262 // parameter may remain without a value provided it is not used in the
2263 // types being used for partial ordering. [ Note: a template parameter used
2264 // in a non-deduced context is considered used. -end note]
2265 unsigned ArgIdx = 0, NumArgs = Deduced.size();
2266 for (; ArgIdx != NumArgs; ++ArgIdx)
2267 if (Deduced[ArgIdx].isNull())
2268 break;
2269
2270 if (ArgIdx == NumArgs) {
2271 // All template arguments were deduced. FT1 is at least as specialized
2272 // as FT2.
2273 return true;
2274 }
2275
Douglas Gregore73bb602009-09-14 21:25:05 +00002276 // Figure out which template parameters were used.
Douglas Gregor8a514912009-09-14 18:39:43 +00002277 llvm::SmallVector<bool, 4> UsedParameters;
2278 UsedParameters.resize(TemplateParams->size());
2279 switch (TPOC) {
2280 case TPOC_Call: {
2281 unsigned NumParams = std::min(Proto1->getNumArgs(), Proto2->getNumArgs());
Douglas Gregor8d706ec2010-11-15 15:41:16 +00002282 if (S.getLangOptions().CPlusPlus0x && IsNonStatic2 && !IsNonStatic1)
2283 ::MarkUsedTemplateParameters(S, Method2->getThisType(S.Context), false,
2284 TemplateParams->getDepth(), UsedParameters);
2285 for (unsigned I = Skip2; I < NumParams; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002286 ::MarkUsedTemplateParameters(S, Proto2->getArgType(I), false,
2287 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002288 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002289 break;
2290 }
2291
2292 case TPOC_Conversion:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002293 ::MarkUsedTemplateParameters(S, Proto2->getResultType(), false,
2294 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00002295 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002296 break;
2297
2298 case TPOC_Other:
Douglas Gregored9c0f92009-10-29 00:04:11 +00002299 ::MarkUsedTemplateParameters(S, FD2->getType(), false,
2300 TemplateParams->getDepth(),
2301 UsedParameters);
Douglas Gregor8a514912009-09-14 18:39:43 +00002302 break;
2303 }
2304
2305 for (; ArgIdx != NumArgs; ++ArgIdx)
2306 // If this argument had no value deduced but was used in one of the types
2307 // used for partial ordering, then deduction fails.
2308 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
2309 return false;
2310
2311 return true;
2312}
2313
2314
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002315/// \brief Returns the more specialized function template according
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002316/// to the rules of function template partial ordering (C++ [temp.func.order]).
2317///
2318/// \param FT1 the first function template
2319///
2320/// \param FT2 the second function template
2321///
Douglas Gregor8a514912009-09-14 18:39:43 +00002322/// \param TPOC the context in which we are performing partial ordering of
2323/// function templates.
Mike Stump1eb44332009-09-09 15:08:12 +00002324///
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002325/// \returns the more specialized function template. If neither
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002326/// template is more specialized, returns NULL.
2327FunctionTemplateDecl *
2328Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
2329 FunctionTemplateDecl *FT2,
John McCall5769d612010-02-08 23:07:23 +00002330 SourceLocation Loc,
Douglas Gregor8a514912009-09-14 18:39:43 +00002331 TemplatePartialOrderingContext TPOC) {
Douglas Gregor8a514912009-09-14 18:39:43 +00002332 llvm::SmallVector<DeductionQualifierComparison, 4> QualifierComparisons;
John McCall5769d612010-02-08 23:07:23 +00002333 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC, 0);
2334 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Douglas Gregor8a514912009-09-14 18:39:43 +00002335 &QualifierComparisons);
2336
2337 if (Better1 != Better2) // We have a clear winner
2338 return Better1? FT1 : FT2;
2339
2340 if (!Better1 && !Better2) // Neither is better than the other
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002341 return 0;
Douglas Gregor8a514912009-09-14 18:39:43 +00002342
2343
2344 // C++0x [temp.deduct.partial]p10:
2345 // If for each type being considered a given template is at least as
2346 // specialized for all types and more specialized for some set of types and
2347 // the other template is not more specialized for any types or is not at
2348 // least as specialized for any types, then the given template is more
2349 // specialized than the other template. Otherwise, neither template is more
2350 // specialized than the other.
2351 Better1 = false;
2352 Better2 = false;
2353 for (unsigned I = 0, N = QualifierComparisons.size(); I != N; ++I) {
2354 // C++0x [temp.deduct.partial]p9:
2355 // If, for a given type, deduction succeeds in both directions (i.e., the
2356 // types are identical after the transformations above) and if the type
2357 // from the argument template is more cv-qualified than the type from the
2358 // parameter template (as described above) that type is considered to be
2359 // more specialized than the other. If neither type is more cv-qualified
2360 // than the other then neither type is more specialized than the other.
2361 switch (QualifierComparisons[I]) {
2362 case NeitherMoreQualified:
2363 break;
2364
2365 case ParamMoreQualified:
2366 Better1 = true;
2367 if (Better2)
2368 return 0;
2369 break;
2370
2371 case ArgMoreQualified:
2372 Better2 = true;
2373 if (Better1)
2374 return 0;
2375 break;
2376 }
2377 }
2378
2379 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002380 if (Better1)
2381 return FT1;
Douglas Gregor8a514912009-09-14 18:39:43 +00002382 else if (Better2)
2383 return FT2;
2384 else
2385 return 0;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002386}
Douglas Gregor83314aa2009-07-08 20:55:45 +00002387
Douglas Gregord5a423b2009-09-25 18:43:00 +00002388/// \brief Determine if the two templates are equivalent.
2389static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
2390 if (T1 == T2)
2391 return true;
2392
2393 if (!T1 || !T2)
2394 return false;
2395
2396 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
2397}
2398
2399/// \brief Retrieve the most specialized of the given function template
2400/// specializations.
2401///
John McCallc373d482010-01-27 01:50:18 +00002402/// \param SpecBegin the start iterator of the function template
2403/// specializations that we will be comparing.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002404///
John McCallc373d482010-01-27 01:50:18 +00002405/// \param SpecEnd the end iterator of the function template
2406/// specializations, paired with \p SpecBegin.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002407///
2408/// \param TPOC the partial ordering context to use to compare the function
2409/// template specializations.
2410///
2411/// \param Loc the location where the ambiguity or no-specializations
2412/// diagnostic should occur.
2413///
2414/// \param NoneDiag partial diagnostic used to diagnose cases where there are
2415/// no matching candidates.
2416///
2417/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
2418/// occurs.
2419///
2420/// \param CandidateDiag partial diagnostic used for each function template
2421/// specialization that is a candidate in the ambiguous ordering. One parameter
2422/// in this diagnostic should be unbound, which will correspond to the string
2423/// describing the template arguments for the function template specialization.
2424///
2425/// \param Index if non-NULL and the result of this function is non-nULL,
2426/// receives the index corresponding to the resulting function template
2427/// specialization.
2428///
2429/// \returns the most specialized function template specialization, if
John McCallc373d482010-01-27 01:50:18 +00002430/// found. Otherwise, returns SpecEnd.
Douglas Gregord5a423b2009-09-25 18:43:00 +00002431///
2432/// \todo FIXME: Consider passing in the "also-ran" candidates that failed
2433/// template argument deduction.
John McCallc373d482010-01-27 01:50:18 +00002434UnresolvedSetIterator
2435Sema::getMostSpecialized(UnresolvedSetIterator SpecBegin,
2436 UnresolvedSetIterator SpecEnd,
2437 TemplatePartialOrderingContext TPOC,
2438 SourceLocation Loc,
2439 const PartialDiagnostic &NoneDiag,
2440 const PartialDiagnostic &AmbigDiag,
2441 const PartialDiagnostic &CandidateDiag) {
2442 if (SpecBegin == SpecEnd) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00002443 Diag(Loc, NoneDiag);
John McCallc373d482010-01-27 01:50:18 +00002444 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002445 }
2446
John McCallc373d482010-01-27 01:50:18 +00002447 if (SpecBegin + 1 == SpecEnd)
2448 return SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002449
2450 // Find the function template that is better than all of the templates it
2451 // has been compared to.
John McCallc373d482010-01-27 01:50:18 +00002452 UnresolvedSetIterator Best = SpecBegin;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002453 FunctionTemplateDecl *BestTemplate
John McCallc373d482010-01-27 01:50:18 +00002454 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002455 assert(BestTemplate && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002456 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
2457 FunctionTemplateDecl *Challenger
2458 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002459 assert(Challenger && "Not a function template specialization?");
John McCallc373d482010-01-27 01:50:18 +00002460 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002461 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002462 Challenger)) {
2463 Best = I;
2464 BestTemplate = Challenger;
2465 }
2466 }
2467
2468 // Make sure that the "best" function template is more specialized than all
2469 // of the others.
2470 bool Ambiguous = false;
John McCallc373d482010-01-27 01:50:18 +00002471 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
2472 FunctionTemplateDecl *Challenger
2473 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregord5a423b2009-09-25 18:43:00 +00002474 if (I != Best &&
2475 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
John McCall5769d612010-02-08 23:07:23 +00002476 Loc, TPOC),
Douglas Gregord5a423b2009-09-25 18:43:00 +00002477 BestTemplate)) {
2478 Ambiguous = true;
2479 break;
2480 }
2481 }
2482
2483 if (!Ambiguous) {
2484 // We found an answer. Return it.
John McCallc373d482010-01-27 01:50:18 +00002485 return Best;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002486 }
2487
2488 // Diagnose the ambiguity.
2489 Diag(Loc, AmbigDiag);
2490
2491 // FIXME: Can we order the candidates in some sane way?
John McCallc373d482010-01-27 01:50:18 +00002492 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I)
2493 Diag((*I)->getLocation(), CandidateDiag)
Douglas Gregord5a423b2009-09-25 18:43:00 +00002494 << getTemplateArgumentBindingsText(
John McCallc373d482010-01-27 01:50:18 +00002495 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
2496 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Douglas Gregord5a423b2009-09-25 18:43:00 +00002497
John McCallc373d482010-01-27 01:50:18 +00002498 return SpecEnd;
Douglas Gregord5a423b2009-09-25 18:43:00 +00002499}
2500
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002501/// \brief Returns the more specialized class template partial specialization
2502/// according to the rules of partial ordering of class template partial
2503/// specializations (C++ [temp.class.order]).
2504///
2505/// \param PS1 the first class template partial specialization
2506///
2507/// \param PS2 the second class template partial specialization
2508///
2509/// \returns the more specialized class template partial specialization. If
2510/// neither partial specialization is more specialized, returns NULL.
2511ClassTemplatePartialSpecializationDecl *
2512Sema::getMoreSpecializedPartialSpecialization(
2513 ClassTemplatePartialSpecializationDecl *PS1,
John McCall5769d612010-02-08 23:07:23 +00002514 ClassTemplatePartialSpecializationDecl *PS2,
2515 SourceLocation Loc) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002516 // C++ [temp.class.order]p1:
2517 // For two class template partial specializations, the first is at least as
2518 // specialized as the second if, given the following rewrite to two
2519 // function templates, the first function template is at least as
2520 // specialized as the second according to the ordering rules for function
2521 // templates (14.6.6.2):
2522 // - the first function template has the same template parameters as the
2523 // first partial specialization and has a single function parameter
2524 // whose type is a class template specialization with the template
2525 // arguments of the first partial specialization, and
2526 // - the second function template has the same template parameters as the
2527 // second partial specialization and has a single function parameter
2528 // whose type is a class template specialization with the template
2529 // arguments of the second partial specialization.
2530 //
Douglas Gregor31dce8f2010-04-29 06:21:43 +00002531 // Rather than synthesize function templates, we merely perform the
2532 // equivalent partial ordering by performing deduction directly on
2533 // the template arguments of the class template partial
2534 // specializations. This computation is slightly simpler than the
2535 // general problem of function template partial ordering, because
2536 // class template partial specializations are more constrained. We
2537 // know that every template parameter is deducible from the class
2538 // template partial specialization's template arguments, for
2539 // example.
Douglas Gregor02024a92010-03-28 02:42:43 +00002540 llvm::SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2a7fb272010-08-25 05:32:35 +00002541 TemplateDeductionInfo Info(Context, Loc);
John McCall31f17ec2010-04-27 00:57:59 +00002542
2543 QualType PT1 = PS1->getInjectedSpecializationType();
2544 QualType PT2 = PS2->getInjectedSpecializationType();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002545
2546 // Determine whether PS1 is at least as specialized as PS2
2547 Deduced.resize(PS2->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002548 bool Better1 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002549 PS2->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002550 PT2,
2551 PT1,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002552 Info,
2553 Deduced,
2554 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002555 if (Better1) {
2556 InstantiatingTemplate Inst(*this, PS2->getLocation(), PS2,
2557 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002558 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
2559 PS1->getTemplateArgs(),
2560 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002561 }
Douglas Gregor516e6e02010-04-29 06:31:36 +00002562
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002563 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregordb0d4b72009-11-11 23:06:43 +00002564 Deduced.clear();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002565 Deduced.resize(PS1->getTemplateParameters()->size());
Chandler Carrutha7ef1302010-02-07 21:33:28 +00002566 bool Better2 = !DeduceTemplateArgumentsDuringPartialOrdering(*this,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002567 PS1->getTemplateParameters(),
John McCall31f17ec2010-04-27 00:57:59 +00002568 PT1,
2569 PT2,
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002570 Info,
2571 Deduced,
2572 0);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002573 if (Better2) {
2574 InstantiatingTemplate Inst(*this, PS1->getLocation(), PS1,
2575 Deduced.data(), Deduced.size(), Info);
Douglas Gregor516e6e02010-04-29 06:31:36 +00002576 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
2577 PS2->getTemplateArgs(),
2578 Deduced, Info);
Argyrios Kyrtzidis2c4792c2010-11-05 23:25:18 +00002579 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002580
2581 if (Better1 == Better2)
2582 return 0;
2583
2584 return Better1? PS1 : PS2;
2585}
2586
Mike Stump1eb44332009-09-09 15:08:12 +00002587static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002588MarkUsedTemplateParameters(Sema &SemaRef,
2589 const TemplateArgument &TemplateArg,
2590 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002591 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002592 llvm::SmallVectorImpl<bool> &Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002593
Douglas Gregore73bb602009-09-14 21:25:05 +00002594/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002595/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002596static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002597MarkUsedTemplateParameters(Sema &SemaRef,
2598 const Expr *E,
2599 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002600 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002601 llvm::SmallVectorImpl<bool> &Used) {
2602 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
2603 // find other occurrences of template parameters.
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002604 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregorc781f9c2010-01-14 18:13:22 +00002605 if (!DRE)
Douglas Gregor031a5882009-06-13 00:26:55 +00002606 return;
2607
Mike Stump1eb44332009-09-09 15:08:12 +00002608 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor031a5882009-06-13 00:26:55 +00002609 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2610 if (!NTTP)
2611 return;
2612
Douglas Gregored9c0f92009-10-29 00:04:11 +00002613 if (NTTP->getDepth() == Depth)
2614 Used[NTTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00002615}
2616
Douglas Gregore73bb602009-09-14 21:25:05 +00002617/// \brief Mark the template parameters that are used by the given
2618/// nested name specifier.
2619static void
2620MarkUsedTemplateParameters(Sema &SemaRef,
2621 NestedNameSpecifier *NNS,
2622 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002623 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002624 llvm::SmallVectorImpl<bool> &Used) {
2625 if (!NNS)
2626 return;
2627
Douglas Gregored9c0f92009-10-29 00:04:11 +00002628 MarkUsedTemplateParameters(SemaRef, NNS->getPrefix(), OnlyDeduced, Depth,
2629 Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002630 MarkUsedTemplateParameters(SemaRef, QualType(NNS->getAsType(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002631 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002632}
2633
2634/// \brief Mark the template parameters that are used by the given
2635/// template name.
2636static void
2637MarkUsedTemplateParameters(Sema &SemaRef,
2638 TemplateName Name,
2639 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002640 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002641 llvm::SmallVectorImpl<bool> &Used) {
2642 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2643 if (TemplateTemplateParmDecl *TTP
Douglas Gregored9c0f92009-10-29 00:04:11 +00002644 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
2645 if (TTP->getDepth() == Depth)
2646 Used[TTP->getIndex()] = true;
2647 }
Douglas Gregore73bb602009-09-14 21:25:05 +00002648 return;
2649 }
2650
Douglas Gregor788cd062009-11-11 01:00:40 +00002651 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
2652 MarkUsedTemplateParameters(SemaRef, QTN->getQualifier(), OnlyDeduced,
2653 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002654 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Douglas Gregored9c0f92009-10-29 00:04:11 +00002655 MarkUsedTemplateParameters(SemaRef, DTN->getQualifier(), OnlyDeduced,
2656 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002657}
2658
2659/// \brief Mark the template parameters that are used by the given
Douglas Gregor031a5882009-06-13 00:26:55 +00002660/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00002661static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002662MarkUsedTemplateParameters(Sema &SemaRef, QualType T,
2663 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002664 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002665 llvm::SmallVectorImpl<bool> &Used) {
2666 if (T.isNull())
2667 return;
2668
Douglas Gregor031a5882009-06-13 00:26:55 +00002669 // Non-dependent types have nothing deducible
2670 if (!T->isDependentType())
2671 return;
2672
2673 T = SemaRef.Context.getCanonicalType(T);
2674 switch (T->getTypeClass()) {
Douglas Gregor031a5882009-06-13 00:26:55 +00002675 case Type::Pointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00002676 MarkUsedTemplateParameters(SemaRef,
2677 cast<PointerType>(T)->getPointeeType(),
2678 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002679 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002680 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002681 break;
2682
2683 case Type::BlockPointer:
Douglas Gregore73bb602009-09-14 21:25:05 +00002684 MarkUsedTemplateParameters(SemaRef,
2685 cast<BlockPointerType>(T)->getPointeeType(),
2686 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002687 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002688 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002689 break;
2690
2691 case Type::LValueReference:
2692 case Type::RValueReference:
Douglas Gregore73bb602009-09-14 21:25:05 +00002693 MarkUsedTemplateParameters(SemaRef,
2694 cast<ReferenceType>(T)->getPointeeType(),
2695 OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002696 Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002697 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002698 break;
2699
2700 case Type::MemberPointer: {
2701 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Douglas Gregore73bb602009-09-14 21:25:05 +00002702 MarkUsedTemplateParameters(SemaRef, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002703 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002704 MarkUsedTemplateParameters(SemaRef, QualType(MemPtr->getClass(), 0),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002705 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002706 break;
2707 }
2708
2709 case Type::DependentSizedArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00002710 MarkUsedTemplateParameters(SemaRef,
2711 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002712 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002713 // Fall through to check the element type
2714
2715 case Type::ConstantArray:
2716 case Type::IncompleteArray:
Douglas Gregore73bb602009-09-14 21:25:05 +00002717 MarkUsedTemplateParameters(SemaRef,
2718 cast<ArrayType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002719 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002720 break;
2721
2722 case Type::Vector:
2723 case Type::ExtVector:
Douglas Gregore73bb602009-09-14 21:25:05 +00002724 MarkUsedTemplateParameters(SemaRef,
2725 cast<VectorType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002726 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002727 break;
2728
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002729 case Type::DependentSizedExtVector: {
2730 const DependentSizedExtVectorType *VecType
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002731 = cast<DependentSizedExtVectorType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00002732 MarkUsedTemplateParameters(SemaRef, VecType->getElementType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002733 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002734 MarkUsedTemplateParameters(SemaRef, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002735 Depth, Used);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00002736 break;
2737 }
2738
Douglas Gregor031a5882009-06-13 00:26:55 +00002739 case Type::FunctionProto: {
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002740 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00002741 MarkUsedTemplateParameters(SemaRef, Proto->getResultType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002742 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002743 for (unsigned I = 0, N = Proto->getNumArgs(); I != N; ++I)
Douglas Gregore73bb602009-09-14 21:25:05 +00002744 MarkUsedTemplateParameters(SemaRef, Proto->getArgType(I), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002745 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002746 break;
2747 }
2748
Douglas Gregored9c0f92009-10-29 00:04:11 +00002749 case Type::TemplateTypeParm: {
2750 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
2751 if (TTP->getDepth() == Depth)
2752 Used[TTP->getIndex()] = true;
Douglas Gregor031a5882009-06-13 00:26:55 +00002753 break;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002754 }
Douglas Gregor031a5882009-06-13 00:26:55 +00002755
John McCall31f17ec2010-04-27 00:57:59 +00002756 case Type::InjectedClassName:
2757 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
2758 // fall through
2759
Douglas Gregor031a5882009-06-13 00:26:55 +00002760 case Type::TemplateSpecialization: {
Mike Stump1eb44332009-09-09 15:08:12 +00002761 const TemplateSpecializationType *Spec
Douglas Gregorf6ddb732009-06-18 18:45:36 +00002762 = cast<TemplateSpecializationType>(T);
Douglas Gregore73bb602009-09-14 21:25:05 +00002763 MarkUsedTemplateParameters(SemaRef, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002764 Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002765 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002766 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
2767 Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002768 break;
2769 }
2770
Douglas Gregore73bb602009-09-14 21:25:05 +00002771 case Type::Complex:
2772 if (!OnlyDeduced)
2773 MarkUsedTemplateParameters(SemaRef,
2774 cast<ComplexType>(T)->getElementType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002775 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002776 break;
2777
Douglas Gregor4714c122010-03-31 17:34:00 +00002778 case Type::DependentName:
Douglas Gregore73bb602009-09-14 21:25:05 +00002779 if (!OnlyDeduced)
2780 MarkUsedTemplateParameters(SemaRef,
Douglas Gregor4714c122010-03-31 17:34:00 +00002781 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002782 OnlyDeduced, Depth, Used);
Douglas Gregore73bb602009-09-14 21:25:05 +00002783 break;
2784
John McCall33500952010-06-11 00:33:02 +00002785 case Type::DependentTemplateSpecialization: {
2786 const DependentTemplateSpecializationType *Spec
2787 = cast<DependentTemplateSpecializationType>(T);
2788 if (!OnlyDeduced)
2789 MarkUsedTemplateParameters(SemaRef, Spec->getQualifier(),
2790 OnlyDeduced, Depth, Used);
2791 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
2792 MarkUsedTemplateParameters(SemaRef, Spec->getArg(I), OnlyDeduced, Depth,
2793 Used);
2794 break;
2795 }
2796
John McCallad5e7382010-03-01 23:49:17 +00002797 case Type::TypeOf:
2798 if (!OnlyDeduced)
2799 MarkUsedTemplateParameters(SemaRef,
2800 cast<TypeOfType>(T)->getUnderlyingType(),
2801 OnlyDeduced, Depth, Used);
2802 break;
2803
2804 case Type::TypeOfExpr:
2805 if (!OnlyDeduced)
2806 MarkUsedTemplateParameters(SemaRef,
2807 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
2808 OnlyDeduced, Depth, Used);
2809 break;
2810
2811 case Type::Decltype:
2812 if (!OnlyDeduced)
2813 MarkUsedTemplateParameters(SemaRef,
2814 cast<DecltypeType>(T)->getUnderlyingExpr(),
2815 OnlyDeduced, Depth, Used);
2816 break;
2817
Douglas Gregore73bb602009-09-14 21:25:05 +00002818 // None of these types have any template parameters in them.
Douglas Gregor031a5882009-06-13 00:26:55 +00002819 case Type::Builtin:
Douglas Gregor031a5882009-06-13 00:26:55 +00002820 case Type::VariableArray:
2821 case Type::FunctionNoProto:
2822 case Type::Record:
2823 case Type::Enum:
Douglas Gregor031a5882009-06-13 00:26:55 +00002824 case Type::ObjCInterface:
John McCallc12c5bb2010-05-15 11:32:37 +00002825 case Type::ObjCObject:
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002826 case Type::ObjCObjectPointer:
John McCalled976492009-12-04 22:46:56 +00002827 case Type::UnresolvedUsing:
Douglas Gregor031a5882009-06-13 00:26:55 +00002828#define TYPE(Class, Base)
2829#define ABSTRACT_TYPE(Class, Base)
2830#define DEPENDENT_TYPE(Class, Base)
2831#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2832#include "clang/AST/TypeNodes.def"
2833 break;
2834 }
2835}
2836
Douglas Gregore73bb602009-09-14 21:25:05 +00002837/// \brief Mark the template parameters that are used by this
Douglas Gregor031a5882009-06-13 00:26:55 +00002838/// template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00002839static void
Douglas Gregore73bb602009-09-14 21:25:05 +00002840MarkUsedTemplateParameters(Sema &SemaRef,
2841 const TemplateArgument &TemplateArg,
2842 bool OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002843 unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002844 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00002845 switch (TemplateArg.getKind()) {
2846 case TemplateArgument::Null:
2847 case TemplateArgument::Integral:
Douglas Gregor788cd062009-11-11 01:00:40 +00002848 case TemplateArgument::Declaration:
Douglas Gregor031a5882009-06-13 00:26:55 +00002849 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Douglas Gregor031a5882009-06-13 00:26:55 +00002851 case TemplateArgument::Type:
Douglas Gregore73bb602009-09-14 21:25:05 +00002852 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002853 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002854 break;
2855
Douglas Gregor788cd062009-11-11 01:00:40 +00002856 case TemplateArgument::Template:
2857 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsTemplate(),
2858 OnlyDeduced, Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002859 break;
2860
2861 case TemplateArgument::Expression:
Douglas Gregore73bb602009-09-14 21:25:05 +00002862 MarkUsedTemplateParameters(SemaRef, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002863 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002864 break;
Douglas Gregore73bb602009-09-14 21:25:05 +00002865
Anders Carlssond01b1da2009-06-15 17:04:53 +00002866 case TemplateArgument::Pack:
Douglas Gregore73bb602009-09-14 21:25:05 +00002867 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
2868 PEnd = TemplateArg.pack_end();
2869 P != PEnd; ++P)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002870 MarkUsedTemplateParameters(SemaRef, *P, OnlyDeduced, Depth, Used);
Anders Carlssond01b1da2009-06-15 17:04:53 +00002871 break;
Douglas Gregor031a5882009-06-13 00:26:55 +00002872 }
2873}
2874
2875/// \brief Mark the template parameters can be deduced by the given
2876/// template argument list.
2877///
2878/// \param TemplateArgs the template argument list from which template
2879/// parameters will be deduced.
2880///
2881/// \param Deduced a bit vector whose elements will be set to \c true
2882/// to indicate when the corresponding template parameter will be
2883/// deduced.
Mike Stump1eb44332009-09-09 15:08:12 +00002884void
Douglas Gregore73bb602009-09-14 21:25:05 +00002885Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002886 bool OnlyDeduced, unsigned Depth,
Douglas Gregore73bb602009-09-14 21:25:05 +00002887 llvm::SmallVectorImpl<bool> &Used) {
Douglas Gregor031a5882009-06-13 00:26:55 +00002888 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002889 ::MarkUsedTemplateParameters(*this, TemplateArgs[I], OnlyDeduced,
2890 Depth, Used);
Douglas Gregor031a5882009-06-13 00:26:55 +00002891}
Douglas Gregor63f07c52009-09-18 23:21:38 +00002892
2893/// \brief Marks all of the template parameters that will be deduced by a
2894/// call to the given function template.
Douglas Gregor02024a92010-03-28 02:42:43 +00002895void
2896Sema::MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate,
2897 llvm::SmallVectorImpl<bool> &Deduced) {
Douglas Gregor63f07c52009-09-18 23:21:38 +00002898 TemplateParameterList *TemplateParams
2899 = FunctionTemplate->getTemplateParameters();
2900 Deduced.clear();
2901 Deduced.resize(TemplateParams->size());
2902
2903 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2904 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
2905 ::MarkUsedTemplateParameters(*this, Function->getParamDecl(I)->getType(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002906 true, TemplateParams->getDepth(), Deduced);
Douglas Gregor63f07c52009-09-18 23:21:38 +00002907}