blob: 008b833bf0c518f51299c817800c9ec07cdd55f0 [file] [log] [blame]
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001//===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===/
12
John McCall19c1bfd2010-08-25 05:32:35 +000013#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000015#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000016#include "clang/AST/ASTLambda.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000018#include "clang/AST/DeclTemplate.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000019#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/StmtVisitor.h"
22#include "clang/Sema/DeclSpec.h"
23#include "clang/Sema/Sema.h"
24#include "clang/Sema/Template.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000025#include "llvm/ADT/SmallBitVector.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000026#include <algorithm>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000027
28namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000029 using namespace sema;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000030 /// \brief Various flags that control template argument deduction.
31 ///
32 /// These flags can be bitwise-OR'd together.
33 enum TemplateDeductionFlags {
34 /// \brief No template argument deduction flags, which indicates the
35 /// strictest results for template argument deduction (as used for, e.g.,
36 /// matching class template partial specializations).
37 TDF_None = 0,
38 /// \brief Within template argument deduction from a function call, we are
39 /// matching with a parameter type for which the original parameter was
40 /// a reference.
41 TDF_ParamWithReferenceType = 0x1,
42 /// \brief Within template argument deduction from a function call, we
43 /// are matching in a case where we ignore cv-qualifiers.
44 TDF_IgnoreQualifiers = 0x02,
45 /// \brief Within template argument deduction from a function call,
46 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000047 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000048 TDF_DerivedClass = 0x04,
49 /// \brief Allow non-dependent types to differ, e.g., when performing
50 /// template argument deduction from a function call where conversions
51 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000052 TDF_SkipNonDependent = 0x08,
53 /// \brief Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000054 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000055 TDF_TopLevelParameterTypeList = 0x10,
56 /// \brief Within template argument deduction from overload resolution per
57 /// C++ [over.over] allow matching function types that are compatible in
58 /// terms of noreturn and default calling convention adjustments.
59 TDF_InOverloadResolution = 0x20
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000060 };
61}
62
Douglas Gregor55ca8f62009-06-04 00:03:07 +000063using namespace clang;
64
Douglas Gregor0a29a052010-03-26 05:50:28 +000065/// \brief Compare two APSInts, extending and switching the sign as
66/// necessary to compare their values regardless of underlying type.
67static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
68 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000069 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000070 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +000071 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +000072
73 // If there is a signedness mismatch, correct it.
74 if (X.isSigned() != Y.isSigned()) {
75 // If the signed value is negative, then the values cannot be the same.
76 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
77 return false;
78
79 Y.setIsSigned(true);
80 X.setIsSigned(true);
81 }
82
83 return X == Y;
84}
85
Douglas Gregor181aa4a2009-06-12 18:26:56 +000086static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +000087DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +000088 TemplateParameterList *TemplateParams,
89 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +000090 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +000091 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +000092 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +000093
Douglas Gregor63814022011-01-21 17:29:42 +000094/// \brief Whether template argument deduction for two reference parameters
95/// resulted in the argument type, parameter type, or neither type being more
96/// qualified than the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000097enum DeductionQualifierComparison {
98 NeitherMoreQualified = 0,
99 ParamMoreQualified,
100 ArgMoreQualified
Douglas Gregorb837ea42011-01-11 17:34:58 +0000101};
102
Douglas Gregor63814022011-01-21 17:29:42 +0000103/// \brief Stores the result of comparing two reference parameters while
104/// performing template argument deduction for partial ordering of function
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000105/// templates.
Douglas Gregor63814022011-01-21 17:29:42 +0000106struct RefParamPartialOrderingComparison {
107 /// \brief Whether the parameter type is an rvalue reference type.
108 bool ParamIsRvalueRef;
109 /// \brief Whether the argument type is an rvalue reference type.
110 bool ArgIsRvalueRef;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000111
Douglas Gregor63814022011-01-21 17:29:42 +0000112 /// \brief Whether the parameter or argument (or neither) is more qualified.
113 DeductionQualifierComparison Qualifiers;
114};
115
116
Douglas Gregorb837ea42011-01-11 17:34:58 +0000117
Douglas Gregor7baabef2010-12-22 18:17:10 +0000118static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000119DeduceTemplateArgumentsByTypeMatch(Sema &S,
120 TemplateParameterList *TemplateParams,
121 QualType Param,
122 QualType Arg,
123 TemplateDeductionInfo &Info,
124 SmallVectorImpl<DeducedTemplateArgument> &
125 Deduced,
126 unsigned TDF,
127 bool PartialOrdering = false,
128 SmallVectorImpl<RefParamPartialOrderingComparison> *
Craig Topperc3ec1492014-05-26 06:22:03 +0000129 RefParamComparisons = nullptr);
Douglas Gregor5499af42011-01-05 23:12:31 +0000130
131static Sema::TemplateDeductionResult
132DeduceTemplateArguments(Sema &S,
133 TemplateParameterList *TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000134 const TemplateArgument *Params, unsigned NumParams,
135 const TemplateArgument *Args, unsigned NumArgs,
136 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +0000137 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000138
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000139/// \brief If the given expression is of a form that permits the deduction
140/// of a non-type template parameter, return the declaration of that
141/// non-type template parameter.
142static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000143 // If we are within an alias template, the expression may have undergone
144 // any number of parameter substitutions already.
145 while (1) {
146 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
147 E = IC->getSubExpr();
148 else if (SubstNonTypeTemplateParmExpr *Subst =
149 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
150 E = Subst->getReplacement();
151 else
152 break;
153 }
Mike Stump11289f42009-09-09 15:08:12 +0000154
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
156 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000157
Craig Topperc3ec1492014-05-26 06:22:03 +0000158 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000159}
160
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000161/// \brief Determine whether two declaration pointers refer to the same
162/// declaration.
163static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000164 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
165 X = NX->getUnderlyingDecl();
166 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
167 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000168
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000169 return X->getCanonicalDecl() == Y->getCanonicalDecl();
170}
171
172/// \brief Verify that the given, deduced template arguments are compatible.
173///
174/// \returns The deduced template argument, or a NULL template argument if
175/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000177checkDeducedTemplateArguments(ASTContext &Context,
178 const DeducedTemplateArgument &X,
179 const DeducedTemplateArgument &Y) {
180 // We have no deduction for one or both of the arguments; they're compatible.
181 if (X.isNull())
182 return Y;
183 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000185
186 switch (X.getKind()) {
187 case TemplateArgument::Null:
188 llvm_unreachable("Non-deduced template arguments handled above");
189
190 case TemplateArgument::Type:
191 // If two template type arguments have the same type, they're compatible.
192 if (Y.getKind() == TemplateArgument::Type &&
193 Context.hasSameType(X.getAsType(), Y.getAsType()))
194 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000196 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000198 case TemplateArgument::Integral:
199 // If we deduced a constant in one case and either a dependent expression or
200 // declaration in another case, keep the integral constant.
201 // If both are integral constants with the same value, keep that value.
202 if (Y.getKind() == TemplateArgument::Expression ||
203 Y.getKind() == TemplateArgument::Declaration ||
204 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000205 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000206 return DeducedTemplateArgument(X,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000207 X.wasDeducedFromArrayBound() &&
208 Y.wasDeducedFromArrayBound());
209
210 // All other combinations are incompatible.
211 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000213 case TemplateArgument::Template:
214 if (Y.getKind() == TemplateArgument::Template &&
215 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
216 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000217
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000218 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000220
221 case TemplateArgument::TemplateExpansion:
222 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000223 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000224 Y.getAsTemplateOrTemplatePattern()))
225 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000226
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000227 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000228 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000229
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000230 case TemplateArgument::Expression:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000231 // If we deduced a dependent expression in one case and either an integral
232 // constant or a declaration in another case, keep the integral constant
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000233 // or declaration.
234 if (Y.getKind() == TemplateArgument::Integral ||
235 Y.getKind() == TemplateArgument::Declaration)
236 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
237 Y.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000238
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000239 if (Y.getKind() == TemplateArgument::Expression) {
240 // Compare the expressions for equality
241 llvm::FoldingSetNodeID ID1, ID2;
242 X.getAsExpr()->Profile(ID1, Context, true);
243 Y.getAsExpr()->Profile(ID2, Context, true);
244 if (ID1 == ID2)
245 return X;
246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000247
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000248 // All other combinations are incompatible.
249 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000250
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000251 case TemplateArgument::Declaration:
252 // If we deduced a declaration and a dependent expression, keep the
253 // declaration.
254 if (Y.getKind() == TemplateArgument::Expression)
255 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000256
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000257 // If we deduced a declaration and an integral constant, keep the
258 // integral constant.
259 if (Y.getKind() == TemplateArgument::Integral)
260 return Y;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000261
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000262 // If we deduced two declarations, make sure they they refer to the
263 // same declaration.
264 if (Y.getKind() == TemplateArgument::Declaration &&
Eli Friedmanb826a002012-09-26 02:36:12 +0000265 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) &&
266 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam())
267 return X;
268
269 // All other combinations are incompatible.
270 return DeducedTemplateArgument();
271
272 case TemplateArgument::NullPtr:
273 // If we deduced a null pointer and a dependent expression, keep the
274 // null pointer.
275 if (Y.getKind() == TemplateArgument::Expression)
276 return X;
277
278 // If we deduced a null pointer and an integral constant, keep the
279 // integral constant.
280 if (Y.getKind() == TemplateArgument::Integral)
281 return Y;
282
283 // If we deduced two null pointers, make sure they have the same type.
284 if (Y.getKind() == TemplateArgument::NullPtr &&
285 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000286 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000288 // All other combinations are incompatible.
289 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000291 case TemplateArgument::Pack:
292 if (Y.getKind() != TemplateArgument::Pack ||
293 X.pack_size() != Y.pack_size())
294 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295
296 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000297 XAEnd = X.pack_end(),
298 YA = Y.pack_begin();
299 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000300 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301 if (checkDeducedTemplateArguments(Context,
302 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000303 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
304 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000305 return DeducedTemplateArgument();
306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000307
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000308 return X;
309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310
David Blaikiee4d798f2012-01-20 21:50:17 +0000311 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000312}
313
Mike Stump11289f42009-09-09 15:08:12 +0000314/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000315/// from the given constant.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000316static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000317DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump11289f42009-09-09 15:08:12 +0000318 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor0a29a052010-03-26 05:50:28 +0000319 llvm::APSInt Value, QualType ValueType,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000320 bool DeducedFromArrayBound,
John McCall19c1bfd2010-08-25 05:32:35 +0000321 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000322 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000323 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000324 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000325
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000326 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
327 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000328 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000329 Deduced[NTTP->getIndex()],
330 NewDeduced);
331 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000332 Info.Param = NTTP;
333 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000334 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000335 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000336 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000337
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000338 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000339 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000340}
341
Mike Stump11289f42009-09-09 15:08:12 +0000342/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000343/// from the given type- or value-dependent expression.
344///
345/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000346static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000347DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000348 NonTypeTemplateParmDecl *NTTP,
349 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000350 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000351 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000352 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000353 "Cannot deduce non-type template argument with depth > 0");
354 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
355 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000357 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000358 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
359 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000360 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000361
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000362 if (Result.isNull()) {
363 Info.Param = NTTP;
364 Info.FirstArg = Deduced[NTTP->getIndex()];
365 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000366 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000369 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000370 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000371}
372
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000373/// \brief Deduce the value of the given non-type template parameter
374/// from the given declaration.
375///
376/// \returns true if deduction succeeded, false otherwise.
377static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000378DeduceNonTypeTemplateArgument(Sema &S,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000379 NonTypeTemplateParmDecl *NTTP,
380 ValueDecl *D,
381 TemplateDeductionInfo &Info,
382 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000383 assert(NTTP->getDepth() == 0 &&
384 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385
Craig Topperc3ec1492014-05-26 06:22:03 +0000386 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Eli Friedmanb826a002012-09-26 02:36:12 +0000387 TemplateArgument New(D, NTTP->getType()->isReferenceType());
388 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000390 Deduced[NTTP->getIndex()],
391 NewDeduced);
392 if (Result.isNull()) {
393 Info.Param = NTTP;
394 Info.FirstArg = Deduced[NTTP->getIndex()];
395 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000396 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000398
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000399 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000400 return Sema::TDK_Success;
401}
402
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000403static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000404DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000405 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000406 TemplateName Param,
407 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000408 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000409 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000410 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000411 if (!ParamDecl) {
412 // The parameter type is dependent and is not a template template parameter,
413 // so there is nothing that we can deduce.
414 return Sema::TDK_Success;
415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000416
Douglas Gregoradee3e32009-11-11 23:06:43 +0000417 if (TemplateTemplateParmDecl *TempParam
418 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000419 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000421 Deduced[TempParam->getIndex()],
422 NewDeduced);
423 if (Result.isNull()) {
424 Info.Param = TempParam;
425 Info.FirstArg = Deduced[TempParam->getIndex()];
426 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000429
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000430 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000431 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000433
Douglas Gregoradee3e32009-11-11 23:06:43 +0000434 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000435 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000436 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437
Douglas Gregoradee3e32009-11-11 23:06:43 +0000438 // Mismatch of non-dependent template parameter to argument.
439 Info.FirstArg = TemplateArgument(Param);
440 Info.SecondArg = TemplateArgument(Arg);
441 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000442}
443
Mike Stump11289f42009-09-09 15:08:12 +0000444/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000445/// type (which is a template-id) with the template argument type.
446///
Chandler Carruthc1263112010-02-07 21:33:28 +0000447/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000448///
449/// \param TemplateParams the template parameters that we are deducing
450///
451/// \param Param the parameter type
452///
453/// \param Arg the argument type
454///
455/// \param Info information about the template argument deduction itself
456///
457/// \param Deduced the deduced template arguments
458///
459/// \returns the result of template argument deduction so far. Note that a
460/// "success" result means that template argument deduction has not yet failed,
461/// but it may still fail, later, for other reasons.
462static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000463DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000464 TemplateParameterList *TemplateParams,
465 const TemplateSpecializationType *Param,
466 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000467 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000468 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000469 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregore81f3e72009-07-07 23:09:34 +0000471 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000472 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000473 = dyn_cast<TemplateSpecializationType>(Arg)) {
474 // Perform template argument deduction for the template name.
475 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000476 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000477 Param->getTemplateName(),
478 SpecArg->getTemplateName(),
479 Info, Deduced))
480 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000481
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregore81f3e72009-07-07 23:09:34 +0000483 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000484 // argument. Ignore any missing/extra arguments, since they could be
485 // filled in by default arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486 return DeduceTemplateArguments(S, TemplateParams,
487 Param->getArgs(), Param->getNumArgs(),
Douglas Gregord80ea202010-12-22 18:55:49 +0000488 SpecArg->getArgs(), SpecArg->getNumArgs(),
Richard Smith16b65392012-12-06 06:44:44 +0000489 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000490 }
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregore81f3e72009-07-07 23:09:34 +0000492 // If the argument type is a class template specialization, we
493 // perform template argument deduction using its template
494 // arguments.
495 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000496 if (!RecordArg) {
497 Info.FirstArg = TemplateArgument(QualType(Param, 0));
498 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000499 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000500 }
Mike Stump11289f42009-09-09 15:08:12 +0000501
502 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000503 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000504 if (!SpecArg) {
505 Info.FirstArg = TemplateArgument(QualType(Param, 0));
506 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000507 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
Douglas Gregore81f3e72009-07-07 23:09:34 +0000510 // Perform template argument deduction for the template name.
511 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000512 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000513 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000514 Param->getTemplateName(),
515 TemplateName(SpecArg->getSpecializedTemplate()),
516 Info, Deduced))
517 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000518
Douglas Gregor7baabef2010-12-22 18:17:10 +0000519 // Perform template argument deduction for the template arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000520 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000521 Param->getArgs(), Param->getNumArgs(),
522 SpecArg->getTemplateArgs().data(),
523 SpecArg->getTemplateArgs().size(),
524 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000525}
526
John McCall08569062010-08-28 22:14:41 +0000527/// \brief Determines whether the given type is an opaque type that
528/// might be more qualified when instantiated.
529static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
530 switch (T->getTypeClass()) {
531 case Type::TypeOfExpr:
532 case Type::TypeOf:
533 case Type::DependentName:
534 case Type::Decltype:
535 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000536 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000537 return true;
538
539 case Type::ConstantArray:
540 case Type::IncompleteArray:
541 case Type::VariableArray:
542 case Type::DependentSizedArray:
543 return IsPossiblyOpaquelyQualifiedType(
544 cast<ArrayType>(T)->getElementType());
545
546 default:
547 return false;
548 }
549}
550
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000551/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000553getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000554 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
555 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556
Douglas Gregor5499af42011-01-05 23:12:31 +0000557 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
558 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000559
Douglas Gregor5499af42011-01-05 23:12:31 +0000560 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
561 return std::make_pair(TTP->getDepth(), TTP->getIndex());
562}
563
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000564/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000566getDepthAndIndex(UnexpandedParameterPack UPP) {
567 if (const TemplateTypeParmType *TTP
568 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
569 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000571 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
572}
573
Douglas Gregor5499af42011-01-05 23:12:31 +0000574/// \brief Helper function to build a TemplateParameter when we don't
575/// know its type statically.
576static TemplateParameter makeTemplateParameter(Decl *D) {
577 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
578 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000579 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000580 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581
Douglas Gregor5499af42011-01-05 23:12:31 +0000582 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
583}
584
Richard Smith0a80d572014-05-29 01:12:14 +0000585/// A pack that we're currently deducing.
586struct clang::DeducedPack {
587 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000588
Richard Smith0a80d572014-05-29 01:12:14 +0000589 // The index of the pack.
590 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Richard Smith0a80d572014-05-29 01:12:14 +0000592 // The old value of the pack before we started deducing it.
593 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000594
Richard Smith0a80d572014-05-29 01:12:14 +0000595 // A deferred value of this pack from an inner deduction, that couldn't be
596 // deduced because this deduction hadn't happened yet.
597 DeducedTemplateArgument DeferredDeduction;
598
599 // The new value of the pack.
600 SmallVector<DeducedTemplateArgument, 4> New;
601
602 // The outer deduction for this pack, if any.
603 DeducedPack *Outer;
604};
605
606/// A scope in which we're performing pack deduction.
607class PackDeductionScope {
608public:
609 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
610 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
611 TemplateDeductionInfo &Info, TemplateArgument Pattern)
612 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
613 // Compute the set of template parameter indices that correspond to
614 // parameter packs expanded by the pack expansion.
615 {
616 llvm::SmallBitVector SawIndices(TemplateParams->size());
617 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
618 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
619 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
620 unsigned Depth, Index;
621 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
622 if (Depth == 0 && !SawIndices[Index]) {
623 SawIndices[Index] = true;
624
625 // Save the deduced template argument for the parameter pack expanded
626 // by this pack expansion, then clear out the deduction.
627 DeducedPack Pack(Index);
628 Pack.Saved = Deduced[Index];
629 Deduced[Index] = TemplateArgument();
630
631 Packs.push_back(Pack);
632 }
633 }
634 }
635 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
636
637 for (auto &Pack : Packs) {
638 if (Info.PendingDeducedPacks.size() > Pack.Index)
639 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
640 else
641 Info.PendingDeducedPacks.resize(Pack.Index + 1);
642 Info.PendingDeducedPacks[Pack.Index] = &Pack;
643
644 if (S.CurrentInstantiationScope) {
645 // If the template argument pack was explicitly specified, add that to
646 // the set of deduced arguments.
647 const TemplateArgument *ExplicitArgs;
648 unsigned NumExplicitArgs;
649 NamedDecl *PartiallySubstitutedPack =
650 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
651 &ExplicitArgs, &NumExplicitArgs);
652 if (PartiallySubstitutedPack &&
653 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
654 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
655 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000656 }
657 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000658
Richard Smith0a80d572014-05-29 01:12:14 +0000659 ~PackDeductionScope() {
660 for (auto &Pack : Packs)
661 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Richard Smith0a80d572014-05-29 01:12:14 +0000664 /// Move to deducing the next element in each pack that is being deduced.
665 void nextPackElement() {
666 // Capture the deduced template arguments for each parameter pack expanded
667 // by this pack expansion, add them to the list of arguments we've deduced
668 // for that pack, then clear out the deduced argument.
669 for (auto &Pack : Packs) {
670 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
671 if (!DeducedArg.isNull()) {
672 Pack.New.push_back(DeducedArg);
673 DeducedArg = DeducedTemplateArgument();
674 }
675 }
676 }
677
678 /// \brief Finish template argument deduction for a set of argument packs,
679 /// producing the argument packs and checking for consistency with prior
680 /// deductions.
681 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
682 // Build argument packs for each of the parameter packs expanded by this
683 // pack expansion.
684 for (auto &Pack : Packs) {
685 // Put back the old value for this pack.
686 Deduced[Pack.Index] = Pack.Saved;
687
688 // Build or find a new value for this pack.
689 DeducedTemplateArgument NewPack;
690 if (HasAnyArguments && Pack.New.empty()) {
691 if (Pack.DeferredDeduction.isNull()) {
692 // We were not able to deduce anything for this parameter pack
693 // (because it only appeared in non-deduced contexts), so just
694 // restore the saved argument pack.
695 continue;
696 }
697
698 NewPack = Pack.DeferredDeduction;
699 Pack.DeferredDeduction = TemplateArgument();
700 } else if (Pack.New.empty()) {
701 // If we deduced an empty argument pack, create it now.
702 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
703 } else {
704 TemplateArgument *ArgumentPack =
705 new (S.Context) TemplateArgument[Pack.New.size()];
706 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
707 NewPack = DeducedTemplateArgument(
708 TemplateArgument(ArgumentPack, Pack.New.size()),
709 Pack.New[0].wasDeducedFromArrayBound());
710 }
711
712 // Pick where we're going to put the merged pack.
713 DeducedTemplateArgument *Loc;
714 if (Pack.Outer) {
715 if (Pack.Outer->DeferredDeduction.isNull()) {
716 // Defer checking this pack until we have a complete pack to compare
717 // it against.
718 Pack.Outer->DeferredDeduction = NewPack;
719 continue;
720 }
721 Loc = &Pack.Outer->DeferredDeduction;
722 } else {
723 Loc = &Deduced[Pack.Index];
724 }
725
726 // Check the new pack matches any previous value.
727 DeducedTemplateArgument OldPack = *Loc;
728 DeducedTemplateArgument Result =
729 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
730
731 // If we deferred a deduction of this pack, check that one now too.
732 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
733 OldPack = Result;
734 NewPack = Pack.DeferredDeduction;
735 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
736 }
737
738 if (Result.isNull()) {
739 Info.Param =
740 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
741 Info.FirstArg = OldPack;
742 Info.SecondArg = NewPack;
743 return Sema::TDK_Inconsistent;
744 }
745
746 *Loc = Result;
747 }
748
749 return Sema::TDK_Success;
750 }
751
752private:
753 Sema &S;
754 TemplateParameterList *TemplateParams;
755 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
756 TemplateDeductionInfo &Info;
757
758 SmallVector<DeducedPack, 2> Packs;
759};
Douglas Gregorb94a6172011-01-10 17:53:52 +0000760
Douglas Gregor5499af42011-01-05 23:12:31 +0000761/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000762/// types to the list of argument types, as in the parameter-type-lists of
763/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000764///
765/// \param S The semantic analysis object within which we are deducing
766///
767/// \param TemplateParams The template parameters that we are deducing
768///
769/// \param Params The list of parameter types
770///
771/// \param NumParams The number of types in \c Params
772///
773/// \param Args The list of argument types
774///
775/// \param NumArgs The number of types in \c Args
776///
777/// \param Info information about the template argument deduction itself
778///
779/// \param Deduced the deduced template arguments
780///
781/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
782/// how template argument deduction is performed.
783///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000784/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000785/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000786/// (C++0x [temp.deduct.partial]).
787///
Douglas Gregor63814022011-01-21 17:29:42 +0000788/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +0000789/// in the context of partial ordering, the set of qualifier comparisons.
790///
Douglas Gregor5499af42011-01-05 23:12:31 +0000791/// \returns the result of template argument deduction so far. Note that a
792/// "success" result means that template argument deduction has not yet failed,
793/// but it may still fail, later, for other reasons.
794static Sema::TemplateDeductionResult
795DeduceTemplateArguments(Sema &S,
796 TemplateParameterList *TemplateParams,
797 const QualType *Params, unsigned NumParams,
798 const QualType *Args, unsigned NumArgs,
799 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000800 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000801 unsigned TDF,
802 bool PartialOrdering = false,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000803 SmallVectorImpl<RefParamPartialOrderingComparison> *
Craig Topperc3ec1492014-05-26 06:22:03 +0000804 RefParamComparisons = nullptr) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000805 // Fast-path check to see if we have too many/too few arguments.
806 if (NumParams != NumArgs &&
807 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
808 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000809 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
Douglas Gregor5499af42011-01-05 23:12:31 +0000811 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812 // Similarly, if P has a form that contains (T), then each parameter type
813 // Pi of the respective parameter-type- list of P is compared with the
814 // corresponding parameter type Ai of the corresponding parameter-type-list
815 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000816 unsigned ArgIdx = 0, ParamIdx = 0;
817 for (; ParamIdx != NumParams; ++ParamIdx) {
818 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000820 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
821 if (!Expansion) {
822 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000823
Douglas Gregor5499af42011-01-05 23:12:31 +0000824 // Make sure we have an argument.
825 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000826 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000828 if (isa<PackExpansionType>(Args[ArgIdx])) {
829 // C++0x [temp.deduct.type]p22:
830 // If the original function parameter associated with A is a function
831 // parameter pack and the function parameter associated with P is not
832 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000833 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000835
Douglas Gregor5499af42011-01-05 23:12:31 +0000836 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000837 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
838 Params[ParamIdx], Args[ArgIdx],
839 Info, Deduced, TDF,
840 PartialOrdering,
841 RefParamComparisons))
Douglas Gregor5499af42011-01-05 23:12:31 +0000842 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843
Douglas Gregor5499af42011-01-05 23:12:31 +0000844 ++ArgIdx;
845 continue;
846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000848 // C++0x [temp.deduct.type]p5:
849 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000851 // parameter-declaration-clause.
852 if (ParamIdx + 1 < NumParams)
853 return Sema::TDK_Success;
854
Douglas Gregor5499af42011-01-05 23:12:31 +0000855 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000857 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000858 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000859 // comparison deduces template arguments for subsequent positions in the
860 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000861
Douglas Gregor5499af42011-01-05 23:12:31 +0000862 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000863 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000864
Douglas Gregor5499af42011-01-05 23:12:31 +0000865 bool HasAnyArguments = false;
866 for (; ArgIdx < NumArgs; ++ArgIdx) {
867 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868
Douglas Gregor5499af42011-01-05 23:12:31 +0000869 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000871 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
872 Args[ArgIdx], Info, Deduced,
873 TDF, PartialOrdering,
874 RefParamComparisons))
Douglas Gregor5499af42011-01-05 23:12:31 +0000875 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876
Richard Smith0a80d572014-05-29 01:12:14 +0000877 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000879
Douglas Gregor5499af42011-01-05 23:12:31 +0000880 // Build argument packs for each of the parameter packs expanded by this
881 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000882 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000883 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000885
Douglas Gregor5499af42011-01-05 23:12:31 +0000886 // Make sure we don't have any extra arguments.
887 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000888 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889
Douglas Gregor5499af42011-01-05 23:12:31 +0000890 return Sema::TDK_Success;
891}
892
Douglas Gregor1d684c22011-04-28 00:56:09 +0000893/// \brief Determine whether the parameter has qualifiers that are either
894/// inconsistent with or a superset of the argument's qualifiers.
895static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
896 QualType ArgType) {
897 Qualifiers ParamQs = ParamType.getQualifiers();
898 Qualifiers ArgQs = ArgType.getQualifiers();
899
900 if (ParamQs == ArgQs)
901 return false;
902
903 // Mismatched (but not missing) Objective-C GC attributes.
904 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
905 ParamQs.hasObjCGCAttr())
906 return true;
907
908 // Mismatched (but not missing) address spaces.
909 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
910 ParamQs.hasAddressSpace())
911 return true;
912
John McCall31168b02011-06-15 23:02:42 +0000913 // Mismatched (but not missing) Objective-C lifetime qualifiers.
914 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
915 ParamQs.hasObjCLifetime())
916 return true;
917
Douglas Gregor1d684c22011-04-28 00:56:09 +0000918 // CVR qualifier superset.
919 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
920 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
921 == ParamQs.getCVRQualifiers());
922}
923
Douglas Gregor19a41f12013-04-17 08:45:07 +0000924/// \brief Compare types for equality with respect to possibly compatible
925/// function types (noreturn adjustment, implicit calling conventions). If any
926/// of parameter and argument is not a function, just perform type comparison.
927///
928/// \param Param the template parameter type.
929///
930/// \param Arg the argument type.
931bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
932 CanQualType Arg) {
933 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
934 *ArgFunction = Arg->getAs<FunctionType>();
935
936 // Just compare if not functions.
937 if (!ParamFunction || !ArgFunction)
938 return Param == Arg;
939
940 // Noreturn adjustment.
941 QualType AdjustedParam;
942 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
943 return Arg == Context.getCanonicalType(AdjustedParam);
944
945 // FIXME: Compatible calling conventions.
946
947 return Param == Arg;
948}
949
Douglas Gregorcceb9752009-06-26 18:27:22 +0000950/// \brief Deduce the template arguments by comparing the parameter type and
951/// the argument type (C++ [temp.deduct.type]).
952///
Chandler Carruthc1263112010-02-07 21:33:28 +0000953/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000954///
955/// \param TemplateParams the template parameters that we are deducing
956///
957/// \param ParamIn the parameter type
958///
959/// \param ArgIn the argument type
960///
961/// \param Info information about the template argument deduction itself
962///
963/// \param Deduced the deduced template arguments
964///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000965/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000966/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000967///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000968/// \param PartialOrdering Whether we're performing template argument deduction
969/// in the context of partial ordering (C++0x [temp.deduct.partial]).
970///
Douglas Gregor63814022011-01-21 17:29:42 +0000971/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +0000972/// in the context of partial ordering, the set of qualifier comparisons.
973///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000974/// \returns the result of template argument deduction so far. Note that a
975/// "success" result means that template argument deduction has not yet failed,
976/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000977static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000978DeduceTemplateArgumentsByTypeMatch(Sema &S,
979 TemplateParameterList *TemplateParams,
980 QualType ParamIn, QualType ArgIn,
981 TemplateDeductionInfo &Info,
982 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
983 unsigned TDF,
984 bool PartialOrdering,
985 SmallVectorImpl<RefParamPartialOrderingComparison> *
986 RefParamComparisons) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000987 // We only want to look at the canonical types, since typedefs and
988 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000989 QualType Param = S.Context.getCanonicalType(ParamIn);
990 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000991
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000992 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000994 if (const PackExpansionType *ArgExpansion
995 = dyn_cast<PackExpansionType>(Arg))
996 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000997
Douglas Gregorb837ea42011-01-11 17:34:58 +0000998 if (PartialOrdering) {
999 // C++0x [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001000 // Before the partial ordering is done, certain transformations are
1001 // performed on the types used for partial ordering:
1002 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001003 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1004 if (ParamRef)
1005 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Douglas Gregorb837ea42011-01-11 17:34:58 +00001007 // - If A is a reference type, A is replaced by the type referred to.
1008 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1009 if (ArgRef)
1010 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001011
Douglas Gregor63814022011-01-21 17:29:42 +00001012 if (RefParamComparisons && ParamRef && ArgRef) {
Douglas Gregorb837ea42011-01-11 17:34:58 +00001013 // C++0x [temp.deduct.partial]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001014 // If both P and A were reference types (before being replaced with the
1015 // type referred to above), determine which of the two types (if any) is
Douglas Gregorb837ea42011-01-11 17:34:58 +00001016 // more cv-qualified than the other; otherwise the types are considered
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001017 // to be equally cv-qualified for partial ordering purposes. The result
Douglas Gregorb837ea42011-01-11 17:34:58 +00001018 // of this determination will be used below.
1019 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001020 // We save this information for later, using it only when deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +00001021 // succeeds in both directions.
Douglas Gregor63814022011-01-21 17:29:42 +00001022 RefParamPartialOrderingComparison Comparison;
1023 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
1024 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
1025 Comparison.Qualifiers = NeitherMoreQualified;
Douglas Gregor85894a82011-04-30 17:07:52 +00001026
1027 Qualifiers ParamQuals = Param.getQualifiers();
1028 Qualifiers ArgQuals = Arg.getQualifiers();
1029 if (ParamQuals.isStrictSupersetOf(ArgQuals))
Douglas Gregor63814022011-01-21 17:29:42 +00001030 Comparison.Qualifiers = ParamMoreQualified;
Douglas Gregor85894a82011-04-30 17:07:52 +00001031 else if (ArgQuals.isStrictSupersetOf(ParamQuals))
Douglas Gregor63814022011-01-21 17:29:42 +00001032 Comparison.Qualifiers = ArgMoreQualified;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001033 else if (ArgQuals.getObjCLifetime() != ParamQuals.getObjCLifetime() &&
1034 ArgQuals.withoutObjCLifetime()
1035 == ParamQuals.withoutObjCLifetime()) {
1036 // Prefer binding to non-__unsafe_autoretained parameters.
1037 if (ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1038 ParamQuals.getObjCLifetime())
1039 Comparison.Qualifiers = ParamMoreQualified;
1040 else if (ParamQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1041 ArgQuals.getObjCLifetime())
1042 Comparison.Qualifiers = ArgMoreQualified;
1043 }
Douglas Gregor63814022011-01-21 17:29:42 +00001044 RefParamComparisons->push_back(Comparison);
Douglas Gregorb837ea42011-01-11 17:34:58 +00001045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
Douglas Gregorb837ea42011-01-11 17:34:58 +00001047 // C++0x [temp.deduct.partial]p7:
1048 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001049 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001050 // version of P.
1051 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001052 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001053 // version of A.
1054 Arg = Arg.getUnqualifiedType();
1055 } else {
1056 // C++0x [temp.deduct.call]p4 bullet 1:
1057 // - If the original P is a reference type, the deduced A (i.e., the type
1058 // referred to by the reference) can be more cv-qualified than the
1059 // transformed A.
1060 if (TDF & TDF_ParamWithReferenceType) {
1061 Qualifiers Quals;
1062 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1063 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001064 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001065 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001067
Douglas Gregor85f240c2011-01-25 17:19:08 +00001068 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1069 // C++0x [temp.deduct.type]p10:
1070 // If P and A are function types that originated from deduction when
1071 // taking the address of a function template (14.8.2.2) or when deducing
1072 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001073 // Ai are parameters of the top-level parameter-type-list of P and A,
1074 // respectively, Pi is adjusted if it is an rvalue reference to a
1075 // cv-unqualified template parameter and Ai is an lvalue reference, in
1076 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001077 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1078 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001079 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001080 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001081
Douglas Gregor85f240c2011-01-25 17:19:08 +00001082 if (const RValueReferenceType *ParamRef
1083 = Param->getAs<RValueReferenceType>()) {
1084 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1085 !ParamRef->getPointeeType().getQualifiers())
1086 if (Arg->isLValueReferenceType())
1087 Param = ParamRef->getPointeeType();
1088 }
1089 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001090 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001092 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001093 // A template type argument T, a template template argument TT or a
1094 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001095 // the following forms:
1096 //
1097 // T
1098 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001099 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001100 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001101 // Just skip any attempts to deduce from a placeholder type.
1102 if (Arg->isPlaceholderType())
1103 return Sema::TDK_Success;
1104
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001105 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001106 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Douglas Gregor60454822009-07-22 20:02:25 +00001108 // If the argument type is an array type, move the qualifiers up to the
1109 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001110 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001111 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001112 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001113 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001114 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001115 RecanonicalizeArg = true;
1116 }
1117 }
Mike Stump11289f42009-09-09 15:08:12 +00001118
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001119 // The argument type can not be less qualified than the parameter
1120 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001121 if (!(TDF & TDF_IgnoreQualifiers) &&
1122 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001123 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001124 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001125 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001126 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001127 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001128
1129 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001130 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001131 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001132
Douglas Gregor1d684c22011-04-28 00:56:09 +00001133 // Remove any qualifiers on the parameter from the deduced type.
1134 // We checked the qualifiers for consistency above.
1135 Qualifiers DeducedQs = DeducedType.getQualifiers();
1136 Qualifiers ParamQs = Param.getQualifiers();
1137 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1138 if (ParamQs.hasObjCGCAttr())
1139 DeducedQs.removeObjCGCAttr();
1140 if (ParamQs.hasAddressSpace())
1141 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001142 if (ParamQs.hasObjCLifetime())
1143 DeducedQs.removeObjCLifetime();
Douglas Gregore46db902011-06-17 22:11:49 +00001144
1145 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001146 // If template deduction would produce a lifetime qualifier on a type
1147 // that is not a lifetime type, template argument deduction fails.
1148 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1149 !DeducedType->isDependentType()) {
1150 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1151 Info.FirstArg = TemplateArgument(Param);
1152 Info.SecondArg = TemplateArgument(Arg);
1153 return Sema::TDK_Underqualified;
1154 }
1155
1156 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001157 // If template deduction would produce an argument type with lifetime type
1158 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001159 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001160 DeducedType->isObjCLifetimeType() &&
1161 !DeducedQs.hasObjCLifetime())
1162 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1163
Douglas Gregor1d684c22011-04-28 00:56:09 +00001164 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1165 DeducedQs);
1166
Douglas Gregord6605db2009-07-22 21:30:48 +00001167 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001168 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001169
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001170 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001171 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001172 Deduced[Index],
1173 NewDeduced);
1174 if (Result.isNull()) {
1175 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1176 Info.FirstArg = Deduced[Index];
1177 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001178 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001180
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001181 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001182 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001183 }
1184
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001185 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001186 Info.FirstArg = TemplateArgument(ParamIn);
1187 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001188
Douglas Gregorfb322d82011-01-14 05:11:40 +00001189 // If the parameter is an already-substituted template parameter
1190 // pack, do nothing: we don't know which of its arguments to look
1191 // at, so we have to wait until all of the parameter packs in this
1192 // expansion have arguments.
1193 if (isa<SubstTemplateTypeParmPackType>(Param))
1194 return Sema::TDK_Success;
1195
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001196 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001197 CanQualType CanParam = S.Context.getCanonicalType(Param);
1198 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001199 if (!(TDF & TDF_IgnoreQualifiers)) {
1200 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001201 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001202 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001203 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001204 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001205 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001206 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001207
1208 // If the parameter type is not dependent, there is nothing to deduce.
1209 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001210 if (!(TDF & TDF_SkipNonDependent)) {
1211 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1212 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1213 Param != Arg;
1214 if (NonDeduced) {
1215 return Sema::TDK_NonDeducedMismatch;
1216 }
1217 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001218 return Sema::TDK_Success;
1219 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001220 } else if (!Param->isDependentType()) {
1221 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1222 ArgUnqualType = CanArg.getUnqualifiedType();
1223 bool Success = (TDF & TDF_InOverloadResolution)?
1224 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1225 ArgUnqualType) :
1226 ParamUnqualType == ArgUnqualType;
1227 if (Success)
1228 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001229 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001230
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001231 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001232 // Non-canonical types cannot appear here.
1233#define NON_CANONICAL_TYPE(Class, Base) \
1234 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1235#define TYPE(Class, Base)
1236#include "clang/AST/TypeNodes.def"
1237
1238 case Type::TemplateTypeParm:
1239 case Type::SubstTemplateTypeParmPack:
1240 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001241
1242 // These types cannot be dependent, so simply check whether the types are
1243 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001244 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001245 case Type::VariableArray:
1246 case Type::Vector:
1247 case Type::FunctionNoProto:
1248 case Type::Record:
1249 case Type::Enum:
1250 case Type::ObjCObject:
1251 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001252 case Type::ObjCObjectPointer: {
1253 if (TDF & TDF_SkipNonDependent)
1254 return Sema::TDK_Success;
1255
1256 if (TDF & TDF_IgnoreQualifiers) {
1257 Param = Param.getUnqualifiedType();
1258 Arg = Arg.getUnqualifiedType();
1259 }
1260
1261 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1262 }
1263
Douglas Gregor39c02722011-06-15 16:02:29 +00001264 // _Complex T [placeholder extension]
1265 case Type::Complex:
1266 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001267 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor39c02722011-06-15 16:02:29 +00001268 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001269 ComplexArg->getElementType(),
1270 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001271
1272 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001273
1274 // _Atomic T [extension]
1275 case Type::Atomic:
1276 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001277 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001278 cast<AtomicType>(Param)->getValueType(),
1279 AtomicArg->getValueType(),
1280 Info, Deduced, TDF);
1281
1282 return Sema::TDK_NonDeducedMismatch;
1283
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001284 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001285 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001286 QualType PointeeType;
1287 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1288 PointeeType = PointerArg->getPointeeType();
1289 } else if (const ObjCObjectPointerType *PointerArg
1290 = Arg->getAs<ObjCObjectPointerType>()) {
1291 PointeeType = PointerArg->getPointeeType();
1292 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001293 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001294 }
Mike Stump11289f42009-09-09 15:08:12 +00001295
Douglas Gregorfc516c92009-06-26 23:27:24 +00001296 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001297 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1298 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001299 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001300 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001301 }
Mike Stump11289f42009-09-09 15:08:12 +00001302
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001303 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001304 case Type::LValueReference: {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001305 const LValueReferenceType *ReferenceArg = Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001306 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001307 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001308
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001309 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001310 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001311 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001312 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001313
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001314 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001315 case Type::RValueReference: {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001316 const RValueReferenceType *ReferenceArg = Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001317 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001318 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001319
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001320 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1321 cast<RValueReferenceType>(Param)->getPointeeType(),
1322 ReferenceArg->getPointeeType(),
1323 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001324 }
Mike Stump11289f42009-09-09 15:08:12 +00001325
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001326 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001327 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001328 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001329 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001330 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001331 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001332
John McCallf7332682010-08-19 00:20:19 +00001333 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001334 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1335 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1336 IncompleteArrayArg->getElementType(),
1337 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001338 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001339
1340 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001341 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001342 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001343 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001344 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001345 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001346
1347 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001348 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001349 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001350 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001351
John McCallf7332682010-08-19 00:20:19 +00001352 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001353 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1354 ConstantArrayParm->getElementType(),
1355 ConstantArrayArg->getElementType(),
1356 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001357 }
1358
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001359 // type [i]
1360 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001361 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001362 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001363 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001364
John McCallf7332682010-08-19 00:20:19 +00001365 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1366
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001367 // Check the element type of the arrays
1368 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001369 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001370 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001371 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1372 DependentArrayParm->getElementType(),
1373 ArrayArg->getElementType(),
1374 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001375 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001376
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001377 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001378 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001379 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1380 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001381 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001382
1383 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001384 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001385 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001386 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001387 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001388 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1389 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001390 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001391 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001392 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001393 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001394 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001395 if (const DependentSizedArrayType *DependentArrayArg
1396 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001397 if (DependentArrayArg->getSizeExpr())
1398 return DeduceNonTypeTemplateArgument(S, NTTP,
1399 DependentArrayArg->getSizeExpr(),
1400 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001401
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001402 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001403 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001404 }
Mike Stump11289f42009-09-09 15:08:12 +00001405
1406 // type(*)(T)
1407 // T(*)()
1408 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001409 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001410 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001411 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001412 dyn_cast<FunctionProtoType>(Arg);
1413 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001414 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001415
1416 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001417 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001418
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001419 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001420 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001421 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001422 != FunctionProtoArg->getRefQualifier() ||
1423 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001424 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001425
Anders Carlsson2128ec72009-06-08 15:19:08 +00001426 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001427 if (Sema::TemplateDeductionResult Result =
1428 DeduceTemplateArgumentsByTypeMatch(
1429 S, TemplateParams, FunctionProtoParam->getReturnType(),
1430 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001431 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001432
Alp Toker9cacbab2014-01-20 20:26:09 +00001433 return DeduceTemplateArguments(
1434 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1435 FunctionProtoParam->getNumParams(),
1436 FunctionProtoArg->param_type_begin(),
1437 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001438 }
Mike Stump11289f42009-09-09 15:08:12 +00001439
John McCalle78aac42010-03-10 03:28:59 +00001440 case Type::InjectedClassName: {
1441 // Treat a template's injected-class-name as if the template
1442 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001443 Param = cast<InjectedClassNameType>(Param)
1444 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001445 assert(isa<TemplateSpecializationType>(Param) &&
1446 "injected class name is not a template specialization type");
1447 // fall through
1448 }
1449
Douglas Gregor705c9002009-06-26 20:57:09 +00001450 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001451 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001452 // TT<T>
1453 // TT<i>
1454 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001455 case Type::TemplateSpecialization: {
1456 const TemplateSpecializationType *SpecParam
1457 = cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001458
Douglas Gregore81f3e72009-07-07 23:09:34 +00001459 // Try to deduce template arguments from the template-id.
1460 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001461 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregore81f3e72009-07-07 23:09:34 +00001462 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001463
Douglas Gregor42909752009-09-30 22:13:51 +00001464 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001465 // C++ [temp.deduct.call]p3b3:
1466 // If P is a class, and P has the form template-id, then A can be a
1467 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump11289f42009-09-09 15:08:12 +00001468 // class of the form template-id, A can be a pointer to a derived
Douglas Gregore81f3e72009-07-07 23:09:34 +00001469 // class pointed to by the deduced A.
1470 //
1471 // More importantly:
Mike Stump11289f42009-09-09 15:08:12 +00001472 // These alternatives are considered only if type deduction would
Douglas Gregore81f3e72009-07-07 23:09:34 +00001473 // otherwise fail.
Chandler Carruthc1263112010-02-07 21:33:28 +00001474 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1475 // We cannot inspect base classes as part of deduction when the type
1476 // is incomplete, so either instantiate any templates necessary to
1477 // complete the type, or skip over it if it cannot be completed.
John McCallbc077cf2010-02-08 23:07:23 +00001478 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carruthc1263112010-02-07 21:33:28 +00001479 return Result;
1480
Douglas Gregore81f3e72009-07-07 23:09:34 +00001481 // Use data recursion to crawl through the list of base classes.
Mike Stump11289f42009-09-09 15:08:12 +00001482 // Visited contains the set of nodes we have already visited, while
Douglas Gregore81f3e72009-07-07 23:09:34 +00001483 // ToVisit is our stack of records that we still need to visit.
1484 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001485 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001486 ToVisit.push_back(RecordT);
1487 bool Successful = false;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001488 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1489 Deduced.end());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001490 while (!ToVisit.empty()) {
1491 // Retrieve the next class in the inheritance hierarchy.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001492 const RecordType *NextT = ToVisit.pop_back_val();
Mike Stump11289f42009-09-09 15:08:12 +00001493
Douglas Gregore81f3e72009-07-07 23:09:34 +00001494 // If we have already seen this type, skip it.
1495 if (!Visited.insert(NextT))
1496 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001497
Douglas Gregore81f3e72009-07-07 23:09:34 +00001498 // If this is a base class, try to perform template argument
1499 // deduction from it.
1500 if (NextT != RecordT) {
Richard Trieu23bafad2012-11-07 21:17:13 +00001501 TemplateDeductionInfo BaseInfo(Info.getLocation());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001502 Sema::TemplateDeductionResult BaseResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001503 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Richard Trieu23bafad2012-11-07 21:17:13 +00001504 QualType(NextT, 0), BaseInfo,
1505 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001506
Douglas Gregore81f3e72009-07-07 23:09:34 +00001507 // If template argument deduction for this base was successful,
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001508 // note that we had some success. Otherwise, ignore any deductions
1509 // from this base class.
1510 if (BaseResult == Sema::TDK_Success) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001511 Successful = true;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001512 DeducedOrig.clear();
1513 DeducedOrig.append(Deduced.begin(), Deduced.end());
Richard Trieu23bafad2012-11-07 21:17:13 +00001514 Info.Param = BaseInfo.Param;
1515 Info.FirstArg = BaseInfo.FirstArg;
1516 Info.SecondArg = BaseInfo.SecondArg;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001517 }
1518 else
1519 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001520 }
Mike Stump11289f42009-09-09 15:08:12 +00001521
Douglas Gregore81f3e72009-07-07 23:09:34 +00001522 // Visit base classes
1523 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
Aaron Ballman574705e2014-03-13 15:41:46 +00001524 for (const auto &Base : Next->bases()) {
1525 assert(Base.getType()->isRecordType() &&
Douglas Gregore81f3e72009-07-07 23:09:34 +00001526 "Base class that isn't a record?");
Aaron Ballman574705e2014-03-13 15:41:46 +00001527 ToVisit.push_back(Base.getType()->getAs<RecordType>());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001528 }
1529 }
Mike Stump11289f42009-09-09 15:08:12 +00001530
Douglas Gregore81f3e72009-07-07 23:09:34 +00001531 if (Successful)
1532 return Sema::TDK_Success;
1533 }
Mike Stump11289f42009-09-09 15:08:12 +00001534
Douglas Gregore81f3e72009-07-07 23:09:34 +00001535 }
Mike Stump11289f42009-09-09 15:08:12 +00001536
Douglas Gregore81f3e72009-07-07 23:09:34 +00001537 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001538 }
1539
Douglas Gregor637d9982009-06-10 23:47:09 +00001540 // T type::*
1541 // T T::*
1542 // T (type::*)()
1543 // type (T::*)()
1544 // type (type::*)(T)
1545 // type (T::*)(T)
1546 // T (type::*)(T)
1547 // T (T::*)()
1548 // T (T::*)(T)
1549 case Type::MemberPointer: {
1550 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1551 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1552 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001553 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001554
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001555 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001556 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1557 MemPtrParam->getPointeeType(),
1558 MemPtrArg->getPointeeType(),
1559 Info, Deduced,
1560 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001561 return Result;
1562
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001563 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1564 QualType(MemPtrParam->getClass(), 0),
1565 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001566 Info, Deduced,
1567 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001568 }
1569
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001570 // (clang extension)
1571 //
Mike Stump11289f42009-09-09 15:08:12 +00001572 // type(^)(T)
1573 // T(^)()
1574 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001575 case Type::BlockPointer: {
1576 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1577 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001578
Anders Carlssona767eee2009-06-12 16:23:10 +00001579 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001580 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001581
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001582 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1583 BlockPtrParam->getPointeeType(),
1584 BlockPtrArg->getPointeeType(),
1585 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001586 }
1587
Douglas Gregor39c02722011-06-15 16:02:29 +00001588 // (clang extension)
1589 //
1590 // T __attribute__(((ext_vector_type(<integral constant>))))
1591 case Type::ExtVector: {
1592 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1593 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1594 // Make sure that the vectors have the same number of elements.
1595 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1596 return Sema::TDK_NonDeducedMismatch;
1597
1598 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001599 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1600 VectorParam->getElementType(),
1601 VectorArg->getElementType(),
1602 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001603 }
1604
1605 if (const DependentSizedExtVectorType *VectorArg
1606 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1607 // We can't check the number of elements, since the argument has a
1608 // dependent number of elements. This can only occur during partial
1609 // ordering.
1610
1611 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001612 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1613 VectorParam->getElementType(),
1614 VectorArg->getElementType(),
1615 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001616 }
1617
1618 return Sema::TDK_NonDeducedMismatch;
1619 }
1620
1621 // (clang extension)
1622 //
1623 // T __attribute__(((ext_vector_type(N))))
1624 case Type::DependentSizedExtVector: {
1625 const DependentSizedExtVectorType *VectorParam
1626 = cast<DependentSizedExtVectorType>(Param);
1627
1628 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1629 // Perform deduction on the element types.
1630 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001631 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1632 VectorParam->getElementType(),
1633 VectorArg->getElementType(),
1634 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001635 return Result;
1636
1637 // Perform deduction on the vector size, if we can.
1638 NonTypeTemplateParmDecl *NTTP
1639 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1640 if (!NTTP)
1641 return Sema::TDK_Success;
1642
1643 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1644 ArgSize = VectorArg->getNumElements();
1645 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1646 false, Info, Deduced);
1647 }
1648
1649 if (const DependentSizedExtVectorType *VectorArg
1650 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1651 // Perform deduction on the element types.
1652 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001653 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1654 VectorParam->getElementType(),
1655 VectorArg->getElementType(),
1656 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001657 return Result;
1658
1659 // Perform deduction on the vector size, if we can.
1660 NonTypeTemplateParmDecl *NTTP
1661 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1662 if (!NTTP)
1663 return Sema::TDK_Success;
1664
1665 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1666 Info, Deduced);
1667 }
1668
1669 return Sema::TDK_NonDeducedMismatch;
1670 }
1671
Douglas Gregor637d9982009-06-10 23:47:09 +00001672 case Type::TypeOfExpr:
1673 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001674 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001675 case Type::UnresolvedUsing:
1676 case Type::Decltype:
1677 case Type::UnaryTransform:
1678 case Type::Auto:
1679 case Type::DependentTemplateSpecialization:
1680 case Type::PackExpansion:
Douglas Gregor637d9982009-06-10 23:47:09 +00001681 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001682 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001683 }
1684
David Blaikiee4d798f2012-01-20 21:50:17 +00001685 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001686}
1687
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001688static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001689DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001690 TemplateParameterList *TemplateParams,
1691 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001692 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001693 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001694 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001695 // If the template argument is a pack expansion, perform template argument
1696 // deduction against the pattern of that expansion. This only occurs during
1697 // partial ordering.
1698 if (Arg.isPackExpansion())
1699 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001700
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001701 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001702 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001703 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001704
1705 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001706 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001707 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1708 Param.getAsType(),
1709 Arg.getAsType(),
1710 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001711 Info.FirstArg = Param;
1712 Info.SecondArg = Arg;
1713 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001714
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001715 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001716 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001718 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001719 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001720 Info.FirstArg = Param;
1721 Info.SecondArg = Arg;
1722 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001723
1724 case TemplateArgument::TemplateExpansion:
1725 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001726
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001727 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001728 if (Arg.getKind() == TemplateArgument::Declaration &&
Eli Friedmanb826a002012-09-26 02:36:12 +00001729 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()) &&
1730 Param.isDeclForReferenceParam() == Arg.isDeclForReferenceParam())
1731 return Sema::TDK_Success;
1732
1733 Info.FirstArg = Param;
1734 Info.SecondArg = Arg;
1735 return Sema::TDK_NonDeducedMismatch;
1736
1737 case TemplateArgument::NullPtr:
1738 if (Arg.getKind() == TemplateArgument::NullPtr &&
1739 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001740 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001741
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001742 Info.FirstArg = Param;
1743 Info.SecondArg = Arg;
1744 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001745
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001746 case TemplateArgument::Integral:
1747 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001748 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001749 return Sema::TDK_Success;
1750
1751 Info.FirstArg = Param;
1752 Info.SecondArg = Arg;
1753 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001754 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001755
1756 if (Arg.getKind() == TemplateArgument::Expression) {
1757 Info.FirstArg = Param;
1758 Info.SecondArg = Arg;
1759 return Sema::TDK_NonDeducedMismatch;
1760 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001761
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001762 Info.FirstArg = Param;
1763 Info.SecondArg = Arg;
1764 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001765
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001766 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001767 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001768 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1769 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001770 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001771 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001772 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001773 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001774 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001775 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001776 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001777 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001778 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001779 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001780 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001781
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001782 Info.FirstArg = Param;
1783 Info.SecondArg = Arg;
1784 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001785 }
Mike Stump11289f42009-09-09 15:08:12 +00001786
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001787 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001788 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001789 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001790 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001791 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001792 }
Mike Stump11289f42009-09-09 15:08:12 +00001793
David Blaikiee4d798f2012-01-20 21:50:17 +00001794 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001795}
1796
Douglas Gregor7baabef2010-12-22 18:17:10 +00001797/// \brief Determine whether there is a template argument to be used for
1798/// deduction.
1799///
1800/// This routine "expands" argument packs in-place, overriding its input
1801/// parameters so that \c Args[ArgIdx] will be the available template argument.
1802///
1803/// \returns true if there is another template argument (which will be at
1804/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001805static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001806 unsigned &ArgIdx,
1807 unsigned &NumArgs) {
1808 if (ArgIdx == NumArgs)
1809 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810
Douglas Gregor7baabef2010-12-22 18:17:10 +00001811 const TemplateArgument &Arg = Args[ArgIdx];
1812 if (Arg.getKind() != TemplateArgument::Pack)
1813 return true;
1814
1815 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1816 Args = Arg.pack_begin();
1817 NumArgs = Arg.pack_size();
1818 ArgIdx = 0;
1819 return ArgIdx < NumArgs;
1820}
1821
Douglas Gregord0ad2942010-12-23 01:24:45 +00001822/// \brief Determine whether the given set of template arguments has a pack
1823/// expansion that is not the last template argument.
1824static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1825 unsigned NumArgs) {
1826 unsigned ArgIdx = 0;
1827 while (ArgIdx < NumArgs) {
1828 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001829
Douglas Gregord0ad2942010-12-23 01:24:45 +00001830 // Unwrap argument packs.
1831 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1832 Args = Arg.pack_begin();
1833 NumArgs = Arg.pack_size();
1834 ArgIdx = 0;
1835 continue;
1836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001837
Douglas Gregord0ad2942010-12-23 01:24:45 +00001838 ++ArgIdx;
1839 if (ArgIdx == NumArgs)
1840 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001841
Douglas Gregord0ad2942010-12-23 01:24:45 +00001842 if (Arg.isPackExpansion())
1843 return true;
1844 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001845
Douglas Gregord0ad2942010-12-23 01:24:45 +00001846 return false;
1847}
1848
Douglas Gregor7baabef2010-12-22 18:17:10 +00001849static Sema::TemplateDeductionResult
1850DeduceTemplateArguments(Sema &S,
1851 TemplateParameterList *TemplateParams,
1852 const TemplateArgument *Params, unsigned NumParams,
1853 const TemplateArgument *Args, unsigned NumArgs,
1854 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +00001855 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001856 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001857 // If the template argument list of P contains a pack expansion that is not
1858 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001859 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001860 if (hasPackExpansionBeforeEnd(Params, NumParams))
1861 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001863 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001864 // If P has a form that contains <T> or <i>, then each argument Pi of the
1865 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001866 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001867 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001869 ++ParamIdx) {
1870 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001871 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001872
Douglas Gregor7baabef2010-12-22 18:17:10 +00001873 // Check whether we have enough arguments.
1874 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Richard Smith16b65392012-12-06 06:44:44 +00001875 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001876
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001877 if (Args[ArgIdx].isPackExpansion()) {
1878 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1879 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001880 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001881 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001882
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001883 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001884 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001885 = DeduceTemplateArguments(S, TemplateParams,
1886 Params[ParamIdx], Args[ArgIdx],
1887 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888 return Result;
1889
Douglas Gregor7baabef2010-12-22 18:17:10 +00001890 // Move to the next argument.
1891 ++ArgIdx;
1892 continue;
1893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001894
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001895 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001897 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001898 // If Pi is a pack expansion, then the pattern of Pi is compared with
1899 // each remaining argument in the template argument list of A. Each
1900 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001901 // template parameter packs expanded by Pi.
1902 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001904 // FIXME: If there are no remaining arguments, we can bail out early
1905 // and set any deduced parameter packs to an empty argument pack.
1906 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907
Richard Smith0a80d572014-05-29 01:12:14 +00001908 // Prepare to deduce the packs within the pattern.
1909 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001910
1911 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001912 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001913 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001914 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001915 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001916 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001918 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001920 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1921 Info, Deduced))
1922 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001923
Richard Smith0a80d572014-05-29 01:12:14 +00001924 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001925 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001927 // Build argument packs for each of the parameter packs expanded by this
1928 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001929 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001930 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Douglas Gregor7baabef2010-12-22 18:17:10 +00001933 return Sema::TDK_Success;
1934}
1935
Mike Stump11289f42009-09-09 15:08:12 +00001936static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001937DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001938 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001939 const TemplateArgumentList &ParamList,
1940 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001941 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001942 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001944 ParamList.data(), ParamList.size(),
1945 ArgList.data(), ArgList.size(),
1946 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001947}
1948
Douglas Gregor705c9002009-06-26 20:57:09 +00001949/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001950static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001951 const TemplateArgument &X,
1952 const TemplateArgument &Y) {
1953 if (X.getKind() != Y.getKind())
1954 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001955
Douglas Gregor705c9002009-06-26 20:57:09 +00001956 switch (X.getKind()) {
1957 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001958 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001959
Douglas Gregor705c9002009-06-26 20:57:09 +00001960 case TemplateArgument::Type:
1961 return Context.getCanonicalType(X.getAsType()) ==
1962 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001963
Douglas Gregor705c9002009-06-26 20:57:09 +00001964 case TemplateArgument::Declaration:
Eli Friedmanb826a002012-09-26 02:36:12 +00001965 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl()) &&
1966 X.isDeclForReferenceParam() == Y.isDeclForReferenceParam();
1967
1968 case TemplateArgument::NullPtr:
1969 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001970
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001971 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001972 case TemplateArgument::TemplateExpansion:
1973 return Context.getCanonicalTemplateName(
1974 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1975 Context.getCanonicalTemplateName(
1976 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977
Douglas Gregor705c9002009-06-26 20:57:09 +00001978 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001979 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001980
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001981 case TemplateArgument::Expression: {
1982 llvm::FoldingSetNodeID XID, YID;
1983 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001984 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001985 return XID == YID;
1986 }
Mike Stump11289f42009-09-09 15:08:12 +00001987
Douglas Gregor705c9002009-06-26 20:57:09 +00001988 case TemplateArgument::Pack:
1989 if (X.pack_size() != Y.pack_size())
1990 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001991
1992 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1993 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001994 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001995 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001996 if (!isSameTemplateArg(Context, *XP, *YP))
1997 return false;
1998
1999 return true;
2000 }
2001
David Blaikiee4d798f2012-01-20 21:50:17 +00002002 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002003}
2004
Douglas Gregorca4686d2011-01-04 23:35:54 +00002005/// \brief Allocate a TemplateArgumentLoc where all locations have
2006/// been initialized to the given location.
2007///
2008/// \param S The semantic analysis object.
2009///
James Dennett634962f2012-06-14 21:40:34 +00002010/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002011/// location information for.
2012///
2013/// \param NTTPType For a declaration template argument, the type of
2014/// the non-type template parameter that corresponds to this template
2015/// argument.
2016///
2017/// \param Loc The source location to use for the resulting template
2018/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002019static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00002020getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002021 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002022 QualType NTTPType,
2023 SourceLocation Loc) {
2024 switch (Arg.getKind()) {
2025 case TemplateArgument::Null:
2026 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002027
Douglas Gregorca4686d2011-01-04 23:35:54 +00002028 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002029 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002030 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031
Douglas Gregorca4686d2011-01-04 23:35:54 +00002032 case TemplateArgument::Declaration: {
2033 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00002034 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002035 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002036 return TemplateArgumentLoc(TemplateArgument(E), E);
2037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Eli Friedmanb826a002012-09-26 02:36:12 +00002039 case TemplateArgument::NullPtr: {
2040 Expr *E
2041 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002042 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002043 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2044 E);
2045 }
2046
Douglas Gregorca4686d2011-01-04 23:35:54 +00002047 case TemplateArgument::Integral: {
2048 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002049 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002050 return TemplateArgumentLoc(TemplateArgument(E), E);
2051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052
Douglas Gregor9d802122011-03-02 17:09:35 +00002053 case TemplateArgument::Template:
2054 case TemplateArgument::TemplateExpansion: {
2055 NestedNameSpecifierLocBuilder Builder;
2056 TemplateName Template = Arg.getAsTemplate();
2057 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2058 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
2059 else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2060 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2061
2062 if (Arg.getKind() == TemplateArgument::Template)
2063 return TemplateArgumentLoc(Arg,
2064 Builder.getWithLocInContext(S.Context),
2065 Loc);
2066
2067
2068 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2069 Loc, Loc);
2070 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002071
Douglas Gregorca4686d2011-01-04 23:35:54 +00002072 case TemplateArgument::Expression:
2073 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074
Douglas Gregorca4686d2011-01-04 23:35:54 +00002075 case TemplateArgument::Pack:
2076 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002078
David Blaikiee4d798f2012-01-20 21:50:17 +00002079 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002080}
2081
2082
2083/// \brief Convert the given deduced template argument and add it to the set of
2084/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002085static bool
2086ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2087 DeducedTemplateArgument Arg,
2088 NamedDecl *Template,
2089 QualType NTTPType,
2090 unsigned ArgumentPackIndex,
2091 TemplateDeductionInfo &Info,
2092 bool InFunctionTemplate,
2093 SmallVectorImpl<TemplateArgument> &Output) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002094 if (Arg.getKind() == TemplateArgument::Pack) {
2095 // This is a template argument pack, so check each of its arguments against
2096 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002097 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098 for (TemplateArgument::pack_iterator PA = Arg.pack_begin(),
Douglas Gregorf491ee22011-01-05 21:00:53 +00002099 PAEnd = Arg.pack_end();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002100 PA != PAEnd; ++PA) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002101 // When converting the deduced template argument, append it to the
2102 // general output list. We need to do this so that the template argument
2103 // checking logic has all of the prior template arguments available.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002104 DeducedTemplateArgument InnerArg(*PA);
2105 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002106 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002107 NTTPType, PackedArgsBuilder.size(),
2108 Info, InFunctionTemplate, Output))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002109 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002110
Douglas Gregor51bc5712011-01-05 20:52:18 +00002111 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002112 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002114
Douglas Gregorca4686d2011-01-04 23:35:54 +00002115 // Create the resulting argument pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002116 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
Douglas Gregor74c6d192011-01-11 23:09:57 +00002117 PackedArgsBuilder.data(),
2118 PackedArgsBuilder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002119 return false;
2120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Douglas Gregorca4686d2011-01-04 23:35:54 +00002122 // Convert the deduced template argument into a template
2123 // argument that we can check, almost as if the user had written
2124 // the template argument explicitly.
2125 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2126 Info.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127
Douglas Gregorca4686d2011-01-04 23:35:54 +00002128 // Check the template argument, converting it as necessary.
2129 return S.CheckTemplateArgument(Param, ArgLoc,
2130 Template,
2131 Template->getLocation(),
2132 Template->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002133 ArgumentPackIndex,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002134 Output,
2135 InFunctionTemplate
2136 ? (Arg.wasDeducedFromArrayBound()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137 ? Sema::CTAK_DeducedFromArrayBound
Douglas Gregorca4686d2011-01-04 23:35:54 +00002138 : Sema::CTAK_Deduced)
2139 : Sema::CTAK_Specified);
2140}
2141
Douglas Gregor684268d2010-04-29 06:21:43 +00002142/// Complete template argument deduction for a class template partial
2143/// specialization.
2144static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002145FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002146 ClassTemplatePartialSpecializationDecl *Partial,
2147 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002148 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002149 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002150 // Unevaluated SFINAE context.
2151 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002152 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002153
Douglas Gregor684268d2010-04-29 06:21:43 +00002154 Sema::ContextRAII SavedContext(S, Partial);
2155
2156 // C++ [temp.deduct.type]p2:
2157 // [...] or if any template argument remains neither deduced nor
2158 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002159 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002160 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2161 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002162 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002163 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002164 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002165 return Sema::TDK_Incomplete;
2166 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002167
Douglas Gregorca4686d2011-01-04 23:35:54 +00002168 // We have deduced this argument, so it still needs to be
2169 // checked and converted.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002170
Douglas Gregorca4686d2011-01-04 23:35:54 +00002171 // First, for a non-type template parameter type that is
2172 // initialized by a declaration, we need the type of the
2173 // corresponding non-type template parameter.
2174 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor51bc5712011-01-05 20:52:18 +00002176 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002177 NTTPType = NTTP->getType();
Douglas Gregor51bc5712011-01-05 20:52:18 +00002178 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002179 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor51bc5712011-01-05 20:52:18 +00002180 Builder.data(), Builder.size());
2181 NTTPType = S.SubstType(NTTPType,
2182 MultiLevelTemplateArgumentList(TemplateArgs),
2183 NTTP->getLocation(),
2184 NTTP->getDeclName());
2185 if (NTTPType.isNull()) {
2186 Info.Param = makeTemplateParameter(Param);
2187 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2189 Builder.data(),
Douglas Gregor51bc5712011-01-05 20:52:18 +00002190 Builder.size()));
2191 return Sema::TDK_SubstitutionFailure;
2192 }
2193 }
2194 }
2195
Douglas Gregorca4686d2011-01-04 23:35:54 +00002196 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002197 Partial, NTTPType, 0, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002198 Builder)) {
2199 Info.Param = makeTemplateParameter(Param);
2200 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002201 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2202 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002203 return Sema::TDK_SubstitutionFailure;
2204 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002206
Douglas Gregor684268d2010-04-29 06:21:43 +00002207 // Form the template argument list from the deduced template arguments.
2208 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002209 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002210 Builder.size());
2211
Douglas Gregor684268d2010-04-29 06:21:43 +00002212 Info.reset(DeducedArgumentList);
2213
2214 // Substitute the deduced template arguments into the template
2215 // arguments of the class template partial specialization, and
2216 // verify that the instantiated template arguments are both valid
2217 // and are equivalent to the template arguments originally provided
2218 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002219 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002220 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002221 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002222 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002223 const TemplateArgumentLoc *PartialTemplateArgs
2224 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002225
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002226 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2227 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002228
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002229 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002230 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2231 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2232 if (ParamIdx >= Partial->getTemplateParameters()->size())
2233 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2234
2235 Decl *Param
2236 = const_cast<NamedDecl *>(
2237 Partial->getTemplateParameters()->getParam(ParamIdx));
2238 Info.Param = makeTemplateParameter(Param);
2239 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2240 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002241 }
2242
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002243 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002244 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002245 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002246 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002247
Douglas Gregorca4686d2011-01-04 23:35:54 +00002248 TemplateParameterList *TemplateParams
2249 = ClassTemplate->getTemplateParameters();
2250 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002251 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002252 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002253 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002254 Info.FirstArg = TemplateArgs[I];
2255 Info.SecondArg = InstArg;
2256 return Sema::TDK_NonDeducedMismatch;
2257 }
2258 }
2259
2260 if (Trap.hasErrorOccurred())
2261 return Sema::TDK_SubstitutionFailure;
2262
2263 return Sema::TDK_Success;
2264}
2265
Douglas Gregor170bc422009-06-12 22:31:52 +00002266/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002267/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002268/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002269Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002270Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002271 const TemplateArgumentList &TemplateArgs,
2272 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002273 if (Partial->isInvalidDecl())
2274 return TDK_Invalid;
2275
Douglas Gregor170bc422009-06-12 22:31:52 +00002276 // C++ [temp.class.spec.match]p2:
2277 // A partial specialization matches a given actual template
2278 // argument list if the template arguments of the partial
2279 // specialization can be deduced from the actual template argument
2280 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002281
2282 // Unevaluated SFINAE context.
2283 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002284 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002285
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002286 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002287 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002288 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002289 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002290 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002291 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002292 TemplateArgs, Info, Deduced))
2293 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002294
Richard Smith80934652012-07-16 01:09:10 +00002295 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002296 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2297 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002298 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002299 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002300
Douglas Gregore1416332009-06-14 08:02:22 +00002301 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002302 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002303
2304 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002305 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002306}
Douglas Gregor91772d12009-06-13 00:26:55 +00002307
Larisse Voufo39a1e502013-08-06 01:03:05 +00002308/// Complete template argument deduction for a variable template partial
2309/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002310/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2311/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2312/// VarTemplate(Partial)SpecializationDecl with a new data
2313/// structure Template(Partial)SpecializationDecl, and
2314/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002315static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2316 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2317 const TemplateArgumentList &TemplateArgs,
2318 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2319 TemplateDeductionInfo &Info) {
2320 // Unevaluated SFINAE context.
2321 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2322 Sema::SFINAETrap Trap(S);
2323
2324 // C++ [temp.deduct.type]p2:
2325 // [...] or if any template argument remains neither deduced nor
2326 // explicitly specified, template argument deduction fails.
2327 SmallVector<TemplateArgument, 4> Builder;
2328 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2329 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2330 NamedDecl *Param = PartialParams->getParam(I);
2331 if (Deduced[I].isNull()) {
2332 Info.Param = makeTemplateParameter(Param);
2333 return Sema::TDK_Incomplete;
2334 }
2335
2336 // We have deduced this argument, so it still needs to be
2337 // checked and converted.
2338
2339 // First, for a non-type template parameter type that is
2340 // initialized by a declaration, we need the type of the
2341 // corresponding non-type template parameter.
2342 QualType NTTPType;
2343 if (NonTypeTemplateParmDecl *NTTP =
2344 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2345 NTTPType = NTTP->getType();
2346 if (NTTPType->isDependentType()) {
2347 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2348 Builder.data(), Builder.size());
2349 NTTPType =
2350 S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs),
2351 NTTP->getLocation(), NTTP->getDeclName());
2352 if (NTTPType.isNull()) {
2353 Info.Param = makeTemplateParameter(Param);
2354 // FIXME: These template arguments are temporary. Free them!
2355 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2356 Builder.size()));
2357 return Sema::TDK_SubstitutionFailure;
2358 }
2359 }
2360 }
2361
2362 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType,
2363 0, Info, false, Builder)) {
2364 Info.Param = makeTemplateParameter(Param);
2365 // FIXME: These template arguments are temporary. Free them!
2366 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2367 Builder.size()));
2368 return Sema::TDK_SubstitutionFailure;
2369 }
2370 }
2371
2372 // Form the template argument list from the deduced template arguments.
2373 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2374 S.Context, Builder.data(), Builder.size());
2375
2376 Info.reset(DeducedArgumentList);
2377
2378 // Substitute the deduced template arguments into the template
2379 // arguments of the class template partial specialization, and
2380 // verify that the instantiated template arguments are both valid
2381 // and are equivalent to the template arguments originally provided
2382 // to the class template.
2383 LocalInstantiationScope InstScope(S);
2384 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002385 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2386 = Partial->getTemplateArgsAsWritten();
2387 const TemplateArgumentLoc *PartialTemplateArgs
2388 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002389
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002390 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2391 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002392
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002393 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002394 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2395 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2396 if (ParamIdx >= Partial->getTemplateParameters()->size())
2397 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2398
2399 Decl *Param = const_cast<NamedDecl *>(
2400 Partial->getTemplateParameters()->getParam(ParamIdx));
2401 Info.Param = makeTemplateParameter(Param);
2402 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2403 return Sema::TDK_SubstitutionFailure;
2404 }
2405 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2406 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2407 false, ConvertedInstArgs))
2408 return Sema::TDK_SubstitutionFailure;
2409
2410 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2411 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2412 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2413 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2414 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2415 Info.FirstArg = TemplateArgs[I];
2416 Info.SecondArg = InstArg;
2417 return Sema::TDK_NonDeducedMismatch;
2418 }
2419 }
2420
2421 if (Trap.hasErrorOccurred())
2422 return Sema::TDK_SubstitutionFailure;
2423
2424 return Sema::TDK_Success;
2425}
2426
2427/// \brief Perform template argument deduction to determine whether
2428/// the given template arguments match the given variable template
2429/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002430/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2431/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2432/// VarTemplate(Partial)SpecializationDecl with a new data
2433/// structure Template(Partial)SpecializationDecl, and
2434/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002435Sema::TemplateDeductionResult
2436Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2437 const TemplateArgumentList &TemplateArgs,
2438 TemplateDeductionInfo &Info) {
2439 if (Partial->isInvalidDecl())
2440 return TDK_Invalid;
2441
2442 // C++ [temp.class.spec.match]p2:
2443 // A partial specialization matches a given actual template
2444 // argument list if the template arguments of the partial
2445 // specialization can be deduced from the actual template argument
2446 // list (14.8.2).
2447
2448 // Unevaluated SFINAE context.
2449 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2450 SFINAETrap Trap(*this);
2451
2452 SmallVector<DeducedTemplateArgument, 4> Deduced;
2453 Deduced.resize(Partial->getTemplateParameters()->size());
2454 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2455 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2456 TemplateArgs, Info, Deduced))
2457 return Result;
2458
2459 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002460 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2461 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002462 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002463 return TDK_InstantiationDepth;
2464
2465 if (Trap.hasErrorOccurred())
2466 return Sema::TDK_SubstitutionFailure;
2467
2468 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2469 Deduced, Info);
2470}
2471
Douglas Gregorfc516c92009-06-26 23:27:24 +00002472/// \brief Determine whether the given type T is a simple-template-id type.
2473static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002474 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002475 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002476 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002477
Douglas Gregorfc516c92009-06-26 23:27:24 +00002478 return false;
2479}
Douglas Gregor9b146582009-07-08 20:55:45 +00002480
2481/// \brief Substitute the explicitly-provided template arguments into the
2482/// given function template according to C++ [temp.arg.explicit].
2483///
2484/// \param FunctionTemplate the function template into which the explicit
2485/// template arguments will be substituted.
2486///
James Dennett634962f2012-06-14 21:40:34 +00002487/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002488/// arguments.
2489///
Mike Stump11289f42009-09-09 15:08:12 +00002490/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002491/// with the converted and checked explicit template arguments.
2492///
Mike Stump11289f42009-09-09 15:08:12 +00002493/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002494/// parameters.
2495///
2496/// \param FunctionType if non-NULL, the result type of the function template
2497/// will also be instantiated and the pointed-to value will be updated with
2498/// the instantiated function type.
2499///
2500/// \param Info if substitution fails for any reason, this object will be
2501/// populated with more information about the failure.
2502///
2503/// \returns TDK_Success if substitution was successful, or some failure
2504/// condition.
2505Sema::TemplateDeductionResult
2506Sema::SubstituteExplicitTemplateArguments(
2507 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002508 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002509 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2510 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002511 QualType *FunctionType,
2512 TemplateDeductionInfo &Info) {
2513 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2514 TemplateParameterList *TemplateParams
2515 = FunctionTemplate->getTemplateParameters();
2516
John McCall6b51f282009-11-23 01:53:49 +00002517 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002518 // No arguments to substitute; just copy over the parameter types and
2519 // fill in the function type.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002520 for (auto P : Function->params())
2521 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002522
Douglas Gregor9b146582009-07-08 20:55:45 +00002523 if (FunctionType)
2524 *FunctionType = Function->getType();
2525 return TDK_Success;
2526 }
Mike Stump11289f42009-09-09 15:08:12 +00002527
Eli Friedman77dcc722012-02-08 03:07:05 +00002528 // Unevaluated SFINAE context.
2529 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002530 SFINAETrap Trap(*this);
2531
Douglas Gregor9b146582009-07-08 20:55:45 +00002532 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002533 // Template arguments that are present shall be specified in the
2534 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002535 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002536 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002537 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002538
2539 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002540 // explicitly-specified template arguments against this function template,
2541 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002542 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002543 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2544 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002545 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2546 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002547 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002548 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002549
Douglas Gregor9b146582009-07-08 20:55:45 +00002550 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002551 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002552 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002553 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002554 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002555 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002556 if (Index >= TemplateParams->size())
2557 Index = TemplateParams->size() - 1;
2558 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002559 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002560 }
Mike Stump11289f42009-09-09 15:08:12 +00002561
Douglas Gregor9b146582009-07-08 20:55:45 +00002562 // Form the template argument list from the explicitly-specified
2563 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002564 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002565 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002566 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002567
John McCall036855a2010-10-12 19:40:14 +00002568 // Template argument deduction and the final substitution should be
2569 // done in the context of the templated declaration. Explicit
2570 // argument substitution, on the other hand, needs to happen in the
2571 // calling context.
2572 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2573
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002574 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002575 // note that the template argument pack is partially substituted and record
2576 // the explicit template arguments. They'll be used as part of deduction
2577 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002578 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2579 const TemplateArgument &Arg = Builder[I];
2580 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002581 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002582 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002583 Arg.pack_begin(),
2584 Arg.pack_size());
2585 break;
2586 }
2587 }
2588
Richard Smith5e580292012-02-10 09:58:53 +00002589 const FunctionProtoType *Proto
2590 = Function->getType()->getAs<FunctionProtoType>();
2591 assert(Proto && "Function template does not have a prototype?");
2592
Douglas Gregor9b146582009-07-08 20:55:45 +00002593 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002594 // explicitly-specified template arguments. If the function has a trailing
2595 // return type, substitute it after the arguments to ensure we substitute
2596 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002597 if (Proto->hasTrailingReturn()) {
2598 if (SubstParmTypes(Function->getLocation(),
2599 Function->param_begin(), Function->getNumParams(),
2600 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2601 ParamTypes))
2602 return TDK_SubstitutionFailure;
2603 }
2604
Richard Smith5e580292012-02-10 09:58:53 +00002605 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002606 QualType ResultType;
2607 {
2608 // C++11 [expr.prim.general]p3:
2609 // If a declaration declares a member function or member function
2610 // template of a class X, the expression this is a prvalue of type
2611 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2612 // and the end of the function-definition, member-declarator, or
2613 // declarator.
2614 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002615 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002616 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2617 ThisContext = Method->getParent();
2618 ThisTypeQuals = Method->getTypeQualifiers();
2619 }
2620
2621 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002622 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002623
2624 ResultType =
2625 SubstType(Proto->getReturnType(),
2626 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2627 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002628 if (ResultType.isNull() || Trap.hasErrorOccurred())
2629 return TDK_SubstitutionFailure;
2630 }
2631
Richard Smith5e580292012-02-10 09:58:53 +00002632 // Instantiate the types of each of the function parameters given the
2633 // explicitly-specified template arguments if we didn't do so earlier.
2634 if (!Proto->hasTrailingReturn() &&
2635 SubstParmTypes(Function->getLocation(),
2636 Function->param_begin(), Function->getNumParams(),
2637 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2638 ParamTypes))
2639 return TDK_SubstitutionFailure;
2640
Douglas Gregor9b146582009-07-08 20:55:45 +00002641 if (FunctionType) {
Jordan Rose5c382722013-03-08 21:51:21 +00002642 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002643 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002644 Function->getDeclName(),
Jordan Rosea0a86be2013-03-08 22:25:36 +00002645 Proto->getExtProtoInfo());
Douglas Gregor9b146582009-07-08 20:55:45 +00002646 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2647 return TDK_SubstitutionFailure;
2648 }
Mike Stump11289f42009-09-09 15:08:12 +00002649
Douglas Gregor9b146582009-07-08 20:55:45 +00002650 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002651 // Trailing template arguments that can be deduced (14.8.2) may be
2652 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002653 // template arguments can be deduced, they may all be omitted; in this
2654 // case, the empty template argument list <> itself may also be omitted.
2655 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002656 // Take all of the explicitly-specified arguments and put them into
2657 // the set of deduced template arguments. Explicitly-specified
2658 // parameter packs, however, will be set to NULL since the deduction
2659 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002660 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002661 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2662 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2663 if (Arg.getKind() == TemplateArgument::Pack)
2664 Deduced.push_back(DeducedTemplateArgument());
2665 else
2666 Deduced.push_back(Arg);
2667 }
Mike Stump11289f42009-09-09 15:08:12 +00002668
Douglas Gregor9b146582009-07-08 20:55:45 +00002669 return TDK_Success;
2670}
2671
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002672/// \brief Check whether the deduced argument type for a call to a function
2673/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2674static bool
2675CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2676 QualType DeducedA) {
2677 ASTContext &Context = S.Context;
2678
2679 QualType A = OriginalArg.OriginalArgType;
2680 QualType OriginalParamType = OriginalArg.OriginalParamType;
2681
2682 // Check for type equality (top-level cv-qualifiers are ignored).
2683 if (Context.hasSameUnqualifiedType(A, DeducedA))
2684 return false;
2685
2686 // Strip off references on the argument types; they aren't needed for
2687 // the following checks.
2688 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2689 DeducedA = DeducedARef->getPointeeType();
2690 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2691 A = ARef->getPointeeType();
2692
2693 // C++ [temp.deduct.call]p4:
2694 // [...] However, there are three cases that allow a difference:
2695 // - If the original P is a reference type, the deduced A (i.e., the
2696 // type referred to by the reference) can be more cv-qualified than
2697 // the transformed A.
2698 if (const ReferenceType *OriginalParamRef
2699 = OriginalParamType->getAs<ReferenceType>()) {
2700 // We don't want to keep the reference around any more.
2701 OriginalParamType = OriginalParamRef->getPointeeType();
2702
2703 Qualifiers AQuals = A.getQualifiers();
2704 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002705
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002706 // Under Objective-C++ ARC, the deduced type may have implicitly
2707 // been given strong or (when dealing with a const reference)
2708 // unsafe_unretained lifetime. If so, update the original
2709 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002710 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002711 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2712 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2713 (DeducedAQuals.hasConst() &&
2714 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2715 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002716 }
2717
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002718 if (AQuals == DeducedAQuals) {
2719 // Qualifiers match; there's nothing to do.
2720 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002721 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002722 } else {
2723 // Qualifiers are compatible, so have the argument type adopt the
2724 // deduced argument type's qualifiers as if we had performed the
2725 // qualification conversion.
2726 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2727 }
2728 }
2729
2730 // - The transformed A can be another pointer or pointer to member
2731 // type that can be converted to the deduced A via a qualification
2732 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002733 //
2734 // Also allow conversions which merely strip [[noreturn]] from function types
2735 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002736 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002737 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002738 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002739 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002740 (S.IsQualificationConversion(A, DeducedA, false,
2741 ObjCLifetimeConversion) ||
2742 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002743 return false;
2744
2745
2746 // - If P is a class and P has the form simple-template-id, then the
2747 // transformed A can be a derived class of the deduced A. [...]
2748 // [...] Likewise, if P is a pointer to a class of the form
2749 // simple-template-id, the transformed A can be a pointer to a
2750 // derived class pointed to by the deduced A.
2751 if (const PointerType *OriginalParamPtr
2752 = OriginalParamType->getAs<PointerType>()) {
2753 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2754 if (const PointerType *APtr = A->getAs<PointerType>()) {
2755 if (A->getPointeeType()->isRecordType()) {
2756 OriginalParamType = OriginalParamPtr->getPointeeType();
2757 DeducedA = DeducedAPtr->getPointeeType();
2758 A = APtr->getPointeeType();
2759 }
2760 }
2761 }
2762 }
2763
2764 if (Context.hasSameUnqualifiedType(A, DeducedA))
2765 return false;
2766
2767 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2768 S.IsDerivedFrom(A, DeducedA))
2769 return false;
2770
2771 return true;
2772}
2773
Mike Stump11289f42009-09-09 15:08:12 +00002774/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002775/// checking the deduced template arguments for completeness and forming
2776/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002777///
2778/// \param OriginalCallArgs If non-NULL, the original call arguments against
2779/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002780Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002781Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002782 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002783 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002784 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002785 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002786 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002787 TemplateParameterList *TemplateParams
2788 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002789
Eli Friedman77dcc722012-02-08 03:07:05 +00002790 // Unevaluated SFINAE context.
2791 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002792 SFINAETrap Trap(*this);
2793
Douglas Gregor9b146582009-07-08 20:55:45 +00002794 // Enter a new template instantiation context while we instantiate the
2795 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002796 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002797 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2798 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002799 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2800 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002801 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002802 return TDK_InstantiationDepth;
2803
John McCalle23b8712010-04-29 01:18:58 +00002804 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002805
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002806 // C++ [temp.deduct.type]p2:
2807 // [...] or if any template argument remains neither deduced nor
2808 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002809 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002810 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2811 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002812
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002813 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002814 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002815 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002817 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002818 Builder.push_back(Deduced[I]);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002819 continue;
2820 }
2821
2822 // We have deduced this argument, so it still needs to be
2823 // checked and converted.
2824
2825 // First, for a non-type template parameter type that is
2826 // initialized by a declaration, we need the type of the
2827 // corresponding non-type template parameter.
2828 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829 if (NonTypeTemplateParmDecl *NTTP
2830 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002831 NTTPType = NTTP->getType();
2832 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002833 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002834 Builder.data(), Builder.size());
2835 NTTPType = SubstType(NTTPType,
2836 MultiLevelTemplateArgumentList(TemplateArgs),
2837 NTTP->getLocation(),
2838 NTTP->getDeclName());
2839 if (NTTPType.isNull()) {
2840 Info.Param = makeTemplateParameter(Param);
2841 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002842 Info.reset(TemplateArgumentList::CreateCopy(Context,
2843 Builder.data(),
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002844 Builder.size()));
2845 return TDK_SubstitutionFailure;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002846 }
2847 }
2848 }
2849
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002850 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002851 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002852 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002853 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002854 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2856 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002857 return TDK_SubstitutionFailure;
2858 }
2859
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002860 continue;
2861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002862
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002863 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002864 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002865 // be deduced to an empty sequence of template arguments.
2866 // FIXME: Where did the word "trailing" come from?
2867 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002868 // We may have had explicitly-specified template arguments for this
2869 // template parameter pack. If so, our empty deduction extends the
2870 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2871 const TemplateArgument *ExplicitArgs;
2872 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002873 if (CurrentInstantiationScope &&
2874 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002875 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002876 == Param) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002877 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002878
Douglas Gregorcaddba92013-01-18 22:27:09 +00002879 // Forget the partially-substituted pack; it's substitution is now
2880 // complete.
2881 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2882 } else {
2883 Builder.push_back(TemplateArgument::getEmptyPack());
2884 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002885 continue;
2886 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002887
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002888 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002889 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002890 TemplateArgumentLoc DefArg
2891 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2892 FunctionTemplate->getLocation(),
2893 FunctionTemplate->getSourceRange().getEnd(),
2894 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002895 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002896
2897 // If there was no default argument, deduction is incomplete.
2898 if (DefArg.getArgument().isNull()) {
2899 Info.Param = makeTemplateParameter(
2900 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002901 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2902 Builder.size()));
2903 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002905
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002906 // Check whether we can actually use the default argument.
2907 if (CheckTemplateArgument(Param, DefArg,
2908 FunctionTemplate,
2909 FunctionTemplate->getLocation(),
2910 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002911 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002912 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002913 Info.Param = makeTemplateParameter(
2914 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002915 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002916 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002917 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002918 return TDK_SubstitutionFailure;
2919 }
2920
2921 // If we get here, we successfully used the default template argument.
2922 }
2923
2924 // Form the template argument list from the deduced template arguments.
2925 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002926 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002927 Info.reset(DeducedArgumentList);
2928
Mike Stump11289f42009-09-09 15:08:12 +00002929 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002930 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002931 DeclContext *Owner = FunctionTemplate->getDeclContext();
2932 if (FunctionTemplate->getFriendObjectKind())
2933 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002934 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002935 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002936 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002937 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002938 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002939
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002940 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002941 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942
Mike Stump11289f42009-09-09 15:08:12 +00002943 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002944 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002945 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2946 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002947 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002948
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002949 // There may have been an error that did not prevent us from constructing a
2950 // declaration. Mark the declaration invalid and return with a substitution
2951 // failure.
2952 if (Trap.hasErrorOccurred()) {
2953 Specialization->setInvalidDecl(true);
2954 return TDK_SubstitutionFailure;
2955 }
2956
Douglas Gregore65aacb2011-06-16 16:50:48 +00002957 if (OriginalCallArgs) {
2958 // C++ [temp.deduct.call]p4:
2959 // In general, the deduction process attempts to find template argument
2960 // values that will make the deduced A identical to A (after the type A
2961 // is transformed as described above). [...]
2962 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2963 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002964 unsigned ParamIdx = OriginalArg.ArgIdx;
2965
2966 if (ParamIdx >= Specialization->getNumParams())
2967 continue;
2968
2969 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002970 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2971 return Sema::TDK_SubstitutionFailure;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002972 }
2973 }
2974
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002975 // If we suppressed any diagnostics while performing template argument
2976 // deduction, and if we haven't already instantiated this declaration,
2977 // keep track of these diagnostics. They'll be emitted if this specialization
2978 // is actually used.
2979 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002980 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002981 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2982 if (Pos == SuppressedDiagnostics.end())
2983 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2984 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002985 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002986
Mike Stump11289f42009-09-09 15:08:12 +00002987 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002988}
2989
John McCall8d08b9b2010-08-27 09:08:28 +00002990/// Gets the type of a function for template-argument-deducton
2991/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002992static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002993 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002994 // We may need to deduce the return type of the function now.
Alp Toker314cc812014-01-25 16:55:45 +00002995 if (S.getLangOpts().CPlusPlus1y && Fn->getReturnType()->isUndeducedType() &&
2996 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002997 return QualType();
2998
John McCallc1f69982010-02-02 02:21:27 +00002999 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003000 if (Method->isInstance()) {
3001 // An instance method that's referenced in a form that doesn't
3002 // look like a member pointer is just invalid.
3003 if (!R.HasFormOfMemberPointer) return QualType();
3004
Richard Smith2a7d4812013-05-04 07:00:32 +00003005 return S.Context.getMemberPointerType(Fn->getType(),
3006 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003007 }
3008
3009 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003010 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003011}
3012
3013/// Apply the deduction rules for overload sets.
3014///
3015/// \return the null type if this argument should be treated as an
3016/// undeduced context
3017static QualType
3018ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003019 Expr *Arg, QualType ParamType,
3020 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021
John McCall8d08b9b2010-08-27 09:08:28 +00003022 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003023
John McCall8d08b9b2010-08-27 09:08:28 +00003024 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003025
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003026 // C++0x [temp.deduct.call]p4
3027 unsigned TDF = 0;
3028 if (ParamWasReference)
3029 TDF |= TDF_ParamWithReferenceType;
3030 if (R.IsAddressOfOperand)
3031 TDF |= TDF_IgnoreQualifiers;
3032
John McCallc1f69982010-02-02 02:21:27 +00003033 // C++0x [temp.deduct.call]p6:
3034 // When P is a function type, pointer to function type, or pointer
3035 // to member function type:
3036
3037 if (!ParamType->isFunctionType() &&
3038 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003039 !ParamType->isMemberFunctionPointerType()) {
3040 if (Ovl->hasExplicitTemplateArgs()) {
3041 // But we can still look for an explicit specialization.
3042 if (FunctionDecl *ExplicitSpec
3043 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003044 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003045 }
John McCallc1f69982010-02-02 02:21:27 +00003046
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003047 return QualType();
3048 }
3049
3050 // Gather the explicit template arguments, if any.
3051 TemplateArgumentListInfo ExplicitTemplateArgs;
3052 if (Ovl->hasExplicitTemplateArgs())
3053 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003054 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003055 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3056 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003057 NamedDecl *D = (*I)->getUnderlyingDecl();
3058
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003059 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3060 // - If the argument is an overload set containing one or more
3061 // function templates, the parameter is treated as a
3062 // non-deduced context.
3063 if (!Ovl->hasExplicitTemplateArgs())
3064 return QualType();
3065
3066 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003067 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003068 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003069 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3070 Specialization, Info))
3071 continue;
3072
3073 D = Specialization;
3074 }
John McCallc1f69982010-02-02 02:21:27 +00003075
3076 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003077 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003078 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003079
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003080 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003081 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003082 ArgType->isFunctionType())
3083 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003084
John McCallc1f69982010-02-02 02:21:27 +00003085 // - If the argument is an overload set (not containing function
3086 // templates), trial argument deduction is attempted using each
3087 // of the members of the set. If deduction succeeds for only one
3088 // of the overload set members, that member is used as the
3089 // argument value for the deduction. If deduction succeeds for
3090 // more than one member of the overload set the parameter is
3091 // treated as a non-deduced context.
3092
3093 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3094 // Type deduction is done independently for each P/A pair, and
3095 // the deduced template argument values are then combined.
3096 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003097 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003098 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003099 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003100 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003101 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3102 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003103 if (Result) continue;
3104 if (!Match.isNull()) return QualType();
3105 Match = ArgType;
3106 }
3107
3108 return Match;
3109}
3110
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003111/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003112/// described in C++ [temp.deduct.call].
3113///
3114/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003115/// argument deduction based on this P/A pair because the argument is an
3116/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003117static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3118 TemplateParameterList *TemplateParams,
3119 QualType &ParamType,
3120 QualType &ArgType,
3121 Expr *Arg,
3122 unsigned &TDF) {
3123 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003124 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003125 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003126 if (ParamType.hasQualifiers())
3127 ParamType = ParamType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003128 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3129 if (ParamRefType) {
Richard Smith30482bc2011-02-20 03:19:35 +00003130 QualType PointeeType = ParamRefType->getPointeeType();
3131
Richard Smith8c6eeb92013-01-31 04:03:12 +00003132 // If the argument has incomplete array type, try to complete its type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003133 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
Douglas Gregor57d4f972011-06-03 03:35:07 +00003134 ArgType = Arg->getType();
3135
Douglas Gregorcba72b12011-01-21 05:18:22 +00003136 // [C++0x] If P is an rvalue reference to a cv-unqualified
3137 // template parameter and the argument is an lvalue, the type
3138 // "lvalue reference to A" is used in place of A for type
3139 // deduction.
Richard Smith30482bc2011-02-20 03:19:35 +00003140 if (isa<RValueReferenceType>(ParamType)) {
3141 if (!PointeeType.getQualifiers() &&
3142 isa<TemplateTypeParmType>(PointeeType) &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00003143 Arg->Classify(S.Context).isLValue() &&
3144 Arg->getType() != S.Context.OverloadTy &&
3145 Arg->getType() != S.Context.BoundMemberTy)
Douglas Gregorcba72b12011-01-21 05:18:22 +00003146 ArgType = S.Context.getLValueReferenceType(ArgType);
3147 }
3148
Douglas Gregor7825bf32011-01-06 22:09:01 +00003149 // [...] If P is a reference type, the type referred to by P is used
3150 // for type deduction.
Richard Smith30482bc2011-02-20 03:19:35 +00003151 ParamType = PointeeType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153
Douglas Gregor7825bf32011-01-06 22:09:01 +00003154 // Overload sets usually make this parameter an undeduced
3155 // context, but there are sometimes special circumstances.
3156 if (ArgType == S.Context.OverloadTy) {
3157 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3158 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003159 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003160 if (ArgType.isNull())
3161 return true;
3162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163
Douglas Gregor7825bf32011-01-06 22:09:01 +00003164 if (ParamRefType) {
3165 // C++0x [temp.deduct.call]p3:
3166 // [...] If P is of the form T&&, where T is a template parameter, and
3167 // the argument is an lvalue, the type A& is used in place of A for
3168 // type deduction.
3169 if (ParamRefType->isRValueReferenceType() &&
3170 ParamRefType->getAs<TemplateTypeParmType>() &&
3171 Arg->isLValue())
3172 ArgType = S.Context.getLValueReferenceType(ArgType);
3173 } else {
3174 // C++ [temp.deduct.call]p2:
3175 // If P is not a reference type:
3176 // - If A is an array type, the pointer type produced by the
3177 // array-to-pointer standard conversion (4.2) is used in place of
3178 // A for type deduction; otherwise,
3179 if (ArgType->isArrayType())
3180 ArgType = S.Context.getArrayDecayedType(ArgType);
3181 // - If A is a function type, the pointer type produced by the
3182 // function-to-pointer standard conversion (4.3) is used in place
3183 // of A for type deduction; otherwise,
3184 else if (ArgType->isFunctionType())
3185 ArgType = S.Context.getPointerType(ArgType);
3186 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003187 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003188 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003189 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003190 }
3191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003192
Douglas Gregor7825bf32011-01-06 22:09:01 +00003193 // C++0x [temp.deduct.call]p4:
3194 // In general, the deduction process attempts to find template argument
3195 // values that will make the deduced A identical to A (after the type A
3196 // is transformed as described above). [...]
3197 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198
Douglas Gregor7825bf32011-01-06 22:09:01 +00003199 // - If the original P is a reference type, the deduced A (i.e., the
3200 // type referred to by the reference) can be more cv-qualified than
3201 // the transformed A.
3202 if (ParamRefType)
3203 TDF |= TDF_ParamWithReferenceType;
3204 // - The transformed A can be another pointer or pointer to member
3205 // type that can be converted to the deduced A via a qualification
3206 // conversion (4.4).
3207 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3208 ArgType->isObjCObjectPointerType())
3209 TDF |= TDF_IgnoreQualifiers;
3210 // - If P is a class and P has the form simple-template-id, then the
3211 // transformed A can be a derived class of the deduced A. Likewise,
3212 // if P is a pointer to a class of the form simple-template-id, the
3213 // transformed A can be a pointer to a derived class pointed to by
3214 // the deduced A.
3215 if (isSimpleTemplateIdType(ParamType) ||
3216 (isa<PointerType>(ParamType) &&
3217 isSimpleTemplateIdType(
3218 ParamType->getAs<PointerType>()->getPointeeType())))
3219 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003220
Douglas Gregor7825bf32011-01-06 22:09:01 +00003221 return false;
3222}
3223
Douglas Gregore65aacb2011-06-16 16:50:48 +00003224static bool hasDeducibleTemplateParameters(Sema &S,
3225 FunctionTemplateDecl *FunctionTemplate,
3226 QualType T);
3227
Sebastian Redl19181662012-03-15 21:40:51 +00003228/// \brief Perform template argument deduction by matching a parameter type
3229/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003230/// an initializer list that was originally matched against a parameter
3231/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003232static Sema::TemplateDeductionResult
3233DeduceTemplateArgumentByListElement(Sema &S,
3234 TemplateParameterList *TemplateParams,
3235 QualType ParamType, Expr *Arg,
3236 TemplateDeductionInfo &Info,
3237 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3238 unsigned TDF) {
3239 // Handle the case where an init list contains another init list as the
3240 // element.
3241 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3242 QualType X;
3243 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X))
3244 return Sema::TDK_Success; // Just ignore this expression.
3245
3246 // Recurse down into the init list.
3247 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3248 if (Sema::TemplateDeductionResult Result =
3249 DeduceTemplateArgumentByListElement(S, TemplateParams, X,
3250 ILE->getInit(i),
3251 Info, Deduced, TDF))
3252 return Result;
3253 }
3254 return Sema::TDK_Success;
3255 }
3256
3257 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003258 QualType ArgType = Arg->getType();
3259 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003260 ArgType, Arg, TDF)) {
3261 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003262 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003263 }
Sebastian Redl19181662012-03-15 21:40:51 +00003264 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003265 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003266}
3267
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003268/// \brief Perform template argument deduction from a function call
3269/// (C++ [temp.deduct.call]).
3270///
3271/// \param FunctionTemplate the function template for which we are performing
3272/// template argument deduction.
3273///
James Dennett18348b62012-06-22 08:52:37 +00003274/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003275/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003276///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003277/// \param Args the function call arguments
3278///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003279/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003280/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003281/// template argument deduction.
3282///
3283/// \param Info the argument will be updated to provide additional information
3284/// about template argument deduction.
3285///
3286/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003287Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3288 FunctionTemplateDecl *FunctionTemplate,
3289 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3290 FunctionDecl *&Specialization, TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003291 if (FunctionTemplate->isInvalidDecl())
3292 return TDK_Invalid;
3293
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003294 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor89026b52009-06-30 23:57:56 +00003295
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003296 // C++ [temp.deduct.call]p1:
3297 // Template argument deduction is done by comparing each function template
3298 // parameter type (call it P) with the type of the corresponding argument
3299 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003300 unsigned CheckArgs = Args.size();
3301 if (Args.size() < Function->getMinRequiredArguments())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003302 return TDK_TooFewArguments;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003303 else if (Args.size() > Function->getNumParams()) {
Mike Stump11289f42009-09-09 15:08:12 +00003304 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003305 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003306 if (Proto->isTemplateVariadic())
3307 /* Do nothing */;
3308 else if (Proto->isVariadic())
3309 CheckArgs = Function->getNumParams();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003310 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003311 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003312 }
Mike Stump11289f42009-09-09 15:08:12 +00003313
Douglas Gregor89026b52009-06-30 23:57:56 +00003314 // The types of the parameters from which we will perform template argument
3315 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003316 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003317 TemplateParameterList *TemplateParams
3318 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003319 SmallVector<DeducedTemplateArgument, 4> Deduced;
3320 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003321 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003322 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003323 TemplateDeductionResult Result =
3324 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003325 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003326 Deduced,
3327 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003328 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003329 Info);
3330 if (Result)
3331 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003332
3333 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003334 } else {
3335 // Just fill in the parameter types from the function declaration.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003336 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003337 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3338 }
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregor89026b52009-06-30 23:57:56 +00003340 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003341 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003342 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003343 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003344 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003345 ParamIdx != NumParams; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003346 QualType OrigParamType = ParamTypes[ParamIdx];
3347 QualType ParamType = OrigParamType;
3348
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003349 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003350 = dyn_cast<PackExpansionType>(ParamType);
3351 if (!ParamExpansion) {
3352 // Simple case: matching a function parameter to a function argument.
3353 if (ArgIdx >= CheckArgs)
3354 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355
Douglas Gregor7825bf32011-01-06 22:09:01 +00003356 Expr *Arg = Args[ArgIdx++];
3357 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003358
Douglas Gregor7825bf32011-01-06 22:09:01 +00003359 unsigned TDF = 0;
3360 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3361 ParamType, ArgType, Arg,
3362 TDF))
3363 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364
Douglas Gregor0c83c812011-10-09 22:06:46 +00003365 // If we have nothing to deduce, we're done.
3366 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3367 continue;
3368
Sebastian Redl43144e72012-01-17 22:49:58 +00003369 // If the argument is an initializer list ...
3370 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3371 // ... then the parameter is an undeduced context, unless the parameter
3372 // type is (reference to cv) std::initializer_list<P'>, in which case
3373 // deduction is done for each element of the initializer list, and the
3374 // result is the deduced type if it's the same for all elements.
3375 QualType X;
3376 // Removing references was already done.
3377 if (!isStdInitializerList(ParamType, &X))
3378 continue;
3379
3380 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3381 if (TemplateDeductionResult Result =
Sebastian Redl19181662012-03-15 21:40:51 +00003382 DeduceTemplateArgumentByListElement(*this, TemplateParams, X,
3383 ILE->getInit(i),
3384 Info, Deduced, TDF))
Sebastian Redl43144e72012-01-17 22:49:58 +00003385 return Result;
3386 }
3387 // Don't track the argument type, since an initializer list has none.
3388 continue;
3389 }
3390
Douglas Gregore65aacb2011-06-16 16:50:48 +00003391 // Keep track of the argument type and corresponding parameter index,
3392 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003393 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3394 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003395
Douglas Gregor7825bf32011-01-06 22:09:01 +00003396 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003397 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3398 ParamType, ArgType,
3399 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003400 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003401
Douglas Gregor7825bf32011-01-06 22:09:01 +00003402 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003404
Douglas Gregor7825bf32011-01-06 22:09:01 +00003405 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406 // For a function parameter pack that occurs at the end of the
3407 // parameter-declaration-list, the type A of each remaining argument of
3408 // the call is compared with the type P of the declarator-id of the
3409 // function parameter pack. Each comparison deduces template arguments
3410 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003411 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003413 // the parameter pack is a non-deduced context.
3414 if (ParamIdx + 1 < NumParams)
3415 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003416
Douglas Gregor7825bf32011-01-06 22:09:01 +00003417 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003418 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3419 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
Douglas Gregor7825bf32011-01-06 22:09:01 +00003421 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003422 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003423 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424
Douglas Gregore65aacb2011-06-16 16:50:48 +00003425 QualType OrigParamType = ParamPattern;
3426 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003427 Expr *Arg = Args[ArgIdx];
3428 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003429
Douglas Gregor7825bf32011-01-06 22:09:01 +00003430 unsigned TDF = 0;
3431 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3432 ParamType, ArgType, Arg,
3433 TDF)) {
3434 // We can't actually perform any deduction for this argument, so stop
3435 // deduction at this point.
3436 ++ArgIdx;
3437 break;
3438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439
Sebastian Redl43144e72012-01-17 22:49:58 +00003440 // As above, initializer lists need special handling.
3441 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3442 QualType X;
3443 if (!isStdInitializerList(ParamType, &X)) {
3444 ++ArgIdx;
3445 break;
3446 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003447
Sebastian Redl43144e72012-01-17 22:49:58 +00003448 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3449 if (TemplateDeductionResult Result =
3450 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X,
3451 ILE->getInit(i)->getType(),
3452 Info, Deduced, TDF))
3453 return Result;
3454 }
3455 } else {
3456
3457 // Keep track of the argument type and corresponding argument index,
3458 // so we can check for compatibility between the deduced A and A.
3459 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3460 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3461 ArgType));
3462
3463 if (TemplateDeductionResult Result
3464 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3465 ParamType, ArgType, Info,
3466 Deduced, TDF))
3467 return Result;
3468 }
Mike Stump11289f42009-09-09 15:08:12 +00003469
Richard Smith0a80d572014-05-29 01:12:14 +00003470 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472
Douglas Gregor7825bf32011-01-06 22:09:01 +00003473 // Build argument packs for each of the parameter packs expanded by this
3474 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003475 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003476 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003477
Douglas Gregor7825bf32011-01-06 22:09:01 +00003478 // After we've matching against a parameter pack, we're done.
3479 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003480 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003481
Mike Stump11289f42009-09-09 15:08:12 +00003482 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003483 NumExplicitlySpecified,
Douglas Gregore65aacb2011-06-16 16:50:48 +00003484 Specialization, Info, &OriginalCallArgs);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003485}
3486
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003487QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3488 QualType FunctionType) {
3489 if (ArgFunctionType.isNull())
3490 return ArgFunctionType;
3491
3492 const FunctionProtoType *FunctionTypeP =
3493 FunctionType->castAs<FunctionProtoType>();
3494 CallingConv CC = FunctionTypeP->getCallConv();
3495 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3496 const FunctionProtoType *ArgFunctionTypeP =
3497 ArgFunctionType->getAs<FunctionProtoType>();
3498 if (ArgFunctionTypeP->getCallConv() == CC &&
3499 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3500 return ArgFunctionType;
3501
3502 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3503 EI = EI.withNoReturn(NoReturn);
3504 ArgFunctionTypeP =
3505 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3506 return QualType(ArgFunctionTypeP, 0);
3507}
3508
Douglas Gregor9b146582009-07-08 20:55:45 +00003509/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003510/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3511/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003512///
3513/// \param FunctionTemplate the function template for which we are performing
3514/// template argument deduction.
3515///
James Dennett18348b62012-06-22 08:52:37 +00003516/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003517/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003518///
3519/// \param ArgFunctionType the function type that will be used as the
3520/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003521/// function template's function type. This type may be NULL, if there is no
3522/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003523///
3524/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003525/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003526/// template argument deduction.
3527///
3528/// \param Info the argument will be updated to provide additional information
3529/// about template argument deduction.
3530///
3531/// \returns the result of template argument deduction.
3532Sema::TemplateDeductionResult
3533Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003534 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003535 QualType ArgFunctionType,
3536 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003537 TemplateDeductionInfo &Info,
3538 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003539 if (FunctionTemplate->isInvalidDecl())
3540 return TDK_Invalid;
3541
Douglas Gregor9b146582009-07-08 20:55:45 +00003542 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3543 TemplateParameterList *TemplateParams
3544 = FunctionTemplate->getTemplateParameters();
3545 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003546 if (!InOverloadResolution)
3547 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003548
Douglas Gregor9b146582009-07-08 20:55:45 +00003549 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003550 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003551 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003552 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003553 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003554 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003555 if (TemplateDeductionResult Result
3556 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003557 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003558 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003559 &FunctionType, Info))
3560 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003561
3562 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003563 }
3564
Eli Friedman77dcc722012-02-08 03:07:05 +00003565 // Unevaluated SFINAE context.
3566 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003567 SFINAETrap Trap(*this);
3568
John McCallc1f69982010-02-02 02:21:27 +00003569 Deduced.resize(TemplateParams->size());
3570
Richard Smith2a7d4812013-05-04 07:00:32 +00003571 // If the function has a deduced return type, substitute it for a dependent
3572 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003573 bool HasDeducedReturnType = false;
Richard Smith2a7d4812013-05-04 07:00:32 +00003574 if (getLangOpts().CPlusPlus1y && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003575 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003576 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003577 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003578 }
3579
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003580 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003581 unsigned TDF = TDF_TopLevelParameterTypeList;
3582 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003583 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003584 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003585 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003586 FunctionType, ArgFunctionType,
3587 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003588 return Result;
3589 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003590
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003591 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003592 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3593 NumExplicitlySpecified,
3594 Specialization, Info))
3595 return Result;
3596
Richard Smith2a7d4812013-05-04 07:00:32 +00003597 // If the function has a deduced return type, deduce it now, so we can check
3598 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003599 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003600 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003601 DeduceReturnType(Specialization, Info.getLocation(), false))
3602 return TDK_MiscellaneousDeductionFailure;
3603
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003604 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003605 // specialization with respect to arguments of compatible pointer to function
3606 // types, template argument deduction fails.
3607 if (!ArgFunctionType.isNull()) {
3608 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3609 Context.getCanonicalType(Specialization->getType()),
3610 Context.getCanonicalType(ArgFunctionType)))
3611 return TDK_MiscellaneousDeductionFailure;
3612 else if(!InOverloadResolution &&
3613 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3614 return TDK_MiscellaneousDeductionFailure;
3615 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003616
3617 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003618}
3619
Faisal Vali850da1a2013-09-29 17:08:32 +00003620/// \brief Given a function declaration (e.g. a generic lambda conversion
3621/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003622/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3623/// to replace 'auto' with and not the actual result type you want
3624/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003625static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003626SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003627 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003628 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003629 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003630 assert(AutoResultType->getContainedAutoType());
3631 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003632 TypeToReplaceAutoWith);
3633 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3634}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003635
3636/// \brief Given a specialized conversion operator of a generic lambda
3637/// create the corresponding specializations of the call operator and
3638/// the static-invoker. If the return type of the call operator is auto,
3639/// deduce its return type and check if that matches the
3640/// return type of the destination function ptr.
3641
3642static inline Sema::TemplateDeductionResult
3643SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3644 CXXConversionDecl *ConversionSpecialized,
3645 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3646 QualType ReturnTypeOfDestFunctionPtr,
3647 TemplateDeductionInfo &TDInfo,
3648 Sema &S) {
3649
3650 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3651 assert(LambdaClass && LambdaClass->isGenericLambda());
3652
3653 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003654 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003655 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3656 CallOpResultType->getContainedAutoType();
3657
3658 FunctionTemplateDecl *CallOpTemplate =
3659 CallOpGeneric->getDescribedFunctionTemplate();
3660
Craig Topperc3ec1492014-05-26 06:22:03 +00003661 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003662 // Use the deduced arguments of the conversion function, to specialize our
3663 // generic lambda's call operator.
3664 if (Sema::TemplateDeductionResult Result
3665 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3666 DeducedArguments,
3667 0, CallOpSpecialized, TDInfo))
3668 return Result;
3669
3670 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003671 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3672 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003673 S.DeduceReturnType(CallOpSpecialized,
3674 CallOpSpecialized->getPointOfInstantiation(),
3675 /*Diagnose*/ true);
3676
3677 // Check to see if the return type of the destination ptr-to-function
3678 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003679 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003680 ReturnTypeOfDestFunctionPtr))
3681 return Sema::TDK_NonDeducedMismatch;
3682 // Since we have succeeded in matching the source and destination
3683 // ptr-to-functions (now including return type), and have successfully
3684 // specialized our corresponding call operator, we are ready to
3685 // specialize the static invoker with the deduced arguments of our
3686 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003687 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003688 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3689 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3690
3691 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result
3692 = S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3693 InvokerSpecialized, TDInfo);
3694 assert(Result == Sema::TDK_Success &&
3695 "If the call operator succeeded so should the invoker!");
3696 // Set the result type to match the corresponding call operator
3697 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003698 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3699 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003700 // Be sure to get the type to replace 'auto' with and not
3701 // the full result type of the call op specialization
3702 // to substitute into the 'auto' of the invoker and conversion
3703 // function.
3704 // For e.g.
3705 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3706 // We don't want to subst 'int*' into 'auto' to get int**.
3707
Alp Toker314cc812014-01-25 16:55:45 +00003708 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3709 ->getContainedAutoType()
3710 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003711 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3712 TypeToReplaceAutoWith, S);
3713 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3714 TypeToReplaceAutoWith, S);
3715 }
3716
3717 // Ensure that static invoker doesn't have a const qualifier.
3718 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3719 // do not use the CallOperator's TypeSourceInfo which allows
3720 // the const qualifier to leak through.
3721 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3722 getType().getTypePtr()->castAs<FunctionProtoType>();
3723 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3724 EPI.TypeQuals = 0;
3725 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003726 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003727 return Sema::TDK_Success;
3728}
Douglas Gregor05155d82009-08-21 23:19:43 +00003729/// \brief Deduce template arguments for a templated conversion
3730/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3731/// conversion function template specialization.
3732Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003733Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003734 QualType ToType,
3735 CXXConversionDecl *&Specialization,
3736 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003737 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003738 return TDK_Invalid;
3739
Faisal Vali2b3a3012013-10-24 23:40:02 +00003740 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003741 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3742
Faisal Vali2b3a3012013-10-24 23:40:02 +00003743 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003744
3745 // Canonicalize the types for deduction.
3746 QualType P = Context.getCanonicalType(FromType);
3747 QualType A = Context.getCanonicalType(ToType);
3748
Douglas Gregord99609a2011-03-06 09:03:20 +00003749 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003750 // If P is a reference type, the type referred to by P is used for
3751 // type deduction.
3752 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3753 P = PRef->getPointeeType();
3754
Douglas Gregord99609a2011-03-06 09:03:20 +00003755 // C++0x [temp.deduct.conv]p4:
3756 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003757 // for type deduction.
3758 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003759 A = ARef->getPointeeType().getUnqualifiedType();
3760 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003761 //
Mike Stump11289f42009-09-09 15:08:12 +00003762 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003763 else {
3764 assert(!A->isReferenceType() && "Reference types were handled above");
3765
3766 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003767 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003768 // of P for type deduction; otherwise,
3769 if (P->isArrayType())
3770 P = Context.getArrayDecayedType(P);
3771 // - If P is a function type, the pointer type produced by the
3772 // function-to-pointer standard conversion (4.3) is used in
3773 // place of P for type deduction; otherwise,
3774 else if (P->isFunctionType())
3775 P = Context.getPointerType(P);
3776 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003777 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003778 else
3779 P = P.getUnqualifiedType();
3780
Douglas Gregord99609a2011-03-06 09:03:20 +00003781 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003782 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregord99609a2011-03-06 09:03:20 +00003783 // type are ignored for type deduction. If A is a reference type, the type
3784 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003785 A = A.getUnqualifiedType();
3786 }
3787
Eli Friedman77dcc722012-02-08 03:07:05 +00003788 // Unevaluated SFINAE context.
3789 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003790 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003791
3792 // C++ [temp.deduct.conv]p1:
3793 // Template argument deduction is done by comparing the return
3794 // type of the template conversion function (call it P) with the
3795 // type that is required as the result of the conversion (call it
3796 // A) as described in 14.8.2.4.
3797 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003798 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003799 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003800 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003801
3802 // C++0x [temp.deduct.conv]p4:
3803 // In general, the deduction process attempts to find template
3804 // argument values that will make the deduced A identical to
3805 // A. However, there are two cases that allow a difference:
3806 unsigned TDF = 0;
3807 // - If the original A is a reference type, A can be more
3808 // cv-qualified than the deduced A (i.e., the type referred to
3809 // by the reference)
3810 if (ToType->isReferenceType())
3811 TDF |= TDF_ParamWithReferenceType;
3812 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003813 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003814 // conversion.
3815 //
3816 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3817 // both P and A are pointers or member pointers. In this case, we
3818 // just ignore cv-qualifiers completely).
3819 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003820 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003821 TDF |= TDF_IgnoreQualifiers;
3822 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003823 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3824 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003825 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003826
3827 // Create an Instantiation Scope for finalizing the operator.
3828 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003829 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003830 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003831 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003832 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3833 ConversionSpecialized, Info);
3834 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3835
3836 // If the conversion operator is being invoked on a lambda closure to convert
3837 // to a ptr-to-function, use the deduced arguments from the conversion function
3838 // to specialize the corresponding call operator.
3839 // e.g., int (*fp)(int) = [](auto a) { return a; };
3840 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3841
3842 // Get the return type of the destination ptr-to-function we are converting
3843 // to. This is necessary for matching the lambda call operator's return
3844 // type to that of the destination ptr-to-function's return type.
3845 assert(A->isPointerType() &&
3846 "Can only convert from lambda to ptr-to-function");
3847 const FunctionType *ToFunType =
3848 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003849 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3850
Faisal Vali2b3a3012013-10-24 23:40:02 +00003851 // Create the corresponding specializations of the call operator and
3852 // the static-invoker; and if the return type is auto,
3853 // deduce the return type and check if it matches the
3854 // DestFunctionPtrReturnType.
3855 // For instance:
3856 // auto L = [](auto a) { return f(a); };
3857 // int (*fp)(int) = L;
3858 // char (*fp2)(int) = L; <-- Not OK.
3859
3860 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3861 Specialization, Deduced, DestFunctionPtrReturnType,
3862 Info, *this);
3863 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003864 return Result;
3865}
3866
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003867/// \brief Deduce template arguments for a function template when there is
3868/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3869///
3870/// \param FunctionTemplate the function template for which we are performing
3871/// template argument deduction.
3872///
James Dennett18348b62012-06-22 08:52:37 +00003873/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003874/// arguments.
3875///
3876/// \param Specialization if template argument deduction was successful,
3877/// this will be set to the function template specialization produced by
3878/// template argument deduction.
3879///
3880/// \param Info the argument will be updated to provide additional information
3881/// about template argument deduction.
3882///
3883/// \returns the result of template argument deduction.
3884Sema::TemplateDeductionResult
3885Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003886 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003887 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003888 TemplateDeductionInfo &Info,
3889 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003890 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003891 QualType(), Specialization, Info,
3892 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003893}
3894
Richard Smith30482bc2011-02-20 03:19:35 +00003895namespace {
3896 /// Substitute the 'auto' type specifier within a type for a given replacement
3897 /// type.
3898 class SubstituteAutoTransform :
3899 public TreeTransform<SubstituteAutoTransform> {
3900 QualType Replacement;
3901 public:
3902 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) :
3903 TreeTransform<SubstituteAutoTransform>(SemaRef), Replacement(Replacement) {
3904 }
3905 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3906 // If we're building the type pattern to deduce against, don't wrap the
3907 // substituted type in an AutoType. Certain template deduction rules
3908 // apply only when a template type parameter appears directly (and not if
3909 // the parameter is found through desugaring). For instance:
3910 // auto &&lref = lvalue;
3911 // must transform into "rvalue reference to T" not "rvalue reference to
3912 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003913 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003914 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003915 TemplateTypeParmTypeLoc NewTL =
3916 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003917 NewTL.setNameLoc(TL.getNameLoc());
3918 return Result;
3919 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003920 bool Dependent =
3921 !Replacement.isNull() && Replacement->isDependentType();
3922 QualType Result =
3923 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3924 TL.getTypePtr()->isDecltypeAuto(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003925 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003926 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3927 NewTL.setNameLoc(TL.getNameLoc());
3928 return Result;
3929 }
3930 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003931
3932 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3933 // Lambdas never need to be transformed.
3934 return E;
3935 }
Richard Smith061f1e22013-04-30 21:23:01 +00003936
Richard Smith2a7d4812013-05-04 07:00:32 +00003937 QualType Apply(TypeLoc TL) {
3938 // Create some scratch storage for the transformed type locations.
3939 // FIXME: We're just going to throw this information away. Don't build it.
3940 TypeLocBuilder TLB;
3941 TLB.reserve(TL.getFullDataSize());
3942 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003943 }
Richard Smith30482bc2011-02-20 03:19:35 +00003944 };
3945}
3946
Richard Smith2a7d4812013-05-04 07:00:32 +00003947Sema::DeduceAutoResult
3948Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3949 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3950}
3951
Richard Smith061f1e22013-04-30 21:23:01 +00003952/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003953///
3954/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003955/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003956/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003957/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003958Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003959Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003960 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003961 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3962 if (NonPlaceholder.isInvalid())
3963 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003964 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003965 }
3966
Richard Smith2a7d4812013-05-04 07:00:32 +00003967 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003968 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003969 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003970 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00003971 }
3972
Richard Smith74aeef52013-04-26 16:15:35 +00003973 // If this is a 'decltype(auto)' specifier, do the decltype dance.
3974 // Since 'decltype(auto)' can only occur at the top of the type, we
3975 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00003976 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00003977 if (AT->isDecltypeAuto()) {
3978 if (isa<InitListExpr>(Init)) {
3979 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
3980 return DAR_FailedAlreadyDiagnosed;
3981 }
3982
3983 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart());
3984 // FIXME: Support a non-canonical deduced type for 'auto'.
3985 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00003986 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003987 if (Result.isNull())
3988 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00003989 return DAR_Succeeded;
3990 }
3991 }
3992
Richard Smith30482bc2011-02-20 03:19:35 +00003993 SourceLocation Loc = Init->getExprLoc();
3994
3995 LocalInstantiationScope InstScope(*this);
3996
3997 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00003998 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00003999 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4000 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004001 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4002 NamedDecl *TemplParamPtr = TemplParam;
Richard Smithb2bc2e62011-02-21 20:05:19 +00004003 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
4004 Loc);
4005
Richard Smith061f1e22013-04-30 21:23:01 +00004006 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4007 assert(!FuncParam.isNull() &&
4008 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004009
4010 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004011 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004012 Deduced.resize(1);
4013 QualType InitType = Init->getType();
4014 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004015
Craig Toppere6706e42012-09-19 02:26:47 +00004016 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004017
Richard Smith74801c82012-07-08 04:13:07 +00004018 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004019 if (InitList) {
4020 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith74801c82012-07-08 04:13:07 +00004021 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004022 TemplArg,
4023 InitList->getInit(i),
4024 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004025 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004026 }
4027 } else {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004028 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
4029 FuncParam, InitType, Init,
4030 TDF))
4031 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004032
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004033 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
4034 InitType, Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004035 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004036 }
Richard Smith30482bc2011-02-20 03:19:35 +00004037
Eli Friedmane4310952012-11-06 23:56:42 +00004038 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004039 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004040
Eli Friedmane4310952012-11-06 23:56:42 +00004041 QualType DeducedType = Deduced[0].getAsType();
4042
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004043 if (InitList) {
4044 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4045 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004046 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004047 }
4048
Richard Smith061f1e22013-04-30 21:23:01 +00004049 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004050 if (Result.isNull())
4051 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004052
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004053 // Check that the deduced argument type is compatible with the original
4054 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004055 if (!InitList && !Result.isNull() &&
4056 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004057 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004058 Result)) {
4059 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004060 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004061 }
4062
Sebastian Redl09edce02012-01-23 22:09:39 +00004063 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004064}
4065
Faisal Vali2b391ab2013-09-26 19:54:12 +00004066QualType Sema::SubstAutoType(QualType TypeWithAuto,
4067 QualType TypeToReplaceAuto) {
4068 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4069 TransformType(TypeWithAuto);
4070}
4071
4072TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4073 QualType TypeToReplaceAuto) {
4074 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4075 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004076}
4077
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004078void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4079 if (isa<InitListExpr>(Init))
4080 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004081 VDecl->isInitCapture()
4082 ? diag::err_init_capture_deduction_failure_from_init_list
4083 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004084 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4085 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004086 Diag(VDecl->getLocation(),
4087 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4088 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004089 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4090 << Init->getSourceRange();
4091}
4092
Richard Smith2a7d4812013-05-04 07:00:32 +00004093bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4094 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004095 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004096
4097 if (FD->getTemplateInstantiationPattern())
4098 InstantiateFunctionDefinition(Loc, FD);
4099
Alp Toker314cc812014-01-25 16:55:45 +00004100 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004101 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4102 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4103 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4104 }
4105
4106 return StillUndeduced;
4107}
4108
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004109static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004110MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004111 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004112 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004113 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004114
4115/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004116static void
4117AddImplicitObjectParameterType(ASTContext &Context,
4118 CXXMethodDecl *Method,
4119 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004120 // C++11 [temp.func.order]p3:
4121 // [...] The new parameter is of type "reference to cv A," where cv are
4122 // the cv-qualifiers of the function template (if any) and A is
4123 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004124 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004125 // The standard doesn't say explicitly, but we pick the appropriate kind of
4126 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004127 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4128 ArgTy = Context.getQualifiedType(ArgTy,
4129 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004130 if (Method->getRefQualifier() == RQ_RValue)
4131 ArgTy = Context.getRValueReferenceType(ArgTy);
4132 else
4133 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004134 ArgTypes.push_back(ArgTy);
4135}
4136
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004137/// \brief Determine whether the function template \p FT1 is at least as
4138/// specialized as \p FT2.
4139static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004140 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004141 FunctionTemplateDecl *FT1,
4142 FunctionTemplateDecl *FT2,
4143 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004144 unsigned NumCallArguments1,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004145 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004146 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004148 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4149 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004151 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4152 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004153 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004154 Deduced.resize(TemplateParams->size());
4155
4156 // C++0x [temp.deduct.partial]p3:
4157 // The types used to determine the ordering depend on the context in which
4158 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004159 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004160 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004161 switch (TPOC) {
4162 case TPOC_Call: {
4163 // - In the context of a function call, the function parameter types are
4164 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004165 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4166 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004167
Eli Friedman3b5774a2012-09-19 23:27:04 +00004168 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004169 // [...] If only one of the function templates is a non-static
4170 // member, that function template is considered to have a new
4171 // first parameter inserted in its function parameter list. The
4172 // new parameter is of type "reference to cv A," where cv are
4173 // the cv-qualifiers of the function template (if any) and A is
4174 // the class of which the function template is a member.
4175 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004176 // Note that we interpret this to mean "if one of the function
4177 // templates is a non-static member and the other is a non-member";
4178 // otherwise, the ordering rules for static functions against non-static
4179 // functions don't make any sense.
4180 //
Douglas Gregoree430a32010-11-15 15:41:16 +00004181 // C++98/03 doesn't have this provision, so instead we drop the
Eli Friedman3b5774a2012-09-19 23:27:04 +00004182 // first argument of the free function, which seems to match
4183 // existing practice.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004184 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004185
4186 unsigned Skip1 = 0, Skip2 = 0;
4187 unsigned NumComparedArguments = NumCallArguments1;
4188
4189 if (!Method2 && Method1 && !Method1->isStatic()) {
4190 if (S.getLangOpts().CPlusPlus11) {
4191 // Compare 'this' from Method1 against first parameter from Method2.
4192 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4193 ++NumComparedArguments;
4194 } else
4195 // Ignore first parameter from Method2.
4196 ++Skip2;
4197 } else if (!Method1 && Method2 && !Method2->isStatic()) {
4198 if (S.getLangOpts().CPlusPlus11)
4199 // Compare 'this' from Method2 against first parameter from Method1.
4200 AddImplicitObjectParameterType(S.Context, Method2, Args2);
4201 else
4202 // Ignore first parameter from Method1.
4203 ++Skip1;
4204 }
4205
Alp Toker9cacbab2014-01-20 20:26:09 +00004206 Args1.insert(Args1.end(), Proto1->param_type_begin() + Skip1,
4207 Proto1->param_type_end());
4208 Args2.insert(Args2.end(), Proto2->param_type_begin() + Skip2,
4209 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210
Douglas Gregorb837ea42011-01-11 17:34:58 +00004211 // C++ [temp.func.order]p5:
4212 // The presence of unused ellipsis and default arguments has no effect on
4213 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004214 if (Args1.size() > NumComparedArguments)
4215 Args1.resize(NumComparedArguments);
4216 if (Args2.size() > NumComparedArguments)
4217 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004218 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4219 Args1.data(), Args1.size(), Info, Deduced,
4220 TDF_None, /*PartialOrdering=*/true,
Douglas Gregor63814022011-01-21 17:29:42 +00004221 RefParamComparisons))
Richard Smith0a80d572014-05-29 01:12:14 +00004222 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004224 break;
4225 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004227 case TPOC_Conversion:
4228 // - In the context of a call to a conversion operator, the return types
4229 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004230 if (DeduceTemplateArgumentsByTypeMatch(
4231 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4232 Info, Deduced, TDF_None,
4233 /*PartialOrdering=*/true, RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004234 return false;
4235 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004237 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004238 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004239 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004240 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4241 FD2->getType(), FD1->getType(),
4242 Info, Deduced, TDF_None,
4243 /*PartialOrdering=*/true,
4244 RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004245 return false;
4246 break;
4247 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004248
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004249 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250 // In most cases, all template parameters must have values in order for
4251 // deduction to succeed, but for partial ordering purposes a template
4252 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004253 // types being used for partial ordering. [ Note: a template parameter used
4254 // in a non-deduced context is considered used. -end note]
4255 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4256 for (; ArgIdx != NumArgs; ++ArgIdx)
4257 if (Deduced[ArgIdx].isNull())
4258 break;
4259
4260 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004262 // as FT2.
4263 return true;
4264 }
4265
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004266 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004267 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004268 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004269 case TPOC_Call:
4270 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4271 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004272 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004273 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004274 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004276 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004277 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4278 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004279 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004281 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004282 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004283 TemplateParams->getDepth(),
4284 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004285 break;
4286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004288 for (; ArgIdx != NumArgs; ++ArgIdx)
4289 // If this argument had no value deduced but was used in one of the types
4290 // used for partial ordering, then deduction fails.
4291 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4292 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004294 return true;
4295}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296
Douglas Gregorcef1a032011-01-16 16:03:23 +00004297/// \brief Determine whether this a function template whose parameter-type-list
4298/// ends with a function parameter pack.
4299static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4300 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4301 unsigned NumParams = Function->getNumParams();
4302 if (NumParams == 0)
4303 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304
Douglas Gregorcef1a032011-01-16 16:03:23 +00004305 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4306 if (!Last->isParameterPack())
4307 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregorcef1a032011-01-16 16:03:23 +00004309 // Make sure that no previous parameter is a parameter pack.
4310 while (--NumParams > 0) {
4311 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4312 return false;
4313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314
Douglas Gregorcef1a032011-01-16 16:03:23 +00004315 return true;
4316}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317
Douglas Gregorbe999392009-09-15 16:23:51 +00004318/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004319/// to the rules of function template partial ordering (C++ [temp.func.order]).
4320///
4321/// \param FT1 the first function template
4322///
4323/// \param FT2 the second function template
4324///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004325/// \param TPOC the context in which we are performing partial ordering of
4326/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004327///
Richard Smithe5b52202013-09-11 00:52:39 +00004328/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4329/// only when \c TPOC is \c TPOC_Call.
4330///
4331/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4332/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004333///
Douglas Gregorbe999392009-09-15 16:23:51 +00004334/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004335/// template is more specialized, returns NULL.
4336FunctionTemplateDecl *
4337Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4338 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004339 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004340 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004341 unsigned NumCallArguments1,
4342 unsigned NumCallArguments2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004343 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Craig Topperc3ec1492014-05-26 06:22:03 +00004345 NumCallArguments1, nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004347 NumCallArguments2,
Douglas Gregor63814022011-01-21 17:29:42 +00004348 &RefParamComparisons);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004349
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004350 if (Better1 != Better2) // We have a clear winner
4351 return Better1? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004352
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004353 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004354 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004355
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004356 // C++0x [temp.deduct.partial]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357 // If for each type being considered a given template is at least as
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004358 // specialized for all types and more specialized for some set of types and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359 // the other template is not more specialized for any types or is not at
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004360 // least as specialized for any types, then the given template is more
4361 // specialized than the other template. Otherwise, neither template is more
4362 // specialized than the other.
4363 Better1 = false;
4364 Better2 = false;
Douglas Gregor63814022011-01-21 17:29:42 +00004365 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004366 // C++0x [temp.deduct.partial]p9:
4367 // If, for a given type, deduction succeeds in both directions (i.e., the
Douglas Gregor63814022011-01-21 17:29:42 +00004368 // types are identical after the transformations above) and both P and A
4369 // were reference types (before being replaced with the type referred to
4370 // above):
4371
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372 // -- if the type from the argument template was an lvalue reference
Douglas Gregor63814022011-01-21 17:29:42 +00004373 // and the type from the parameter template was not, the argument
4374 // type is considered to be more specialized than the other;
4375 // otherwise,
4376 if (!RefParamComparisons[I].ArgIsRvalueRef &&
4377 RefParamComparisons[I].ParamIsRvalueRef) {
4378 Better2 = true;
4379 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004380 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004381 continue;
4382 } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
4383 RefParamComparisons[I].ArgIsRvalueRef) {
4384 Better1 = true;
4385 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004386 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004387 continue;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004389
Douglas Gregor63814022011-01-21 17:29:42 +00004390 // -- if the type from the argument template is more cv-qualified than
4391 // the type from the parameter template (as described above), the
4392 // argument type is considered to be more specialized than the
4393 // other; otherwise,
4394 switch (RefParamComparisons[I].Qualifiers) {
4395 case NeitherMoreQualified:
4396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397
Douglas Gregor63814022011-01-21 17:29:42 +00004398 case ParamMoreQualified:
4399 Better1 = true;
4400 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004401 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004402 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004403
Douglas Gregor63814022011-01-21 17:29:42 +00004404 case ArgMoreQualified:
4405 Better2 = true;
4406 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004407 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004408 continue;
4409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Douglas Gregor63814022011-01-21 17:29:42 +00004411 // -- neither type is more specialized than the other.
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004414 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor05155d82009-08-21 23:19:43 +00004415 if (Better1)
4416 return FT1;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004417 else if (Better2)
4418 return FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419
Douglas Gregorcef1a032011-01-16 16:03:23 +00004420 // FIXME: This mimics what GCC implements, but doesn't match up with the
4421 // proposed resolution for core issue 692. This area needs to be sorted out,
4422 // but for now we attempt to maintain compatibility.
4423 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4424 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4425 if (Variadic1 != Variadic2)
4426 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427
Craig Topperc3ec1492014-05-26 06:22:03 +00004428 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004429}
Douglas Gregor9b146582009-07-08 20:55:45 +00004430
Douglas Gregor450f00842009-09-25 18:43:00 +00004431/// \brief Determine if the two templates are equivalent.
4432static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4433 if (T1 == T2)
4434 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435
Douglas Gregor450f00842009-09-25 18:43:00 +00004436 if (!T1 || !T2)
4437 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004438
Douglas Gregor450f00842009-09-25 18:43:00 +00004439 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4440}
4441
4442/// \brief Retrieve the most specialized of the given function template
4443/// specializations.
4444///
John McCall58cc69d2010-01-27 01:50:18 +00004445/// \param SpecBegin the start iterator of the function template
4446/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004447///
John McCall58cc69d2010-01-27 01:50:18 +00004448/// \param SpecEnd the end iterator of the function template
4449/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004450///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004452/// diagnostic should occur.
4453///
4454/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4455/// no matching candidates.
4456///
4457/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4458/// occurs.
4459///
4460/// \param CandidateDiag partial diagnostic used for each function template
4461/// specialization that is a candidate in the ambiguous ordering. One parameter
4462/// in this diagnostic should be unbound, which will correspond to the string
4463/// describing the template arguments for the function template specialization.
4464///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004465/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004466/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004467UnresolvedSetIterator Sema::getMostSpecialized(
4468 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4469 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004470 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4471 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4472 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004473 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004474 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004475 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004476 FailedCandidates.NoteCandidates(*this, Loc);
4477 }
John McCall58cc69d2010-01-27 01:50:18 +00004478 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004480
4481 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004482 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004483
Douglas Gregor450f00842009-09-25 18:43:00 +00004484 // Find the function template that is better than all of the templates it
4485 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004486 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004487 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004488 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004489 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004490 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4491 FunctionTemplateDecl *Challenger
4492 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004493 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004494 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004495 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004496 Challenger)) {
4497 Best = I;
4498 BestTemplate = Challenger;
4499 }
4500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501
Douglas Gregor450f00842009-09-25 18:43:00 +00004502 // Make sure that the "best" function template is more specialized than all
4503 // of the others.
4504 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004505 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4506 FunctionTemplateDecl *Challenger
4507 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004508 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004510 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004511 BestTemplate)) {
4512 Ambiguous = true;
4513 break;
4514 }
4515 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516
Douglas Gregor450f00842009-09-25 18:43:00 +00004517 if (!Ambiguous) {
4518 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004519 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521
Douglas Gregor450f00842009-09-25 18:43:00 +00004522 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004523 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004524 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
Richard Smithb875c432013-05-04 01:51:08 +00004526 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004527 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4528 PartialDiagnostic PD = CandidateDiag;
4529 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004530 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004531 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004532 if (!TargetType.isNull())
4533 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4534 TargetType);
4535 Diag((*I)->getLocation(), PD);
4536 }
Richard Smithb875c432013-05-04 01:51:08 +00004537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004538
John McCall58cc69d2010-01-27 01:50:18 +00004539 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004540}
4541
Douglas Gregorbe999392009-09-15 16:23:51 +00004542/// \brief Returns the more specialized class template partial specialization
4543/// according to the rules of partial ordering of class template partial
4544/// specializations (C++ [temp.class.order]).
4545///
4546/// \param PS1 the first class template partial specialization
4547///
4548/// \param PS2 the second class template partial specialization
4549///
4550/// \returns the more specialized class template partial specialization. If
4551/// neither partial specialization is more specialized, returns NULL.
4552ClassTemplatePartialSpecializationDecl *
4553Sema::getMoreSpecializedPartialSpecialization(
4554 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004555 ClassTemplatePartialSpecializationDecl *PS2,
4556 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004557 // C++ [temp.class.order]p1:
4558 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559 // specialized as the second if, given the following rewrite to two
4560 // function templates, the first function template is at least as
4561 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004562 // templates (14.6.6.2):
4563 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004564 // first partial specialization and has a single function parameter
4565 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004566 // arguments of the first partial specialization, and
4567 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004568 // second partial specialization and has a single function parameter
4569 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004570 // arguments of the second partial specialization.
4571 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004572 // Rather than synthesize function templates, we merely perform the
4573 // equivalent partial ordering by performing deduction directly on
4574 // the template arguments of the class template partial
4575 // specializations. This computation is slightly simpler than the
4576 // general problem of function template partial ordering, because
4577 // class template partial specializations are more constrained. We
4578 // know that every template parameter is deducible from the class
4579 // template partial specialization's template arguments, for
4580 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004581 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004582 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004583
4584 QualType PT1 = PS1->getInjectedSpecializationType();
4585 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004586
Douglas Gregorbe999392009-09-15 16:23:51 +00004587 // Determine whether PS1 is at least as specialized as PS2
4588 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004589 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4590 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004591 PT2, PT1, Info, Deduced, TDF_None,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004592 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004593 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004594 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004595 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004596 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004597 Better1 = !::FinishTemplateArgumentDeduction(
4598 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4599 }
4600
4601 // Determine whether PS2 is at least as specialized as PS1
4602 Deduced.clear();
4603 Deduced.resize(PS1->getTemplateParameters()->size());
4604 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4605 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
4606 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004607 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004608 if (Better2) {
4609 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4610 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004611 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004612 Better2 = !::FinishTemplateArgumentDeduction(
4613 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4614 }
4615
4616 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004617 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004618
4619 return Better1 ? PS1 : PS2;
4620}
4621
Larisse Voufo30616382013-08-23 22:21:36 +00004622/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4623/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4624/// VarTemplate(Partial)SpecializationDecl with a new data
4625/// structure Template(Partial)SpecializationDecl, and
4626/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004627VarTemplatePartialSpecializationDecl *
4628Sema::getMoreSpecializedPartialSpecialization(
4629 VarTemplatePartialSpecializationDecl *PS1,
4630 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4631 SmallVector<DeducedTemplateArgument, 4> Deduced;
4632 TemplateDeductionInfo Info(Loc);
4633
Richard Smithf04fd0b2013-12-12 23:14:16 +00004634 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004635 "the partial specializations being compared should specialize"
4636 " the same template.");
4637 TemplateName Name(PS1->getSpecializedTemplate());
4638 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4639 QualType PT1 = Context.getTemplateSpecializationType(
4640 CanonTemplate, PS1->getTemplateArgs().data(),
4641 PS1->getTemplateArgs().size());
4642 QualType PT2 = Context.getTemplateSpecializationType(
4643 CanonTemplate, PS2->getTemplateArgs().data(),
4644 PS2->getTemplateArgs().size());
4645
4646 // Determine whether PS1 is at least as specialized as PS2
4647 Deduced.resize(PS2->getTemplateParameters()->size());
4648 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4649 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
4650 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004651 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004652 if (Better1) {
4653 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4654 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004655 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4657 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004658 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004659 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004660
Douglas Gregorbe999392009-09-15 16:23:51 +00004661 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004662 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004663 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004664 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4665 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004666 PT1, PT2, Info, Deduced, TDF_None,
4667 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004668 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004669 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004670 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004671 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004672 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4673 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004674 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004675 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004676
Douglas Gregorbe999392009-09-15 16:23:51 +00004677 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004678 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679
Douglas Gregorbe999392009-09-15 16:23:51 +00004680 return Better1? PS1 : PS2;
4681}
4682
Mike Stump11289f42009-09-09 15:08:12 +00004683static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004684MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004685 const TemplateArgument &TemplateArg,
4686 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004687 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004688 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004689
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004690/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004691/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004692static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004693MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004694 const Expr *E,
4695 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004696 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004697 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004698 // We can deduce from a pack expansion.
4699 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4700 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
Richard Smith34349002012-07-09 03:07:20 +00004702 // Skip through any implicit casts we added while type-checking, and any
4703 // substitutions performed by template alias expansion.
4704 while (1) {
4705 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4706 E = ICE->getSubExpr();
4707 else if (const SubstNonTypeTemplateParmExpr *Subst =
4708 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4709 E = Subst->getReplacement();
4710 else
4711 break;
4712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713
4714 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004715 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004716 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004717 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004718 return;
4719
Mike Stump11289f42009-09-09 15:08:12 +00004720 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004721 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4722 if (!NTTP)
4723 return;
4724
Douglas Gregor21610382009-10-29 00:04:11 +00004725 if (NTTP->getDepth() == Depth)
4726 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004727}
4728
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004729/// \brief Mark the template parameters that are used by the given
4730/// nested name specifier.
4731static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004732MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004733 NestedNameSpecifier *NNS,
4734 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004735 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004736 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004737 if (!NNS)
4738 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004739
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004740 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004741 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004742 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004743 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004744}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004745
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004746/// \brief Mark the template parameters that are used by the given
4747/// template name.
4748static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004749MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004750 TemplateName Name,
4751 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004752 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004753 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004754 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4755 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004756 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4757 if (TTP->getDepth() == Depth)
4758 Used[TTP->getIndex()] = true;
4759 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004760 return;
4761 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004762
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004763 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004764 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004765 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004766 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004767 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004768 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004769}
4770
4771/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004772/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004773static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004774MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004775 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004776 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004777 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004778 if (T.isNull())
4779 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004780
Douglas Gregor91772d12009-06-13 00:26:55 +00004781 // Non-dependent types have nothing deducible
4782 if (!T->isDependentType())
4783 return;
4784
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004785 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004786 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004787 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004788 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004789 cast<PointerType>(T)->getPointeeType(),
4790 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004791 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004792 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004793 break;
4794
4795 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004796 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004797 cast<BlockPointerType>(T)->getPointeeType(),
4798 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004799 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004800 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004801 break;
4802
4803 case Type::LValueReference:
4804 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004805 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004806 cast<ReferenceType>(T)->getPointeeType(),
4807 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004808 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004809 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004810 break;
4811
4812 case Type::MemberPointer: {
4813 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004814 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004815 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004816 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004817 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004818 break;
4819 }
4820
4821 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004822 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004823 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004824 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004825 // Fall through to check the element type
4826
4827 case Type::ConstantArray:
4828 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004829 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004830 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004831 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004832 break;
4833
4834 case Type::Vector:
4835 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004836 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004837 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004838 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004839 break;
4840
Douglas Gregor758a8692009-06-17 21:51:59 +00004841 case Type::DependentSizedExtVector: {
4842 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004843 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004844 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004845 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004846 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004847 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004848 break;
4849 }
4850
Douglas Gregor91772d12009-06-13 00:26:55 +00004851 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004852 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004853 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4854 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004855 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4856 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004857 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004858 break;
4859 }
4860
Douglas Gregor21610382009-10-29 00:04:11 +00004861 case Type::TemplateTypeParm: {
4862 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4863 if (TTP->getDepth() == Depth)
4864 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004865 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004866 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004867
Douglas Gregorfb322d82011-01-14 05:11:40 +00004868 case Type::SubstTemplateTypeParmPack: {
4869 const SubstTemplateTypeParmPackType *Subst
4870 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004871 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004872 QualType(Subst->getReplacedParameter(), 0),
4873 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004874 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004875 OnlyDeduced, Depth, Used);
4876 break;
4877 }
4878
John McCall2408e322010-04-27 00:57:59 +00004879 case Type::InjectedClassName:
4880 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4881 // fall through
4882
Douglas Gregor91772d12009-06-13 00:26:55 +00004883 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004884 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004885 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004886 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004887 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888
Douglas Gregord0ad2942010-12-23 01:24:45 +00004889 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004890 // If the template argument list of P contains a pack expansion that is not
4891 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004892 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004893 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004894 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4895 break;
4896
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004897 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004898 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004899 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004900 break;
4901 }
4902
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004903 case Type::Complex:
4904 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004905 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004906 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004907 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004908 break;
4909
Eli Friedman0dfb8892011-10-06 23:00:33 +00004910 case Type::Atomic:
4911 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004912 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004913 cast<AtomicType>(T)->getValueType(),
4914 OnlyDeduced, Depth, Used);
4915 break;
4916
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004917 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004918 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004919 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004920 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004921 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004922 break;
4923
John McCallc392f372010-06-11 00:33:02 +00004924 case Type::DependentTemplateSpecialization: {
4925 const DependentTemplateSpecializationType *Spec
4926 = cast<DependentTemplateSpecializationType>(T);
4927 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004928 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00004929 OnlyDeduced, Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930
Douglas Gregord0ad2942010-12-23 01:24:45 +00004931 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932 // If the template argument list of P contains a pack expansion that is not
4933 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004934 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004936 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4937 break;
4938
John McCallc392f372010-06-11 00:33:02 +00004939 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004940 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004941 Used);
4942 break;
4943 }
4944
John McCallbd8d9bd2010-03-01 23:49:17 +00004945 case Type::TypeOf:
4946 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004947 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004948 cast<TypeOfType>(T)->getUnderlyingType(),
4949 OnlyDeduced, Depth, Used);
4950 break;
4951
4952 case Type::TypeOfExpr:
4953 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004954 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004955 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4956 OnlyDeduced, Depth, Used);
4957 break;
4958
4959 case Type::Decltype:
4960 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004961 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004962 cast<DecltypeType>(T)->getUnderlyingExpr(),
4963 OnlyDeduced, Depth, Used);
4964 break;
4965
Alexis Hunte852b102011-05-24 22:41:36 +00004966 case Type::UnaryTransform:
4967 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004968 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004969 cast<UnaryTransformType>(T)->getUnderlyingType(),
4970 OnlyDeduced, Depth, Used);
4971 break;
4972
Douglas Gregord2fa7662010-12-20 02:24:11 +00004973 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004974 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004975 cast<PackExpansionType>(T)->getPattern(),
4976 OnlyDeduced, Depth, Used);
4977 break;
4978
Richard Smith30482bc2011-02-20 03:19:35 +00004979 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004980 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004981 cast<AutoType>(T)->getDeducedType(),
4982 OnlyDeduced, Depth, Used);
4983
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004984 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004985 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004986 case Type::VariableArray:
4987 case Type::FunctionNoProto:
4988 case Type::Record:
4989 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004990 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004991 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004992 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004993 case Type::UnresolvedUsing:
Douglas Gregor91772d12009-06-13 00:26:55 +00004994#define TYPE(Class, Base)
4995#define ABSTRACT_TYPE(Class, Base)
4996#define DEPENDENT_TYPE(Class, Base)
4997#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4998#include "clang/AST/TypeNodes.def"
4999 break;
5000 }
5001}
5002
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005003/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005004/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005005static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005006MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005007 const TemplateArgument &TemplateArg,
5008 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005009 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005010 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005011 switch (TemplateArg.getKind()) {
5012 case TemplateArgument::Null:
5013 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005014 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005015 break;
Mike Stump11289f42009-09-09 15:08:12 +00005016
Eli Friedmanb826a002012-09-26 02:36:12 +00005017 case TemplateArgument::NullPtr:
5018 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5019 Depth, Used);
5020 break;
5021
Douglas Gregor91772d12009-06-13 00:26:55 +00005022 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005023 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005024 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005025 break;
5026
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005027 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005028 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005029 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005031 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005032 break;
5033
5034 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005035 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005036 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005037 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005038
Anders Carlssonbc343912009-06-15 17:04:53 +00005039 case TemplateArgument::Pack:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005040 for (TemplateArgument::pack_iterator P = TemplateArg.pack_begin(),
5041 PEnd = TemplateArg.pack_end();
5042 P != PEnd; ++P)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005043 MarkUsedTemplateParameters(Ctx, *P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005044 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005045 }
5046}
5047
James Dennett41725122012-06-22 10:16:05 +00005048/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005049/// template argument list.
5050///
5051/// \param TemplateArgs the template argument list from which template
5052/// parameters will be deduced.
5053///
James Dennett41725122012-06-22 10:16:05 +00005054/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005055/// to indicate when the corresponding template parameter will be
5056/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005057void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005058Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005059 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005060 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005061 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062 // If the template argument list of P contains a pack expansion that is not
5063 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005064 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005066 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5067 return;
5068
Douglas Gregor91772d12009-06-13 00:26:55 +00005069 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005070 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005071 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005072}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005073
5074/// \brief Marks all of the template parameters that will be deduced by a
5075/// call to the given function template.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005077Sema::MarkDeducedTemplateParameters(ASTContext &Ctx,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005078 const FunctionTemplateDecl *FunctionTemplate,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005079 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005081 = FunctionTemplate->getTemplateParameters();
5082 Deduced.clear();
5083 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005084
Douglas Gregorce23bae2009-09-18 23:21:38 +00005085 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5086 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005087 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005088 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005089}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005090
5091bool hasDeducibleTemplateParameters(Sema &S,
5092 FunctionTemplateDecl *FunctionTemplate,
5093 QualType T) {
5094 if (!T->isDependentType())
5095 return false;
5096
5097 TemplateParameterList *TemplateParams
5098 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005099 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005100 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005101 Deduced);
5102
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005103 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005104}