blob: 53a75d227c7b965ccf0428cdb825dc44132eb615 [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;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002098 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002099 // When converting the deduced template argument, append it to the
2100 // general output list. We need to do this so that the template argument
2101 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002102 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002103 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002104 if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002105 NTTPType, PackedArgsBuilder.size(),
2106 Info, InFunctionTemplate, Output))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002107 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002108
Douglas Gregor51bc5712011-01-05 20:52:18 +00002109 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002110 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
Douglas Gregorca4686d2011-01-04 23:35:54 +00002113 // Create the resulting argument pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002114 Output.push_back(TemplateArgument::CreatePackCopy(S.Context,
Douglas Gregor74c6d192011-01-11 23:09:57 +00002115 PackedArgsBuilder.data(),
2116 PackedArgsBuilder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002117 return false;
2118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
Douglas Gregorca4686d2011-01-04 23:35:54 +00002120 // Convert the deduced template argument into a template
2121 // argument that we can check, almost as if the user had written
2122 // the template argument explicitly.
2123 TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2124 Info.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002125
Douglas Gregorca4686d2011-01-04 23:35:54 +00002126 // Check the template argument, converting it as necessary.
2127 return S.CheckTemplateArgument(Param, ArgLoc,
2128 Template,
2129 Template->getLocation(),
2130 Template->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002131 ArgumentPackIndex,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002132 Output,
2133 InFunctionTemplate
2134 ? (Arg.wasDeducedFromArrayBound()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002135 ? Sema::CTAK_DeducedFromArrayBound
Douglas Gregorca4686d2011-01-04 23:35:54 +00002136 : Sema::CTAK_Deduced)
2137 : Sema::CTAK_Specified);
2138}
2139
Douglas Gregor684268d2010-04-29 06:21:43 +00002140/// Complete template argument deduction for a class template partial
2141/// specialization.
2142static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002143FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002144 ClassTemplatePartialSpecializationDecl *Partial,
2145 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002146 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002147 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002148 // Unevaluated SFINAE context.
2149 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002150 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
Douglas Gregor684268d2010-04-29 06:21:43 +00002152 Sema::ContextRAII SavedContext(S, Partial);
2153
2154 // C++ [temp.deduct.type]p2:
2155 // [...] or if any template argument remains neither deduced nor
2156 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002157 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002158 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2159 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002160 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002161 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002162 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002163 return Sema::TDK_Incomplete;
2164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002165
Douglas Gregorca4686d2011-01-04 23:35:54 +00002166 // We have deduced this argument, so it still needs to be
2167 // checked and converted.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168
Douglas Gregorca4686d2011-01-04 23:35:54 +00002169 // First, for a non-type template parameter type that is
2170 // initialized by a declaration, we need the type of the
2171 // corresponding non-type template parameter.
2172 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor51bc5712011-01-05 20:52:18 +00002174 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002175 NTTPType = NTTP->getType();
Douglas Gregor51bc5712011-01-05 20:52:18 +00002176 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregor51bc5712011-01-05 20:52:18 +00002178 Builder.data(), Builder.size());
2179 NTTPType = S.SubstType(NTTPType,
2180 MultiLevelTemplateArgumentList(TemplateArgs),
2181 NTTP->getLocation(),
2182 NTTP->getDeclName());
2183 if (NTTPType.isNull()) {
2184 Info.Param = makeTemplateParameter(Param);
2185 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002186 Info.reset(TemplateArgumentList::CreateCopy(S.Context,
2187 Builder.data(),
Douglas Gregor51bc5712011-01-05 20:52:18 +00002188 Builder.size()));
2189 return Sema::TDK_SubstitutionFailure;
2190 }
2191 }
2192 }
2193
Douglas Gregorca4686d2011-01-04 23:35:54 +00002194 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002195 Partial, NTTPType, 0, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002196 Builder)) {
2197 Info.Param = makeTemplateParameter(Param);
2198 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002199 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2200 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002201 return Sema::TDK_SubstitutionFailure;
2202 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204
Douglas Gregor684268d2010-04-29 06:21:43 +00002205 // Form the template argument list from the deduced template arguments.
2206 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002208 Builder.size());
2209
Douglas Gregor684268d2010-04-29 06:21:43 +00002210 Info.reset(DeducedArgumentList);
2211
2212 // Substitute the deduced template arguments into the template
2213 // arguments of the class template partial specialization, and
2214 // verify that the instantiated template arguments are both valid
2215 // and are equivalent to the template arguments originally provided
2216 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002217 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002218 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002219 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002220 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002221 const TemplateArgumentLoc *PartialTemplateArgs
2222 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002223
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002224 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2225 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002226
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002227 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002228 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2229 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2230 if (ParamIdx >= Partial->getTemplateParameters()->size())
2231 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2232
2233 Decl *Param
2234 = const_cast<NamedDecl *>(
2235 Partial->getTemplateParameters()->getParam(ParamIdx));
2236 Info.Param = makeTemplateParameter(Param);
2237 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2238 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002239 }
2240
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002241 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002242 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002243 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002244 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002245
Douglas Gregorca4686d2011-01-04 23:35:54 +00002246 TemplateParameterList *TemplateParams
2247 = ClassTemplate->getTemplateParameters();
2248 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002249 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002250 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002251 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002252 Info.FirstArg = TemplateArgs[I];
2253 Info.SecondArg = InstArg;
2254 return Sema::TDK_NonDeducedMismatch;
2255 }
2256 }
2257
2258 if (Trap.hasErrorOccurred())
2259 return Sema::TDK_SubstitutionFailure;
2260
2261 return Sema::TDK_Success;
2262}
2263
Douglas Gregor170bc422009-06-12 22:31:52 +00002264/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002265/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002266/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002267Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002268Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002269 const TemplateArgumentList &TemplateArgs,
2270 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002271 if (Partial->isInvalidDecl())
2272 return TDK_Invalid;
2273
Douglas Gregor170bc422009-06-12 22:31:52 +00002274 // C++ [temp.class.spec.match]p2:
2275 // A partial specialization matches a given actual template
2276 // argument list if the template arguments of the partial
2277 // specialization can be deduced from the actual template argument
2278 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002279
2280 // Unevaluated SFINAE context.
2281 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002282 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002283
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002284 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002285 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002286 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002287 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002288 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002289 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002290 TemplateArgs, Info, Deduced))
2291 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002292
Richard Smith80934652012-07-16 01:09:10 +00002293 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002294 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2295 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002296 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002297 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002298
Douglas Gregore1416332009-06-14 08:02:22 +00002299 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002300 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002301
2302 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002303 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002304}
Douglas Gregor91772d12009-06-13 00:26:55 +00002305
Larisse Voufo39a1e502013-08-06 01:03:05 +00002306/// Complete template argument deduction for a variable template partial
2307/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002308/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2309/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2310/// VarTemplate(Partial)SpecializationDecl with a new data
2311/// structure Template(Partial)SpecializationDecl, and
2312/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002313static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2314 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2315 const TemplateArgumentList &TemplateArgs,
2316 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2317 TemplateDeductionInfo &Info) {
2318 // Unevaluated SFINAE context.
2319 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2320 Sema::SFINAETrap Trap(S);
2321
2322 // C++ [temp.deduct.type]p2:
2323 // [...] or if any template argument remains neither deduced nor
2324 // explicitly specified, template argument deduction fails.
2325 SmallVector<TemplateArgument, 4> Builder;
2326 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2327 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2328 NamedDecl *Param = PartialParams->getParam(I);
2329 if (Deduced[I].isNull()) {
2330 Info.Param = makeTemplateParameter(Param);
2331 return Sema::TDK_Incomplete;
2332 }
2333
2334 // We have deduced this argument, so it still needs to be
2335 // checked and converted.
2336
2337 // First, for a non-type template parameter type that is
2338 // initialized by a declaration, we need the type of the
2339 // corresponding non-type template parameter.
2340 QualType NTTPType;
2341 if (NonTypeTemplateParmDecl *NTTP =
2342 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2343 NTTPType = NTTP->getType();
2344 if (NTTPType->isDependentType()) {
2345 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2346 Builder.data(), Builder.size());
2347 NTTPType =
2348 S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs),
2349 NTTP->getLocation(), NTTP->getDeclName());
2350 if (NTTPType.isNull()) {
2351 Info.Param = makeTemplateParameter(Param);
2352 // FIXME: These template arguments are temporary. Free them!
2353 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2354 Builder.size()));
2355 return Sema::TDK_SubstitutionFailure;
2356 }
2357 }
2358 }
2359
2360 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType,
2361 0, Info, false, Builder)) {
2362 Info.Param = makeTemplateParameter(Param);
2363 // FIXME: These template arguments are temporary. Free them!
2364 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2365 Builder.size()));
2366 return Sema::TDK_SubstitutionFailure;
2367 }
2368 }
2369
2370 // Form the template argument list from the deduced template arguments.
2371 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2372 S.Context, Builder.data(), Builder.size());
2373
2374 Info.reset(DeducedArgumentList);
2375
2376 // Substitute the deduced template arguments into the template
2377 // arguments of the class template partial specialization, and
2378 // verify that the instantiated template arguments are both valid
2379 // and are equivalent to the template arguments originally provided
2380 // to the class template.
2381 LocalInstantiationScope InstScope(S);
2382 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002383 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2384 = Partial->getTemplateArgsAsWritten();
2385 const TemplateArgumentLoc *PartialTemplateArgs
2386 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002387
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002388 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2389 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002390
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002391 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002392 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2393 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2394 if (ParamIdx >= Partial->getTemplateParameters()->size())
2395 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2396
2397 Decl *Param = const_cast<NamedDecl *>(
2398 Partial->getTemplateParameters()->getParam(ParamIdx));
2399 Info.Param = makeTemplateParameter(Param);
2400 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2401 return Sema::TDK_SubstitutionFailure;
2402 }
2403 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2404 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2405 false, ConvertedInstArgs))
2406 return Sema::TDK_SubstitutionFailure;
2407
2408 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2409 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2410 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2411 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2412 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2413 Info.FirstArg = TemplateArgs[I];
2414 Info.SecondArg = InstArg;
2415 return Sema::TDK_NonDeducedMismatch;
2416 }
2417 }
2418
2419 if (Trap.hasErrorOccurred())
2420 return Sema::TDK_SubstitutionFailure;
2421
2422 return Sema::TDK_Success;
2423}
2424
2425/// \brief Perform template argument deduction to determine whether
2426/// the given template arguments match the given variable template
2427/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002428/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2429/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2430/// VarTemplate(Partial)SpecializationDecl with a new data
2431/// structure Template(Partial)SpecializationDecl, and
2432/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002433Sema::TemplateDeductionResult
2434Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2435 const TemplateArgumentList &TemplateArgs,
2436 TemplateDeductionInfo &Info) {
2437 if (Partial->isInvalidDecl())
2438 return TDK_Invalid;
2439
2440 // C++ [temp.class.spec.match]p2:
2441 // A partial specialization matches a given actual template
2442 // argument list if the template arguments of the partial
2443 // specialization can be deduced from the actual template argument
2444 // list (14.8.2).
2445
2446 // Unevaluated SFINAE context.
2447 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2448 SFINAETrap Trap(*this);
2449
2450 SmallVector<DeducedTemplateArgument, 4> Deduced;
2451 Deduced.resize(Partial->getTemplateParameters()->size());
2452 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2453 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2454 TemplateArgs, Info, Deduced))
2455 return Result;
2456
2457 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002458 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2459 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002460 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002461 return TDK_InstantiationDepth;
2462
2463 if (Trap.hasErrorOccurred())
2464 return Sema::TDK_SubstitutionFailure;
2465
2466 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2467 Deduced, Info);
2468}
2469
Douglas Gregorfc516c92009-06-26 23:27:24 +00002470/// \brief Determine whether the given type T is a simple-template-id type.
2471static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002472 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002473 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002474 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002475
Douglas Gregorfc516c92009-06-26 23:27:24 +00002476 return false;
2477}
Douglas Gregor9b146582009-07-08 20:55:45 +00002478
2479/// \brief Substitute the explicitly-provided template arguments into the
2480/// given function template according to C++ [temp.arg.explicit].
2481///
2482/// \param FunctionTemplate the function template into which the explicit
2483/// template arguments will be substituted.
2484///
James Dennett634962f2012-06-14 21:40:34 +00002485/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002486/// arguments.
2487///
Mike Stump11289f42009-09-09 15:08:12 +00002488/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002489/// with the converted and checked explicit template arguments.
2490///
Mike Stump11289f42009-09-09 15:08:12 +00002491/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002492/// parameters.
2493///
2494/// \param FunctionType if non-NULL, the result type of the function template
2495/// will also be instantiated and the pointed-to value will be updated with
2496/// the instantiated function type.
2497///
2498/// \param Info if substitution fails for any reason, this object will be
2499/// populated with more information about the failure.
2500///
2501/// \returns TDK_Success if substitution was successful, or some failure
2502/// condition.
2503Sema::TemplateDeductionResult
2504Sema::SubstituteExplicitTemplateArguments(
2505 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002506 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002507 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2508 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002509 QualType *FunctionType,
2510 TemplateDeductionInfo &Info) {
2511 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2512 TemplateParameterList *TemplateParams
2513 = FunctionTemplate->getTemplateParameters();
2514
John McCall6b51f282009-11-23 01:53:49 +00002515 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002516 // No arguments to substitute; just copy over the parameter types and
2517 // fill in the function type.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002518 for (auto P : Function->params())
2519 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002520
Douglas Gregor9b146582009-07-08 20:55:45 +00002521 if (FunctionType)
2522 *FunctionType = Function->getType();
2523 return TDK_Success;
2524 }
Mike Stump11289f42009-09-09 15:08:12 +00002525
Eli Friedman77dcc722012-02-08 03:07:05 +00002526 // Unevaluated SFINAE context.
2527 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002528 SFINAETrap Trap(*this);
2529
Douglas Gregor9b146582009-07-08 20:55:45 +00002530 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002531 // Template arguments that are present shall be specified in the
2532 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002533 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002534 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002535 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002536
2537 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002538 // explicitly-specified template arguments against this function template,
2539 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002540 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002541 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2542 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002543 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2544 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002545 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002546 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002547
Douglas Gregor9b146582009-07-08 20:55:45 +00002548 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002549 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002550 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002551 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002552 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002553 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002554 if (Index >= TemplateParams->size())
2555 Index = TemplateParams->size() - 1;
2556 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002557 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002558 }
Mike Stump11289f42009-09-09 15:08:12 +00002559
Douglas Gregor9b146582009-07-08 20:55:45 +00002560 // Form the template argument list from the explicitly-specified
2561 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002562 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002563 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002564 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002565
John McCall036855a2010-10-12 19:40:14 +00002566 // Template argument deduction and the final substitution should be
2567 // done in the context of the templated declaration. Explicit
2568 // argument substitution, on the other hand, needs to happen in the
2569 // calling context.
2570 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2571
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002572 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002573 // note that the template argument pack is partially substituted and record
2574 // the explicit template arguments. They'll be used as part of deduction
2575 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002576 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2577 const TemplateArgument &Arg = Builder[I];
2578 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002579 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002580 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002581 Arg.pack_begin(),
2582 Arg.pack_size());
2583 break;
2584 }
2585 }
2586
Richard Smith5e580292012-02-10 09:58:53 +00002587 const FunctionProtoType *Proto
2588 = Function->getType()->getAs<FunctionProtoType>();
2589 assert(Proto && "Function template does not have a prototype?");
2590
Douglas Gregor9b146582009-07-08 20:55:45 +00002591 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002592 // explicitly-specified template arguments. If the function has a trailing
2593 // return type, substitute it after the arguments to ensure we substitute
2594 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002595 if (Proto->hasTrailingReturn()) {
2596 if (SubstParmTypes(Function->getLocation(),
2597 Function->param_begin(), Function->getNumParams(),
2598 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2599 ParamTypes))
2600 return TDK_SubstitutionFailure;
2601 }
2602
Richard Smith5e580292012-02-10 09:58:53 +00002603 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002604 QualType ResultType;
2605 {
2606 // C++11 [expr.prim.general]p3:
2607 // If a declaration declares a member function or member function
2608 // template of a class X, the expression this is a prvalue of type
2609 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2610 // and the end of the function-definition, member-declarator, or
2611 // declarator.
2612 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002613 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002614 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2615 ThisContext = Method->getParent();
2616 ThisTypeQuals = Method->getTypeQualifiers();
2617 }
2618
2619 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002620 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002621
2622 ResultType =
2623 SubstType(Proto->getReturnType(),
2624 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2625 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002626 if (ResultType.isNull() || Trap.hasErrorOccurred())
2627 return TDK_SubstitutionFailure;
2628 }
2629
Richard Smith5e580292012-02-10 09:58:53 +00002630 // Instantiate the types of each of the function parameters given the
2631 // explicitly-specified template arguments if we didn't do so earlier.
2632 if (!Proto->hasTrailingReturn() &&
2633 SubstParmTypes(Function->getLocation(),
2634 Function->param_begin(), Function->getNumParams(),
2635 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2636 ParamTypes))
2637 return TDK_SubstitutionFailure;
2638
Douglas Gregor9b146582009-07-08 20:55:45 +00002639 if (FunctionType) {
Jordan Rose5c382722013-03-08 21:51:21 +00002640 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002641 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002642 Function->getDeclName(),
Jordan Rosea0a86be2013-03-08 22:25:36 +00002643 Proto->getExtProtoInfo());
Douglas Gregor9b146582009-07-08 20:55:45 +00002644 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2645 return TDK_SubstitutionFailure;
2646 }
Mike Stump11289f42009-09-09 15:08:12 +00002647
Douglas Gregor9b146582009-07-08 20:55:45 +00002648 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002649 // Trailing template arguments that can be deduced (14.8.2) may be
2650 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002651 // template arguments can be deduced, they may all be omitted; in this
2652 // case, the empty template argument list <> itself may also be omitted.
2653 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002654 // Take all of the explicitly-specified arguments and put them into
2655 // the set of deduced template arguments. Explicitly-specified
2656 // parameter packs, however, will be set to NULL since the deduction
2657 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002658 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002659 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2660 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2661 if (Arg.getKind() == TemplateArgument::Pack)
2662 Deduced.push_back(DeducedTemplateArgument());
2663 else
2664 Deduced.push_back(Arg);
2665 }
Mike Stump11289f42009-09-09 15:08:12 +00002666
Douglas Gregor9b146582009-07-08 20:55:45 +00002667 return TDK_Success;
2668}
2669
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002670/// \brief Check whether the deduced argument type for a call to a function
2671/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2672static bool
2673CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2674 QualType DeducedA) {
2675 ASTContext &Context = S.Context;
2676
2677 QualType A = OriginalArg.OriginalArgType;
2678 QualType OriginalParamType = OriginalArg.OriginalParamType;
2679
2680 // Check for type equality (top-level cv-qualifiers are ignored).
2681 if (Context.hasSameUnqualifiedType(A, DeducedA))
2682 return false;
2683
2684 // Strip off references on the argument types; they aren't needed for
2685 // the following checks.
2686 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2687 DeducedA = DeducedARef->getPointeeType();
2688 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2689 A = ARef->getPointeeType();
2690
2691 // C++ [temp.deduct.call]p4:
2692 // [...] However, there are three cases that allow a difference:
2693 // - If the original P is a reference type, the deduced A (i.e., the
2694 // type referred to by the reference) can be more cv-qualified than
2695 // the transformed A.
2696 if (const ReferenceType *OriginalParamRef
2697 = OriginalParamType->getAs<ReferenceType>()) {
2698 // We don't want to keep the reference around any more.
2699 OriginalParamType = OriginalParamRef->getPointeeType();
2700
2701 Qualifiers AQuals = A.getQualifiers();
2702 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002703
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002704 // Under Objective-C++ ARC, the deduced type may have implicitly
2705 // been given strong or (when dealing with a const reference)
2706 // unsafe_unretained lifetime. If so, update the original
2707 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002708 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002709 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2710 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2711 (DeducedAQuals.hasConst() &&
2712 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2713 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002714 }
2715
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002716 if (AQuals == DeducedAQuals) {
2717 // Qualifiers match; there's nothing to do.
2718 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002719 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002720 } else {
2721 // Qualifiers are compatible, so have the argument type adopt the
2722 // deduced argument type's qualifiers as if we had performed the
2723 // qualification conversion.
2724 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2725 }
2726 }
2727
2728 // - The transformed A can be another pointer or pointer to member
2729 // type that can be converted to the deduced A via a qualification
2730 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002731 //
2732 // Also allow conversions which merely strip [[noreturn]] from function types
2733 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002734 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002735 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002736 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002737 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002738 (S.IsQualificationConversion(A, DeducedA, false,
2739 ObjCLifetimeConversion) ||
2740 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002741 return false;
2742
2743
2744 // - If P is a class and P has the form simple-template-id, then the
2745 // transformed A can be a derived class of the deduced A. [...]
2746 // [...] Likewise, if P is a pointer to a class of the form
2747 // simple-template-id, the transformed A can be a pointer to a
2748 // derived class pointed to by the deduced A.
2749 if (const PointerType *OriginalParamPtr
2750 = OriginalParamType->getAs<PointerType>()) {
2751 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2752 if (const PointerType *APtr = A->getAs<PointerType>()) {
2753 if (A->getPointeeType()->isRecordType()) {
2754 OriginalParamType = OriginalParamPtr->getPointeeType();
2755 DeducedA = DeducedAPtr->getPointeeType();
2756 A = APtr->getPointeeType();
2757 }
2758 }
2759 }
2760 }
2761
2762 if (Context.hasSameUnqualifiedType(A, DeducedA))
2763 return false;
2764
2765 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2766 S.IsDerivedFrom(A, DeducedA))
2767 return false;
2768
2769 return true;
2770}
2771
Mike Stump11289f42009-09-09 15:08:12 +00002772/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002773/// checking the deduced template arguments for completeness and forming
2774/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002775///
2776/// \param OriginalCallArgs If non-NULL, the original call arguments against
2777/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002778Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002779Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002780 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002781 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002782 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002783 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002784 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002785 TemplateParameterList *TemplateParams
2786 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002787
Eli Friedman77dcc722012-02-08 03:07:05 +00002788 // Unevaluated SFINAE context.
2789 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002790 SFINAETrap Trap(*this);
2791
Douglas Gregor9b146582009-07-08 20:55:45 +00002792 // Enter a new template instantiation context while we instantiate the
2793 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002794 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002795 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2796 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002797 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2798 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002799 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002800 return TDK_InstantiationDepth;
2801
John McCalle23b8712010-04-29 01:18:58 +00002802 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002803
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002804 // C++ [temp.deduct.type]p2:
2805 // [...] or if any template argument remains neither deduced nor
2806 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002807 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002808 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2809 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002810
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002811 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002812 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002813 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002815 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002816 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002817 // We may have had explicitly-specified template arguments for a
2818 // template parameter pack (that may or may not have been extended
2819 // via additional deduced arguments).
2820 if (Param->isParameterPack() && CurrentInstantiationScope) {
2821 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2822 Param) {
2823 // Forget the partially-substituted pack; its substitution is now
2824 // complete.
2825 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2826 }
2827 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002828 continue;
2829 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002830 // We have deduced this argument, so it still needs to be
2831 // checked and converted.
2832
2833 // First, for a non-type template parameter type that is
2834 // initialized by a declaration, we need the type of the
2835 // corresponding non-type template parameter.
2836 QualType NTTPType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002837 if (NonTypeTemplateParmDecl *NTTP
2838 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002839 NTTPType = NTTP->getType();
2840 if (NTTPType->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002842 Builder.data(), Builder.size());
2843 NTTPType = SubstType(NTTPType,
2844 MultiLevelTemplateArgumentList(TemplateArgs),
2845 NTTP->getLocation(),
2846 NTTP->getDeclName());
2847 if (NTTPType.isNull()) {
2848 Info.Param = makeTemplateParameter(Param);
2849 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002850 Info.reset(TemplateArgumentList::CreateCopy(Context,
2851 Builder.data(),
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002852 Builder.size()));
2853 return TDK_SubstitutionFailure;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002854 }
2855 }
2856 }
2857
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002858 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002859 FunctionTemplate, NTTPType, 0, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002860 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002861 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002862 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002863 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2864 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002865 return TDK_SubstitutionFailure;
2866 }
2867
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002868 continue;
2869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002870
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002871 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002872 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002873 // be deduced to an empty sequence of template arguments.
2874 // FIXME: Where did the word "trailing" come from?
2875 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002876 // We may have had explicitly-specified template arguments for this
2877 // template parameter pack. If so, our empty deduction extends the
2878 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2879 const TemplateArgument *ExplicitArgs;
2880 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002881 if (CurrentInstantiationScope &&
2882 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002883 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002884 == Param) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002885 Builder.push_back(TemplateArgument(ExplicitArgs, NumExplicitArgs));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002886
Douglas Gregorcaddba92013-01-18 22:27:09 +00002887 // Forget the partially-substituted pack; it's substitution is now
2888 // complete.
2889 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2890 } else {
2891 Builder.push_back(TemplateArgument::getEmptyPack());
2892 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002893 continue;
2894 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002895
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002896 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002897 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002898 TemplateArgumentLoc DefArg
2899 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2900 FunctionTemplate->getLocation(),
2901 FunctionTemplate->getSourceRange().getEnd(),
2902 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002903 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002904
2905 // If there was no default argument, deduction is incomplete.
2906 if (DefArg.getArgument().isNull()) {
2907 Info.Param = makeTemplateParameter(
2908 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002909 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2910 Builder.size()));
2911 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002912 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002914 // Check whether we can actually use the default argument.
2915 if (CheckTemplateArgument(Param, DefArg,
2916 FunctionTemplate,
2917 FunctionTemplate->getLocation(),
2918 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002919 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002920 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002921 Info.Param = makeTemplateParameter(
2922 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002923 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002924 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002925 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002926 return TDK_SubstitutionFailure;
2927 }
2928
2929 // If we get here, we successfully used the default template argument.
2930 }
2931
2932 // Form the template argument list from the deduced template arguments.
2933 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002934 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002935 Info.reset(DeducedArgumentList);
2936
Mike Stump11289f42009-09-09 15:08:12 +00002937 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002938 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002939 DeclContext *Owner = FunctionTemplate->getDeclContext();
2940 if (FunctionTemplate->getFriendObjectKind())
2941 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002942 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002943 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002944 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002945 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002946 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002947
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002949 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950
Mike Stump11289f42009-09-09 15:08:12 +00002951 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002952 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002953 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2954 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002955 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002956
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002957 // There may have been an error that did not prevent us from constructing a
2958 // declaration. Mark the declaration invalid and return with a substitution
2959 // failure.
2960 if (Trap.hasErrorOccurred()) {
2961 Specialization->setInvalidDecl(true);
2962 return TDK_SubstitutionFailure;
2963 }
2964
Douglas Gregore65aacb2011-06-16 16:50:48 +00002965 if (OriginalCallArgs) {
2966 // C++ [temp.deduct.call]p4:
2967 // In general, the deduction process attempts to find template argument
2968 // values that will make the deduced A identical to A (after the type A
2969 // is transformed as described above). [...]
2970 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2971 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002972 unsigned ParamIdx = OriginalArg.ArgIdx;
2973
2974 if (ParamIdx >= Specialization->getNumParams())
2975 continue;
2976
2977 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002978 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA))
2979 return Sema::TDK_SubstitutionFailure;
Douglas Gregore65aacb2011-06-16 16:50:48 +00002980 }
2981 }
2982
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002983 // If we suppressed any diagnostics while performing template argument
2984 // deduction, and if we haven't already instantiated this declaration,
2985 // keep track of these diagnostics. They'll be emitted if this specialization
2986 // is actually used.
2987 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002988 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002989 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2990 if (Pos == SuppressedDiagnostics.end())
2991 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2992 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002993 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002994
Mike Stump11289f42009-09-09 15:08:12 +00002995 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002996}
2997
John McCall8d08b9b2010-08-27 09:08:28 +00002998/// Gets the type of a function for template-argument-deducton
2999/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003000static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003001 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003002 // We may need to deduce the return type of the function now.
Alp Toker314cc812014-01-25 16:55:45 +00003003 if (S.getLangOpts().CPlusPlus1y && Fn->getReturnType()->isUndeducedType() &&
3004 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003005 return QualType();
3006
John McCallc1f69982010-02-02 02:21:27 +00003007 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003008 if (Method->isInstance()) {
3009 // An instance method that's referenced in a form that doesn't
3010 // look like a member pointer is just invalid.
3011 if (!R.HasFormOfMemberPointer) return QualType();
3012
Richard Smith2a7d4812013-05-04 07:00:32 +00003013 return S.Context.getMemberPointerType(Fn->getType(),
3014 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003015 }
3016
3017 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003018 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003019}
3020
3021/// Apply the deduction rules for overload sets.
3022///
3023/// \return the null type if this argument should be treated as an
3024/// undeduced context
3025static QualType
3026ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003027 Expr *Arg, QualType ParamType,
3028 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003029
John McCall8d08b9b2010-08-27 09:08:28 +00003030 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003031
John McCall8d08b9b2010-08-27 09:08:28 +00003032 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003033
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003034 // C++0x [temp.deduct.call]p4
3035 unsigned TDF = 0;
3036 if (ParamWasReference)
3037 TDF |= TDF_ParamWithReferenceType;
3038 if (R.IsAddressOfOperand)
3039 TDF |= TDF_IgnoreQualifiers;
3040
John McCallc1f69982010-02-02 02:21:27 +00003041 // C++0x [temp.deduct.call]p6:
3042 // When P is a function type, pointer to function type, or pointer
3043 // to member function type:
3044
3045 if (!ParamType->isFunctionType() &&
3046 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003047 !ParamType->isMemberFunctionPointerType()) {
3048 if (Ovl->hasExplicitTemplateArgs()) {
3049 // But we can still look for an explicit specialization.
3050 if (FunctionDecl *ExplicitSpec
3051 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003052 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003053 }
John McCallc1f69982010-02-02 02:21:27 +00003054
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003055 return QualType();
3056 }
3057
3058 // Gather the explicit template arguments, if any.
3059 TemplateArgumentListInfo ExplicitTemplateArgs;
3060 if (Ovl->hasExplicitTemplateArgs())
3061 Ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003062 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003063 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3064 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003065 NamedDecl *D = (*I)->getUnderlyingDecl();
3066
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003067 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3068 // - If the argument is an overload set containing one or more
3069 // function templates, the parameter is treated as a
3070 // non-deduced context.
3071 if (!Ovl->hasExplicitTemplateArgs())
3072 return QualType();
3073
3074 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003075 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003076 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003077 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3078 Specialization, Info))
3079 continue;
3080
3081 D = Specialization;
3082 }
John McCallc1f69982010-02-02 02:21:27 +00003083
3084 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003085 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003086 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003087
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003088 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003089 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003090 ArgType->isFunctionType())
3091 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003092
John McCallc1f69982010-02-02 02:21:27 +00003093 // - If the argument is an overload set (not containing function
3094 // templates), trial argument deduction is attempted using each
3095 // of the members of the set. If deduction succeeds for only one
3096 // of the overload set members, that member is used as the
3097 // argument value for the deduction. If deduction succeeds for
3098 // more than one member of the overload set the parameter is
3099 // treated as a non-deduced context.
3100
3101 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3102 // Type deduction is done independently for each P/A pair, and
3103 // the deduced template argument values are then combined.
3104 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003105 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003106 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003107 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003108 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003109 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3110 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003111 if (Result) continue;
3112 if (!Match.isNull()) return QualType();
3113 Match = ArgType;
3114 }
3115
3116 return Match;
3117}
3118
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003119/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003120/// described in C++ [temp.deduct.call].
3121///
3122/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003123/// argument deduction based on this P/A pair because the argument is an
3124/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003125static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3126 TemplateParameterList *TemplateParams,
3127 QualType &ParamType,
3128 QualType &ArgType,
3129 Expr *Arg,
3130 unsigned &TDF) {
3131 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003132 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003133 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003134 if (ParamType.hasQualifiers())
3135 ParamType = ParamType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003136 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3137 if (ParamRefType) {
Richard Smith30482bc2011-02-20 03:19:35 +00003138 QualType PointeeType = ParamRefType->getPointeeType();
3139
Richard Smith8c6eeb92013-01-31 04:03:12 +00003140 // If the argument has incomplete array type, try to complete its type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003141 if (ArgType->isIncompleteArrayType() && !S.RequireCompleteExprType(Arg, 0))
Douglas Gregor57d4f972011-06-03 03:35:07 +00003142 ArgType = Arg->getType();
3143
Douglas Gregorcba72b12011-01-21 05:18:22 +00003144 // [C++0x] If P is an rvalue reference to a cv-unqualified
3145 // template parameter and the argument is an lvalue, the type
3146 // "lvalue reference to A" is used in place of A for type
3147 // deduction.
Richard Smith30482bc2011-02-20 03:19:35 +00003148 if (isa<RValueReferenceType>(ParamType)) {
3149 if (!PointeeType.getQualifiers() &&
3150 isa<TemplateTypeParmType>(PointeeType) &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00003151 Arg->Classify(S.Context).isLValue() &&
3152 Arg->getType() != S.Context.OverloadTy &&
3153 Arg->getType() != S.Context.BoundMemberTy)
Douglas Gregorcba72b12011-01-21 05:18:22 +00003154 ArgType = S.Context.getLValueReferenceType(ArgType);
3155 }
3156
Douglas Gregor7825bf32011-01-06 22:09:01 +00003157 // [...] If P is a reference type, the type referred to by P is used
3158 // for type deduction.
Richard Smith30482bc2011-02-20 03:19:35 +00003159 ParamType = PointeeType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161
Douglas Gregor7825bf32011-01-06 22:09:01 +00003162 // Overload sets usually make this parameter an undeduced
3163 // context, but there are sometimes special circumstances.
3164 if (ArgType == S.Context.OverloadTy) {
3165 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3166 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003167 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003168 if (ArgType.isNull())
3169 return true;
3170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor7825bf32011-01-06 22:09:01 +00003172 if (ParamRefType) {
3173 // C++0x [temp.deduct.call]p3:
3174 // [...] If P is of the form T&&, where T is a template parameter, and
3175 // the argument is an lvalue, the type A& is used in place of A for
3176 // type deduction.
3177 if (ParamRefType->isRValueReferenceType() &&
3178 ParamRefType->getAs<TemplateTypeParmType>() &&
3179 Arg->isLValue())
3180 ArgType = S.Context.getLValueReferenceType(ArgType);
3181 } else {
3182 // C++ [temp.deduct.call]p2:
3183 // If P is not a reference type:
3184 // - If A is an array type, the pointer type produced by the
3185 // array-to-pointer standard conversion (4.2) is used in place of
3186 // A for type deduction; otherwise,
3187 if (ArgType->isArrayType())
3188 ArgType = S.Context.getArrayDecayedType(ArgType);
3189 // - If A is a function type, the pointer type produced by the
3190 // function-to-pointer standard conversion (4.3) is used in place
3191 // of A for type deduction; otherwise,
3192 else if (ArgType->isFunctionType())
3193 ArgType = S.Context.getPointerType(ArgType);
3194 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003195 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003196 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003197 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003198 }
3199 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200
Douglas Gregor7825bf32011-01-06 22:09:01 +00003201 // C++0x [temp.deduct.call]p4:
3202 // In general, the deduction process attempts to find template argument
3203 // values that will make the deduced A identical to A (after the type A
3204 // is transformed as described above). [...]
3205 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206
Douglas Gregor7825bf32011-01-06 22:09:01 +00003207 // - If the original P is a reference type, the deduced A (i.e., the
3208 // type referred to by the reference) can be more cv-qualified than
3209 // the transformed A.
3210 if (ParamRefType)
3211 TDF |= TDF_ParamWithReferenceType;
3212 // - The transformed A can be another pointer or pointer to member
3213 // type that can be converted to the deduced A via a qualification
3214 // conversion (4.4).
3215 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3216 ArgType->isObjCObjectPointerType())
3217 TDF |= TDF_IgnoreQualifiers;
3218 // - If P is a class and P has the form simple-template-id, then the
3219 // transformed A can be a derived class of the deduced A. Likewise,
3220 // if P is a pointer to a class of the form simple-template-id, the
3221 // transformed A can be a pointer to a derived class pointed to by
3222 // the deduced A.
3223 if (isSimpleTemplateIdType(ParamType) ||
3224 (isa<PointerType>(ParamType) &&
3225 isSimpleTemplateIdType(
3226 ParamType->getAs<PointerType>()->getPointeeType())))
3227 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003228
Douglas Gregor7825bf32011-01-06 22:09:01 +00003229 return false;
3230}
3231
Douglas Gregore65aacb2011-06-16 16:50:48 +00003232static bool hasDeducibleTemplateParameters(Sema &S,
3233 FunctionTemplateDecl *FunctionTemplate,
3234 QualType T);
3235
Sebastian Redl19181662012-03-15 21:40:51 +00003236/// \brief Perform template argument deduction by matching a parameter type
3237/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003238/// an initializer list that was originally matched against a parameter
3239/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003240static Sema::TemplateDeductionResult
3241DeduceTemplateArgumentByListElement(Sema &S,
3242 TemplateParameterList *TemplateParams,
3243 QualType ParamType, Expr *Arg,
3244 TemplateDeductionInfo &Info,
3245 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3246 unsigned TDF) {
3247 // Handle the case where an init list contains another init list as the
3248 // element.
3249 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3250 QualType X;
3251 if (!S.isStdInitializerList(ParamType.getNonReferenceType(), &X))
3252 return Sema::TDK_Success; // Just ignore this expression.
3253
3254 // Recurse down into the init list.
3255 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3256 if (Sema::TemplateDeductionResult Result =
3257 DeduceTemplateArgumentByListElement(S, TemplateParams, X,
3258 ILE->getInit(i),
3259 Info, Deduced, TDF))
3260 return Result;
3261 }
3262 return Sema::TDK_Success;
3263 }
3264
3265 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003266 QualType ArgType = Arg->getType();
3267 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003268 ArgType, Arg, TDF)) {
3269 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003270 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003271 }
Sebastian Redl19181662012-03-15 21:40:51 +00003272 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003273 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003274}
3275
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003276/// \brief Perform template argument deduction from a function call
3277/// (C++ [temp.deduct.call]).
3278///
3279/// \param FunctionTemplate the function template for which we are performing
3280/// template argument deduction.
3281///
James Dennett18348b62012-06-22 08:52:37 +00003282/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003283/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003284///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003285/// \param Args the function call arguments
3286///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003287/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003288/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003289/// template argument deduction.
3290///
3291/// \param Info the argument will be updated to provide additional information
3292/// about template argument deduction.
3293///
3294/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003295Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3296 FunctionTemplateDecl *FunctionTemplate,
3297 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3298 FunctionDecl *&Specialization, TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003299 if (FunctionTemplate->isInvalidDecl())
3300 return TDK_Invalid;
3301
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003302 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Douglas Gregor89026b52009-06-30 23:57:56 +00003303
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003304 // C++ [temp.deduct.call]p1:
3305 // Template argument deduction is done by comparing each function template
3306 // parameter type (call it P) with the type of the corresponding argument
3307 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003308 unsigned CheckArgs = Args.size();
3309 if (Args.size() < Function->getMinRequiredArguments())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003310 return TDK_TooFewArguments;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003311 else if (Args.size() > Function->getNumParams()) {
Mike Stump11289f42009-09-09 15:08:12 +00003312 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003313 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003314 if (Proto->isTemplateVariadic())
3315 /* Do nothing */;
3316 else if (Proto->isVariadic())
3317 CheckArgs = Function->getNumParams();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003319 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003320 }
Mike Stump11289f42009-09-09 15:08:12 +00003321
Douglas Gregor89026b52009-06-30 23:57:56 +00003322 // The types of the parameters from which we will perform template argument
3323 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003324 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003325 TemplateParameterList *TemplateParams
3326 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003327 SmallVector<DeducedTemplateArgument, 4> Deduced;
3328 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003329 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003330 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003331 TemplateDeductionResult Result =
3332 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003333 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003334 Deduced,
3335 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003336 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003337 Info);
3338 if (Result)
3339 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003340
3341 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003342 } else {
3343 // Just fill in the parameter types from the function declaration.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003344 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003345 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3346 }
Mike Stump11289f42009-09-09 15:08:12 +00003347
Douglas Gregor89026b52009-06-30 23:57:56 +00003348 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003349 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003350 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003351 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352 for (unsigned ParamIdx = 0, NumParams = ParamTypes.size();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003353 ParamIdx != NumParams; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003354 QualType OrigParamType = ParamTypes[ParamIdx];
3355 QualType ParamType = OrigParamType;
3356
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003358 = dyn_cast<PackExpansionType>(ParamType);
3359 if (!ParamExpansion) {
3360 // Simple case: matching a function parameter to a function argument.
3361 if (ArgIdx >= CheckArgs)
3362 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003363
Douglas Gregor7825bf32011-01-06 22:09:01 +00003364 Expr *Arg = Args[ArgIdx++];
3365 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003366
Douglas Gregor7825bf32011-01-06 22:09:01 +00003367 unsigned TDF = 0;
3368 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3369 ParamType, ArgType, Arg,
3370 TDF))
3371 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003372
Douglas Gregor0c83c812011-10-09 22:06:46 +00003373 // If we have nothing to deduce, we're done.
3374 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3375 continue;
3376
Sebastian Redl43144e72012-01-17 22:49:58 +00003377 // If the argument is an initializer list ...
3378 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3379 // ... then the parameter is an undeduced context, unless the parameter
3380 // type is (reference to cv) std::initializer_list<P'>, in which case
3381 // deduction is done for each element of the initializer list, and the
3382 // result is the deduced type if it's the same for all elements.
3383 QualType X;
3384 // Removing references was already done.
3385 if (!isStdInitializerList(ParamType, &X))
3386 continue;
3387
3388 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3389 if (TemplateDeductionResult Result =
Sebastian Redl19181662012-03-15 21:40:51 +00003390 DeduceTemplateArgumentByListElement(*this, TemplateParams, X,
3391 ILE->getInit(i),
3392 Info, Deduced, TDF))
Sebastian Redl43144e72012-01-17 22:49:58 +00003393 return Result;
3394 }
3395 // Don't track the argument type, since an initializer list has none.
3396 continue;
3397 }
3398
Douglas Gregore65aacb2011-06-16 16:50:48 +00003399 // Keep track of the argument type and corresponding parameter index,
3400 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003401 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3402 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003403
Douglas Gregor7825bf32011-01-06 22:09:01 +00003404 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003405 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3406 ParamType, ArgType,
3407 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003408 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003409
Douglas Gregor7825bf32011-01-06 22:09:01 +00003410 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412
Douglas Gregor7825bf32011-01-06 22:09:01 +00003413 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414 // For a function parameter pack that occurs at the end of the
3415 // parameter-declaration-list, the type A of each remaining argument of
3416 // the call is compared with the type P of the declarator-id of the
3417 // function parameter pack. Each comparison deduces template arguments
3418 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003419 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003421 // the parameter pack is a non-deduced context.
3422 if (ParamIdx + 1 < NumParams)
3423 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003424
Douglas Gregor7825bf32011-01-06 22:09:01 +00003425 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003426 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3427 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428
Douglas Gregor7825bf32011-01-06 22:09:01 +00003429 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003430 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003431 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432
Douglas Gregore65aacb2011-06-16 16:50:48 +00003433 QualType OrigParamType = ParamPattern;
3434 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003435 Expr *Arg = Args[ArgIdx];
3436 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003437
Douglas Gregor7825bf32011-01-06 22:09:01 +00003438 unsigned TDF = 0;
3439 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3440 ParamType, ArgType, Arg,
3441 TDF)) {
3442 // We can't actually perform any deduction for this argument, so stop
3443 // deduction at this point.
3444 ++ArgIdx;
3445 break;
3446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447
Sebastian Redl43144e72012-01-17 22:49:58 +00003448 // As above, initializer lists need special handling.
3449 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3450 QualType X;
3451 if (!isStdInitializerList(ParamType, &X)) {
3452 ++ArgIdx;
3453 break;
3454 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003455
Sebastian Redl43144e72012-01-17 22:49:58 +00003456 for (unsigned i = 0, e = ILE->getNumInits(); i < e; ++i) {
3457 if (TemplateDeductionResult Result =
3458 DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams, X,
3459 ILE->getInit(i)->getType(),
3460 Info, Deduced, TDF))
3461 return Result;
3462 }
3463 } else {
3464
3465 // Keep track of the argument type and corresponding argument index,
3466 // so we can check for compatibility between the deduced A and A.
3467 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3468 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3469 ArgType));
3470
3471 if (TemplateDeductionResult Result
3472 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3473 ParamType, ArgType, Info,
3474 Deduced, TDF))
3475 return Result;
3476 }
Mike Stump11289f42009-09-09 15:08:12 +00003477
Richard Smith0a80d572014-05-29 01:12:14 +00003478 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480
Douglas Gregor7825bf32011-01-06 22:09:01 +00003481 // Build argument packs for each of the parameter packs expanded by this
3482 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003483 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003485
Douglas Gregor7825bf32011-01-06 22:09:01 +00003486 // After we've matching against a parameter pack, we're done.
3487 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003488 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003489
Mike Stump11289f42009-09-09 15:08:12 +00003490 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003491 NumExplicitlySpecified,
Douglas Gregore65aacb2011-06-16 16:50:48 +00003492 Specialization, Info, &OriginalCallArgs);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003493}
3494
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003495QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3496 QualType FunctionType) {
3497 if (ArgFunctionType.isNull())
3498 return ArgFunctionType;
3499
3500 const FunctionProtoType *FunctionTypeP =
3501 FunctionType->castAs<FunctionProtoType>();
3502 CallingConv CC = FunctionTypeP->getCallConv();
3503 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3504 const FunctionProtoType *ArgFunctionTypeP =
3505 ArgFunctionType->getAs<FunctionProtoType>();
3506 if (ArgFunctionTypeP->getCallConv() == CC &&
3507 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3508 return ArgFunctionType;
3509
3510 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3511 EI = EI.withNoReturn(NoReturn);
3512 ArgFunctionTypeP =
3513 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3514 return QualType(ArgFunctionTypeP, 0);
3515}
3516
Douglas Gregor9b146582009-07-08 20:55:45 +00003517/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003518/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3519/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003520///
3521/// \param FunctionTemplate the function template for which we are performing
3522/// template argument deduction.
3523///
James Dennett18348b62012-06-22 08:52:37 +00003524/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003525/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003526///
3527/// \param ArgFunctionType the function type that will be used as the
3528/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003529/// function template's function type. This type may be NULL, if there is no
3530/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003531///
3532/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003533/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003534/// template argument deduction.
3535///
3536/// \param Info the argument will be updated to provide additional information
3537/// about template argument deduction.
3538///
3539/// \returns the result of template argument deduction.
3540Sema::TemplateDeductionResult
3541Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003542 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003543 QualType ArgFunctionType,
3544 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003545 TemplateDeductionInfo &Info,
3546 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003547 if (FunctionTemplate->isInvalidDecl())
3548 return TDK_Invalid;
3549
Douglas Gregor9b146582009-07-08 20:55:45 +00003550 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3551 TemplateParameterList *TemplateParams
3552 = FunctionTemplate->getTemplateParameters();
3553 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003554 if (!InOverloadResolution)
3555 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003556
Douglas Gregor9b146582009-07-08 20:55:45 +00003557 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003558 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003559 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003560 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003561 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003562 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003563 if (TemplateDeductionResult Result
3564 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003565 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003566 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003567 &FunctionType, Info))
3568 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003569
3570 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003571 }
3572
Eli Friedman77dcc722012-02-08 03:07:05 +00003573 // Unevaluated SFINAE context.
3574 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003575 SFINAETrap Trap(*this);
3576
John McCallc1f69982010-02-02 02:21:27 +00003577 Deduced.resize(TemplateParams->size());
3578
Richard Smith2a7d4812013-05-04 07:00:32 +00003579 // If the function has a deduced return type, substitute it for a dependent
3580 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003581 bool HasDeducedReturnType = false;
Richard Smith2a7d4812013-05-04 07:00:32 +00003582 if (getLangOpts().CPlusPlus1y && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003583 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003584 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003585 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003586 }
3587
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003588 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003589 unsigned TDF = TDF_TopLevelParameterTypeList;
3590 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003591 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003592 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003593 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003594 FunctionType, ArgFunctionType,
3595 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003596 return Result;
3597 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003598
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003599 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003600 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3601 NumExplicitlySpecified,
3602 Specialization, Info))
3603 return Result;
3604
Richard Smith2a7d4812013-05-04 07:00:32 +00003605 // If the function has a deduced return type, deduce it now, so we can check
3606 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003607 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003608 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003609 DeduceReturnType(Specialization, Info.getLocation(), false))
3610 return TDK_MiscellaneousDeductionFailure;
3611
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003612 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003613 // specialization with respect to arguments of compatible pointer to function
3614 // types, template argument deduction fails.
3615 if (!ArgFunctionType.isNull()) {
3616 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3617 Context.getCanonicalType(Specialization->getType()),
3618 Context.getCanonicalType(ArgFunctionType)))
3619 return TDK_MiscellaneousDeductionFailure;
3620 else if(!InOverloadResolution &&
3621 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3622 return TDK_MiscellaneousDeductionFailure;
3623 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003624
3625 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003626}
3627
Faisal Vali850da1a2013-09-29 17:08:32 +00003628/// \brief Given a function declaration (e.g. a generic lambda conversion
3629/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003630/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3631/// to replace 'auto' with and not the actual result type you want
3632/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003633static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003634SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003635 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003636 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003637 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003638 assert(AutoResultType->getContainedAutoType());
3639 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003640 TypeToReplaceAutoWith);
3641 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3642}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003643
3644/// \brief Given a specialized conversion operator of a generic lambda
3645/// create the corresponding specializations of the call operator and
3646/// the static-invoker. If the return type of the call operator is auto,
3647/// deduce its return type and check if that matches the
3648/// return type of the destination function ptr.
3649
3650static inline Sema::TemplateDeductionResult
3651SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3652 CXXConversionDecl *ConversionSpecialized,
3653 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3654 QualType ReturnTypeOfDestFunctionPtr,
3655 TemplateDeductionInfo &TDInfo,
3656 Sema &S) {
3657
3658 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3659 assert(LambdaClass && LambdaClass->isGenericLambda());
3660
3661 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003662 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003663 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3664 CallOpResultType->getContainedAutoType();
3665
3666 FunctionTemplateDecl *CallOpTemplate =
3667 CallOpGeneric->getDescribedFunctionTemplate();
3668
Craig Topperc3ec1492014-05-26 06:22:03 +00003669 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003670 // Use the deduced arguments of the conversion function, to specialize our
3671 // generic lambda's call operator.
3672 if (Sema::TemplateDeductionResult Result
3673 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3674 DeducedArguments,
3675 0, CallOpSpecialized, TDInfo))
3676 return Result;
3677
3678 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003679 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3680 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003681 S.DeduceReturnType(CallOpSpecialized,
3682 CallOpSpecialized->getPointOfInstantiation(),
3683 /*Diagnose*/ true);
3684
3685 // Check to see if the return type of the destination ptr-to-function
3686 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003687 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003688 ReturnTypeOfDestFunctionPtr))
3689 return Sema::TDK_NonDeducedMismatch;
3690 // Since we have succeeded in matching the source and destination
3691 // ptr-to-functions (now including return type), and have successfully
3692 // specialized our corresponding call operator, we are ready to
3693 // specialize the static invoker with the deduced arguments of our
3694 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003695 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003696 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3697 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3698
3699 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result
3700 = S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3701 InvokerSpecialized, TDInfo);
3702 assert(Result == Sema::TDK_Success &&
3703 "If the call operator succeeded so should the invoker!");
3704 // Set the result type to match the corresponding call operator
3705 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003706 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3707 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003708 // Be sure to get the type to replace 'auto' with and not
3709 // the full result type of the call op specialization
3710 // to substitute into the 'auto' of the invoker and conversion
3711 // function.
3712 // For e.g.
3713 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3714 // We don't want to subst 'int*' into 'auto' to get int**.
3715
Alp Toker314cc812014-01-25 16:55:45 +00003716 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3717 ->getContainedAutoType()
3718 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003719 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3720 TypeToReplaceAutoWith, S);
3721 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3722 TypeToReplaceAutoWith, S);
3723 }
3724
3725 // Ensure that static invoker doesn't have a const qualifier.
3726 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3727 // do not use the CallOperator's TypeSourceInfo which allows
3728 // the const qualifier to leak through.
3729 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3730 getType().getTypePtr()->castAs<FunctionProtoType>();
3731 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3732 EPI.TypeQuals = 0;
3733 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003734 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003735 return Sema::TDK_Success;
3736}
Douglas Gregor05155d82009-08-21 23:19:43 +00003737/// \brief Deduce template arguments for a templated conversion
3738/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3739/// conversion function template specialization.
3740Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003741Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003742 QualType ToType,
3743 CXXConversionDecl *&Specialization,
3744 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003745 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003746 return TDK_Invalid;
3747
Faisal Vali2b3a3012013-10-24 23:40:02 +00003748 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003749 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3750
Faisal Vali2b3a3012013-10-24 23:40:02 +00003751 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003752
3753 // Canonicalize the types for deduction.
3754 QualType P = Context.getCanonicalType(FromType);
3755 QualType A = Context.getCanonicalType(ToType);
3756
Douglas Gregord99609a2011-03-06 09:03:20 +00003757 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003758 // If P is a reference type, the type referred to by P is used for
3759 // type deduction.
3760 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3761 P = PRef->getPointeeType();
3762
Douglas Gregord99609a2011-03-06 09:03:20 +00003763 // C++0x [temp.deduct.conv]p4:
3764 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003765 // for type deduction.
3766 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003767 A = ARef->getPointeeType().getUnqualifiedType();
3768 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003769 //
Mike Stump11289f42009-09-09 15:08:12 +00003770 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003771 else {
3772 assert(!A->isReferenceType() && "Reference types were handled above");
3773
3774 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003775 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003776 // of P for type deduction; otherwise,
3777 if (P->isArrayType())
3778 P = Context.getArrayDecayedType(P);
3779 // - If P is a function type, the pointer type produced by the
3780 // function-to-pointer standard conversion (4.3) is used in
3781 // place of P for type deduction; otherwise,
3782 else if (P->isFunctionType())
3783 P = Context.getPointerType(P);
3784 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003785 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003786 else
3787 P = P.getUnqualifiedType();
3788
Douglas Gregord99609a2011-03-06 09:03:20 +00003789 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003790 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregord99609a2011-03-06 09:03:20 +00003791 // type are ignored for type deduction. If A is a reference type, the type
3792 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003793 A = A.getUnqualifiedType();
3794 }
3795
Eli Friedman77dcc722012-02-08 03:07:05 +00003796 // Unevaluated SFINAE context.
3797 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003798 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003799
3800 // C++ [temp.deduct.conv]p1:
3801 // Template argument deduction is done by comparing the return
3802 // type of the template conversion function (call it P) with the
3803 // type that is required as the result of the conversion (call it
3804 // A) as described in 14.8.2.4.
3805 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003806 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003807 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003808 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003809
3810 // C++0x [temp.deduct.conv]p4:
3811 // In general, the deduction process attempts to find template
3812 // argument values that will make the deduced A identical to
3813 // A. However, there are two cases that allow a difference:
3814 unsigned TDF = 0;
3815 // - If the original A is a reference type, A can be more
3816 // cv-qualified than the deduced A (i.e., the type referred to
3817 // by the reference)
3818 if (ToType->isReferenceType())
3819 TDF |= TDF_ParamWithReferenceType;
3820 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003821 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003822 // conversion.
3823 //
3824 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3825 // both P and A are pointers or member pointers. In this case, we
3826 // just ignore cv-qualifiers completely).
3827 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003828 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003829 TDF |= TDF_IgnoreQualifiers;
3830 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003831 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3832 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003833 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003834
3835 // Create an Instantiation Scope for finalizing the operator.
3836 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003837 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003838 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003839 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003840 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3841 ConversionSpecialized, Info);
3842 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3843
3844 // If the conversion operator is being invoked on a lambda closure to convert
3845 // to a ptr-to-function, use the deduced arguments from the conversion function
3846 // to specialize the corresponding call operator.
3847 // e.g., int (*fp)(int) = [](auto a) { return a; };
3848 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3849
3850 // Get the return type of the destination ptr-to-function we are converting
3851 // to. This is necessary for matching the lambda call operator's return
3852 // type to that of the destination ptr-to-function's return type.
3853 assert(A->isPointerType() &&
3854 "Can only convert from lambda to ptr-to-function");
3855 const FunctionType *ToFunType =
3856 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003857 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3858
Faisal Vali2b3a3012013-10-24 23:40:02 +00003859 // Create the corresponding specializations of the call operator and
3860 // the static-invoker; and if the return type is auto,
3861 // deduce the return type and check if it matches the
3862 // DestFunctionPtrReturnType.
3863 // For instance:
3864 // auto L = [](auto a) { return f(a); };
3865 // int (*fp)(int) = L;
3866 // char (*fp2)(int) = L; <-- Not OK.
3867
3868 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3869 Specialization, Deduced, DestFunctionPtrReturnType,
3870 Info, *this);
3871 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003872 return Result;
3873}
3874
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003875/// \brief Deduce template arguments for a function template when there is
3876/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3877///
3878/// \param FunctionTemplate the function template for which we are performing
3879/// template argument deduction.
3880///
James Dennett18348b62012-06-22 08:52:37 +00003881/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003882/// arguments.
3883///
3884/// \param Specialization if template argument deduction was successful,
3885/// this will be set to the function template specialization produced by
3886/// template argument deduction.
3887///
3888/// \param Info the argument will be updated to provide additional information
3889/// about template argument deduction.
3890///
3891/// \returns the result of template argument deduction.
3892Sema::TemplateDeductionResult
3893Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003894 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003895 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003896 TemplateDeductionInfo &Info,
3897 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003898 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003899 QualType(), Specialization, Info,
3900 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003901}
3902
Richard Smith30482bc2011-02-20 03:19:35 +00003903namespace {
3904 /// Substitute the 'auto' type specifier within a type for a given replacement
3905 /// type.
3906 class SubstituteAutoTransform :
3907 public TreeTransform<SubstituteAutoTransform> {
3908 QualType Replacement;
3909 public:
3910 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement) :
3911 TreeTransform<SubstituteAutoTransform>(SemaRef), Replacement(Replacement) {
3912 }
3913 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3914 // If we're building the type pattern to deduce against, don't wrap the
3915 // substituted type in an AutoType. Certain template deduction rules
3916 // apply only when a template type parameter appears directly (and not if
3917 // the parameter is found through desugaring). For instance:
3918 // auto &&lref = lvalue;
3919 // must transform into "rvalue reference to T" not "rvalue reference to
3920 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003921 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003922 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003923 TemplateTypeParmTypeLoc NewTL =
3924 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003925 NewTL.setNameLoc(TL.getNameLoc());
3926 return Result;
3927 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003928 bool Dependent =
3929 !Replacement.isNull() && Replacement->isDependentType();
3930 QualType Result =
3931 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3932 TL.getTypePtr()->isDecltypeAuto(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003933 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003934 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3935 NewTL.setNameLoc(TL.getNameLoc());
3936 return Result;
3937 }
3938 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003939
3940 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3941 // Lambdas never need to be transformed.
3942 return E;
3943 }
Richard Smith061f1e22013-04-30 21:23:01 +00003944
Richard Smith2a7d4812013-05-04 07:00:32 +00003945 QualType Apply(TypeLoc TL) {
3946 // Create some scratch storage for the transformed type locations.
3947 // FIXME: We're just going to throw this information away. Don't build it.
3948 TypeLocBuilder TLB;
3949 TLB.reserve(TL.getFullDataSize());
3950 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003951 }
Richard Smith30482bc2011-02-20 03:19:35 +00003952 };
3953}
3954
Richard Smith2a7d4812013-05-04 07:00:32 +00003955Sema::DeduceAutoResult
3956Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3957 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3958}
3959
Richard Smith061f1e22013-04-30 21:23:01 +00003960/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003961///
3962/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003963/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003964/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003965/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003966Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003967Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003968 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003969 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3970 if (NonPlaceholder.isInvalid())
3971 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003972 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003973 }
3974
Richard Smith2a7d4812013-05-04 07:00:32 +00003975 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003976 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003977 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003978 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00003979 }
3980
Richard Smith74aeef52013-04-26 16:15:35 +00003981 // If this is a 'decltype(auto)' specifier, do the decltype dance.
3982 // Since 'decltype(auto)' can only occur at the top of the type, we
3983 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00003984 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00003985 if (AT->isDecltypeAuto()) {
3986 if (isa<InitListExpr>(Init)) {
3987 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
3988 return DAR_FailedAlreadyDiagnosed;
3989 }
3990
3991 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart());
3992 // FIXME: Support a non-canonical deduced type for 'auto'.
3993 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00003994 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003995 if (Result.isNull())
3996 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00003997 return DAR_Succeeded;
3998 }
3999 }
4000
Richard Smith30482bc2011-02-20 03:19:35 +00004001 SourceLocation Loc = Init->getExprLoc();
4002
4003 LocalInstantiationScope InstScope(*this);
4004
4005 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004006 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004007 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4008 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004009 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4010 NamedDecl *TemplParamPtr = TemplParam;
Richard Smithb2bc2e62011-02-21 20:05:19 +00004011 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
4012 Loc);
4013
Richard Smith061f1e22013-04-30 21:23:01 +00004014 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4015 assert(!FuncParam.isNull() &&
4016 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004017
4018 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004019 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004020 Deduced.resize(1);
4021 QualType InitType = Init->getType();
4022 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004023
Craig Toppere6706e42012-09-19 02:26:47 +00004024 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004025
Richard Smith74801c82012-07-08 04:13:07 +00004026 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004027 if (InitList) {
4028 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith74801c82012-07-08 04:13:07 +00004029 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004030 TemplArg,
4031 InitList->getInit(i),
4032 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004033 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004034 }
4035 } else {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004036 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
4037 FuncParam, InitType, Init,
4038 TDF))
4039 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004040
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004041 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
4042 InitType, Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004043 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004044 }
Richard Smith30482bc2011-02-20 03:19:35 +00004045
Eli Friedmane4310952012-11-06 23:56:42 +00004046 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004047 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004048
Eli Friedmane4310952012-11-06 23:56:42 +00004049 QualType DeducedType = Deduced[0].getAsType();
4050
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004051 if (InitList) {
4052 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4053 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004054 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004055 }
4056
Richard Smith061f1e22013-04-30 21:23:01 +00004057 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004058 if (Result.isNull())
4059 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004060
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004061 // Check that the deduced argument type is compatible with the original
4062 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004063 if (!InitList && !Result.isNull() &&
4064 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004065 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004066 Result)) {
4067 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004068 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004069 }
4070
Sebastian Redl09edce02012-01-23 22:09:39 +00004071 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004072}
4073
Faisal Vali2b391ab2013-09-26 19:54:12 +00004074QualType Sema::SubstAutoType(QualType TypeWithAuto,
4075 QualType TypeToReplaceAuto) {
4076 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4077 TransformType(TypeWithAuto);
4078}
4079
4080TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4081 QualType TypeToReplaceAuto) {
4082 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4083 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004084}
4085
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004086void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4087 if (isa<InitListExpr>(Init))
4088 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004089 VDecl->isInitCapture()
4090 ? diag::err_init_capture_deduction_failure_from_init_list
4091 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004092 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4093 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004094 Diag(VDecl->getLocation(),
4095 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4096 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004097 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4098 << Init->getSourceRange();
4099}
4100
Richard Smith2a7d4812013-05-04 07:00:32 +00004101bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4102 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004103 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004104
4105 if (FD->getTemplateInstantiationPattern())
4106 InstantiateFunctionDefinition(Loc, FD);
4107
Alp Toker314cc812014-01-25 16:55:45 +00004108 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004109 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4110 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4111 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4112 }
4113
4114 return StillUndeduced;
4115}
4116
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004117static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004118MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004119 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004120 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004121 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004122
4123/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004124static void
4125AddImplicitObjectParameterType(ASTContext &Context,
4126 CXXMethodDecl *Method,
4127 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004128 // C++11 [temp.func.order]p3:
4129 // [...] The new parameter is of type "reference to cv A," where cv are
4130 // the cv-qualifiers of the function template (if any) and A is
4131 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004132 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004133 // The standard doesn't say explicitly, but we pick the appropriate kind of
4134 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004135 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4136 ArgTy = Context.getQualifiedType(ArgTy,
4137 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004138 if (Method->getRefQualifier() == RQ_RValue)
4139 ArgTy = Context.getRValueReferenceType(ArgTy);
4140 else
4141 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004142 ArgTypes.push_back(ArgTy);
4143}
4144
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004145/// \brief Determine whether the function template \p FT1 is at least as
4146/// specialized as \p FT2.
4147static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004148 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004149 FunctionTemplateDecl *FT1,
4150 FunctionTemplateDecl *FT2,
4151 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004152 unsigned NumCallArguments1,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004153 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004154 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004155 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004156 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4157 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004158
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004159 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4160 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004161 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004162 Deduced.resize(TemplateParams->size());
4163
4164 // C++0x [temp.deduct.partial]p3:
4165 // The types used to determine the ordering depend on the context in which
4166 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004167 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004168 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004169 switch (TPOC) {
4170 case TPOC_Call: {
4171 // - In the context of a function call, the function parameter types are
4172 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004173 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4174 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004175
Eli Friedman3b5774a2012-09-19 23:27:04 +00004176 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004177 // [...] If only one of the function templates is a non-static
4178 // member, that function template is considered to have a new
4179 // first parameter inserted in its function parameter list. The
4180 // new parameter is of type "reference to cv A," where cv are
4181 // the cv-qualifiers of the function template (if any) and A is
4182 // the class of which the function template is a member.
4183 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004184 // Note that we interpret this to mean "if one of the function
4185 // templates is a non-static member and the other is a non-member";
4186 // otherwise, the ordering rules for static functions against non-static
4187 // functions don't make any sense.
4188 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004189 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4190 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004191 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004192
Richard Smithe5b52202013-09-11 00:52:39 +00004193 unsigned NumComparedArguments = NumCallArguments1;
4194
4195 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004196 // Compare 'this' from Method1 against first parameter from Method2.
4197 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4198 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004199 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004200 // Compare 'this' from Method2 against first parameter from Method1.
4201 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004202 }
4203
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004204 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004205 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004206 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004207 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208
Douglas Gregorb837ea42011-01-11 17:34:58 +00004209 // C++ [temp.func.order]p5:
4210 // The presence of unused ellipsis and default arguments has no effect on
4211 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004212 if (Args1.size() > NumComparedArguments)
4213 Args1.resize(NumComparedArguments);
4214 if (Args2.size() > NumComparedArguments)
4215 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004216 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4217 Args1.data(), Args1.size(), Info, Deduced,
4218 TDF_None, /*PartialOrdering=*/true,
Douglas Gregor63814022011-01-21 17:29:42 +00004219 RefParamComparisons))
Richard Smith0a80d572014-05-29 01:12:14 +00004220 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004221
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004222 break;
4223 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004224
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004225 case TPOC_Conversion:
4226 // - In the context of a call to a conversion operator, the return types
4227 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004228 if (DeduceTemplateArgumentsByTypeMatch(
4229 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4230 Info, Deduced, TDF_None,
4231 /*PartialOrdering=*/true, RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004232 return false;
4233 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004234
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004235 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004236 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004237 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004238 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4239 FD2->getType(), FD1->getType(),
4240 Info, Deduced, TDF_None,
4241 /*PartialOrdering=*/true,
4242 RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004243 return false;
4244 break;
4245 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004246
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004247 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004248 // In most cases, all template parameters must have values in order for
4249 // deduction to succeed, but for partial ordering purposes a template
4250 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004251 // types being used for partial ordering. [ Note: a template parameter used
4252 // in a non-deduced context is considered used. -end note]
4253 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4254 for (; ArgIdx != NumArgs; ++ArgIdx)
4255 if (Deduced[ArgIdx].isNull())
4256 break;
4257
4258 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004260 // as FT2.
4261 return true;
4262 }
4263
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004264 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004265 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004266 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004267 case TPOC_Call:
4268 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4269 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004270 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004271 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004272 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004274 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004275 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4276 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004277 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004279 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004280 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004281 TemplateParams->getDepth(),
4282 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004283 break;
4284 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004286 for (; ArgIdx != NumArgs; ++ArgIdx)
4287 // If this argument had no value deduced but was used in one of the types
4288 // used for partial ordering, then deduction fails.
4289 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4290 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004292 return true;
4293}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
Douglas Gregorcef1a032011-01-16 16:03:23 +00004295/// \brief Determine whether this a function template whose parameter-type-list
4296/// ends with a function parameter pack.
4297static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4298 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4299 unsigned NumParams = Function->getNumParams();
4300 if (NumParams == 0)
4301 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
Douglas Gregorcef1a032011-01-16 16:03:23 +00004303 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4304 if (!Last->isParameterPack())
4305 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregorcef1a032011-01-16 16:03:23 +00004307 // Make sure that no previous parameter is a parameter pack.
4308 while (--NumParams > 0) {
4309 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4310 return false;
4311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312
Douglas Gregorcef1a032011-01-16 16:03:23 +00004313 return true;
4314}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315
Douglas Gregorbe999392009-09-15 16:23:51 +00004316/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004317/// to the rules of function template partial ordering (C++ [temp.func.order]).
4318///
4319/// \param FT1 the first function template
4320///
4321/// \param FT2 the second function template
4322///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004323/// \param TPOC the context in which we are performing partial ordering of
4324/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004325///
Richard Smithe5b52202013-09-11 00:52:39 +00004326/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4327/// only when \c TPOC is \c TPOC_Call.
4328///
4329/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4330/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004331///
Douglas Gregorbe999392009-09-15 16:23:51 +00004332/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004333/// template is more specialized, returns NULL.
4334FunctionTemplateDecl *
4335Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4336 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004337 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004338 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004339 unsigned NumCallArguments1,
4340 unsigned NumCallArguments2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004341 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Craig Topperc3ec1492014-05-26 06:22:03 +00004343 NumCallArguments1, nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004345 NumCallArguments2,
Douglas Gregor63814022011-01-21 17:29:42 +00004346 &RefParamComparisons);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004347
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004348 if (Better1 != Better2) // We have a clear winner
4349 return Better1? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004351 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004352 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004353
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004354 // C++0x [temp.deduct.partial]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355 // If for each type being considered a given template is at least as
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004356 // specialized for all types and more specialized for some set of types and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357 // the other template is not more specialized for any types or is not at
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004358 // least as specialized for any types, then the given template is more
4359 // specialized than the other template. Otherwise, neither template is more
4360 // specialized than the other.
4361 Better1 = false;
4362 Better2 = false;
Douglas Gregor63814022011-01-21 17:29:42 +00004363 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004364 // C++0x [temp.deduct.partial]p9:
4365 // If, for a given type, deduction succeeds in both directions (i.e., the
Douglas Gregor63814022011-01-21 17:29:42 +00004366 // types are identical after the transformations above) and both P and A
4367 // were reference types (before being replaced with the type referred to
4368 // above):
4369
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370 // -- if the type from the argument template was an lvalue reference
Douglas Gregor63814022011-01-21 17:29:42 +00004371 // and the type from the parameter template was not, the argument
4372 // type is considered to be more specialized than the other;
4373 // otherwise,
4374 if (!RefParamComparisons[I].ArgIsRvalueRef &&
4375 RefParamComparisons[I].ParamIsRvalueRef) {
4376 Better2 = true;
4377 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004378 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004379 continue;
4380 } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
4381 RefParamComparisons[I].ArgIsRvalueRef) {
4382 Better1 = true;
4383 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004384 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004385 continue;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004387
Douglas Gregor63814022011-01-21 17:29:42 +00004388 // -- if the type from the argument template is more cv-qualified than
4389 // the type from the parameter template (as described above), the
4390 // argument type is considered to be more specialized than the
4391 // other; otherwise,
4392 switch (RefParamComparisons[I].Qualifiers) {
4393 case NeitherMoreQualified:
4394 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395
Douglas Gregor63814022011-01-21 17:29:42 +00004396 case ParamMoreQualified:
4397 Better1 = true;
4398 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004399 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004400 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
Douglas Gregor63814022011-01-21 17:29:42 +00004402 case ArgMoreQualified:
4403 Better2 = true;
4404 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004405 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004406 continue;
4407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408
Douglas Gregor63814022011-01-21 17:29:42 +00004409 // -- neither type is more specialized than the other.
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004410 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004412 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor05155d82009-08-21 23:19:43 +00004413 if (Better1)
4414 return FT1;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004415 else if (Better2)
4416 return FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417
Douglas Gregorcef1a032011-01-16 16:03:23 +00004418 // FIXME: This mimics what GCC implements, but doesn't match up with the
4419 // proposed resolution for core issue 692. This area needs to be sorted out,
4420 // but for now we attempt to maintain compatibility.
4421 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4422 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4423 if (Variadic1 != Variadic2)
4424 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425
Craig Topperc3ec1492014-05-26 06:22:03 +00004426 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004427}
Douglas Gregor9b146582009-07-08 20:55:45 +00004428
Douglas Gregor450f00842009-09-25 18:43:00 +00004429/// \brief Determine if the two templates are equivalent.
4430static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4431 if (T1 == T2)
4432 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433
Douglas Gregor450f00842009-09-25 18:43:00 +00004434 if (!T1 || !T2)
4435 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436
Douglas Gregor450f00842009-09-25 18:43:00 +00004437 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4438}
4439
4440/// \brief Retrieve the most specialized of the given function template
4441/// specializations.
4442///
John McCall58cc69d2010-01-27 01:50:18 +00004443/// \param SpecBegin the start iterator of the function template
4444/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004445///
John McCall58cc69d2010-01-27 01:50:18 +00004446/// \param SpecEnd the end iterator of the function template
4447/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004448///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004450/// diagnostic should occur.
4451///
4452/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4453/// no matching candidates.
4454///
4455/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4456/// occurs.
4457///
4458/// \param CandidateDiag partial diagnostic used for each function template
4459/// specialization that is a candidate in the ambiguous ordering. One parameter
4460/// in this diagnostic should be unbound, which will correspond to the string
4461/// describing the template arguments for the function template specialization.
4462///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004464/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004465UnresolvedSetIterator Sema::getMostSpecialized(
4466 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4467 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004468 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4469 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4470 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004471 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004472 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004473 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004474 FailedCandidates.NoteCandidates(*this, Loc);
4475 }
John McCall58cc69d2010-01-27 01:50:18 +00004476 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004477 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004478
4479 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004480 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481
Douglas Gregor450f00842009-09-25 18:43:00 +00004482 // Find the function template that is better than all of the templates it
4483 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004484 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004486 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004487 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004488 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4489 FunctionTemplateDecl *Challenger
4490 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004491 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004492 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004493 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004494 Challenger)) {
4495 Best = I;
4496 BestTemplate = Challenger;
4497 }
4498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499
Douglas Gregor450f00842009-09-25 18:43:00 +00004500 // Make sure that the "best" function template is more specialized than all
4501 // of the others.
4502 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004503 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4504 FunctionTemplateDecl *Challenger
4505 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004506 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004508 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004509 BestTemplate)) {
4510 Ambiguous = true;
4511 break;
4512 }
4513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004514
Douglas Gregor450f00842009-09-25 18:43:00 +00004515 if (!Ambiguous) {
4516 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004517 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004518 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519
Douglas Gregor450f00842009-09-25 18:43:00 +00004520 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004521 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004522 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523
Richard Smithb875c432013-05-04 01:51:08 +00004524 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004525 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4526 PartialDiagnostic PD = CandidateDiag;
4527 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004528 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004529 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004530 if (!TargetType.isNull())
4531 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4532 TargetType);
4533 Diag((*I)->getLocation(), PD);
4534 }
Richard Smithb875c432013-05-04 01:51:08 +00004535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004536
John McCall58cc69d2010-01-27 01:50:18 +00004537 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004538}
4539
Douglas Gregorbe999392009-09-15 16:23:51 +00004540/// \brief Returns the more specialized class template partial specialization
4541/// according to the rules of partial ordering of class template partial
4542/// specializations (C++ [temp.class.order]).
4543///
4544/// \param PS1 the first class template partial specialization
4545///
4546/// \param PS2 the second class template partial specialization
4547///
4548/// \returns the more specialized class template partial specialization. If
4549/// neither partial specialization is more specialized, returns NULL.
4550ClassTemplatePartialSpecializationDecl *
4551Sema::getMoreSpecializedPartialSpecialization(
4552 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004553 ClassTemplatePartialSpecializationDecl *PS2,
4554 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004555 // C++ [temp.class.order]p1:
4556 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004557 // specialized as the second if, given the following rewrite to two
4558 // function templates, the first function template is at least as
4559 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004560 // templates (14.6.6.2):
4561 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562 // first partial specialization and has a single function parameter
4563 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004564 // arguments of the first partial specialization, and
4565 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004566 // second partial specialization and has a single function parameter
4567 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004568 // arguments of the second partial specialization.
4569 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004570 // Rather than synthesize function templates, we merely perform the
4571 // equivalent partial ordering by performing deduction directly on
4572 // the template arguments of the class template partial
4573 // specializations. This computation is slightly simpler than the
4574 // general problem of function template partial ordering, because
4575 // class template partial specializations are more constrained. We
4576 // know that every template parameter is deducible from the class
4577 // template partial specialization's template arguments, for
4578 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004579 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004580 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004581
4582 QualType PT1 = PS1->getInjectedSpecializationType();
4583 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584
Douglas Gregorbe999392009-09-15 16:23:51 +00004585 // Determine whether PS1 is at least as specialized as PS2
4586 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004587 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4588 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004589 PT2, PT1, Info, Deduced, TDF_None,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004590 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004591 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004592 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004593 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004594 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004595 Better1 = !::FinishTemplateArgumentDeduction(
4596 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4597 }
4598
4599 // Determine whether PS2 is at least as specialized as PS1
4600 Deduced.clear();
4601 Deduced.resize(PS1->getTemplateParameters()->size());
4602 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4603 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
4604 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004605 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004606 if (Better2) {
4607 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4608 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004609 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004610 Better2 = !::FinishTemplateArgumentDeduction(
4611 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4612 }
4613
4614 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004615 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004616
4617 return Better1 ? PS1 : PS2;
4618}
4619
Larisse Voufo30616382013-08-23 22:21:36 +00004620/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4621/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4622/// VarTemplate(Partial)SpecializationDecl with a new data
4623/// structure Template(Partial)SpecializationDecl, and
4624/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004625VarTemplatePartialSpecializationDecl *
4626Sema::getMoreSpecializedPartialSpecialization(
4627 VarTemplatePartialSpecializationDecl *PS1,
4628 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4629 SmallVector<DeducedTemplateArgument, 4> Deduced;
4630 TemplateDeductionInfo Info(Loc);
4631
Richard Smithf04fd0b2013-12-12 23:14:16 +00004632 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004633 "the partial specializations being compared should specialize"
4634 " the same template.");
4635 TemplateName Name(PS1->getSpecializedTemplate());
4636 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4637 QualType PT1 = Context.getTemplateSpecializationType(
4638 CanonTemplate, PS1->getTemplateArgs().data(),
4639 PS1->getTemplateArgs().size());
4640 QualType PT2 = Context.getTemplateSpecializationType(
4641 CanonTemplate, PS2->getTemplateArgs().data(),
4642 PS2->getTemplateArgs().size());
4643
4644 // Determine whether PS1 is at least as specialized as PS2
4645 Deduced.resize(PS2->getTemplateParameters()->size());
4646 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4647 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
4648 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004649 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004650 if (Better1) {
4651 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4652 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004653 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4655 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004656 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658
Douglas Gregorbe999392009-09-15 16:23:51 +00004659 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004660 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004661 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004662 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4663 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004664 PT1, PT2, Info, Deduced, TDF_None,
4665 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004666 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004667 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004668 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004669 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004670 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4671 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004672 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004673 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Douglas Gregorbe999392009-09-15 16:23:51 +00004675 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004676 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004677
Douglas Gregorbe999392009-09-15 16:23:51 +00004678 return Better1? PS1 : PS2;
4679}
4680
Mike Stump11289f42009-09-09 15:08:12 +00004681static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004682MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004683 const TemplateArgument &TemplateArg,
4684 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004685 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004686 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004687
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004688/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004689/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004690static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004691MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004692 const Expr *E,
4693 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004694 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004695 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004696 // We can deduce from a pack expansion.
4697 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4698 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004699
Richard Smith34349002012-07-09 03:07:20 +00004700 // Skip through any implicit casts we added while type-checking, and any
4701 // substitutions performed by template alias expansion.
4702 while (1) {
4703 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4704 E = ICE->getSubExpr();
4705 else if (const SubstNonTypeTemplateParmExpr *Subst =
4706 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4707 E = Subst->getReplacement();
4708 else
4709 break;
4710 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711
4712 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004713 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004714 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004715 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004716 return;
4717
Mike Stump11289f42009-09-09 15:08:12 +00004718 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004719 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4720 if (!NTTP)
4721 return;
4722
Douglas Gregor21610382009-10-29 00:04:11 +00004723 if (NTTP->getDepth() == Depth)
4724 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004725}
4726
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004727/// \brief Mark the template parameters that are used by the given
4728/// nested name specifier.
4729static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004730MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004731 NestedNameSpecifier *NNS,
4732 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004733 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004734 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004735 if (!NNS)
4736 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004738 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004739 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004740 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004741 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004742}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004744/// \brief Mark the template parameters that are used by the given
4745/// template name.
4746static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004747MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004748 TemplateName Name,
4749 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004750 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004751 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004752 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4753 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004754 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4755 if (TTP->getDepth() == Depth)
4756 Used[TTP->getIndex()] = true;
4757 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004758 return;
4759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004761 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004762 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004763 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004764 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004765 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004766 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004767}
4768
4769/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004770/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004771static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004772MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004773 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004774 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004775 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004776 if (T.isNull())
4777 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
Douglas Gregor91772d12009-06-13 00:26:55 +00004779 // Non-dependent types have nothing deducible
4780 if (!T->isDependentType())
4781 return;
4782
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004783 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004784 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004785 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004786 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004787 cast<PointerType>(T)->getPointeeType(),
4788 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004789 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004790 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004791 break;
4792
4793 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004794 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004795 cast<BlockPointerType>(T)->getPointeeType(),
4796 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004797 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004798 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004799 break;
4800
4801 case Type::LValueReference:
4802 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004803 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004804 cast<ReferenceType>(T)->getPointeeType(),
4805 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004806 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004807 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004808 break;
4809
4810 case Type::MemberPointer: {
4811 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004812 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004813 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004814 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004815 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004816 break;
4817 }
4818
4819 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004820 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004821 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004822 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004823 // Fall through to check the element type
4824
4825 case Type::ConstantArray:
4826 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004827 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004828 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004829 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004830 break;
4831
4832 case Type::Vector:
4833 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004834 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004835 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004836 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004837 break;
4838
Douglas Gregor758a8692009-06-17 21:51:59 +00004839 case Type::DependentSizedExtVector: {
4840 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004841 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004842 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004843 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004844 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004845 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004846 break;
4847 }
4848
Douglas Gregor91772d12009-06-13 00:26:55 +00004849 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004850 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004851 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4852 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004853 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4854 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004855 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004856 break;
4857 }
4858
Douglas Gregor21610382009-10-29 00:04:11 +00004859 case Type::TemplateTypeParm: {
4860 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4861 if (TTP->getDepth() == Depth)
4862 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004863 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004864 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004865
Douglas Gregorfb322d82011-01-14 05:11:40 +00004866 case Type::SubstTemplateTypeParmPack: {
4867 const SubstTemplateTypeParmPackType *Subst
4868 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004869 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004870 QualType(Subst->getReplacedParameter(), 0),
4871 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004872 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004873 OnlyDeduced, Depth, Used);
4874 break;
4875 }
4876
John McCall2408e322010-04-27 00:57:59 +00004877 case Type::InjectedClassName:
4878 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4879 // fall through
4880
Douglas Gregor91772d12009-06-13 00:26:55 +00004881 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004882 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004883 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004884 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004885 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886
Douglas Gregord0ad2942010-12-23 01:24:45 +00004887 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888 // If the template argument list of P contains a pack expansion that is not
4889 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004890 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004891 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004892 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4893 break;
4894
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004895 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004896 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004897 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004898 break;
4899 }
4900
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004901 case Type::Complex:
4902 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004903 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004904 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004905 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004906 break;
4907
Eli Friedman0dfb8892011-10-06 23:00:33 +00004908 case Type::Atomic:
4909 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004910 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004911 cast<AtomicType>(T)->getValueType(),
4912 OnlyDeduced, Depth, Used);
4913 break;
4914
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004915 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004916 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004917 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004918 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004919 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004920 break;
4921
John McCallc392f372010-06-11 00:33:02 +00004922 case Type::DependentTemplateSpecialization: {
4923 const DependentTemplateSpecializationType *Spec
4924 = cast<DependentTemplateSpecializationType>(T);
4925 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004926 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00004927 OnlyDeduced, Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004928
Douglas Gregord0ad2942010-12-23 01:24:45 +00004929 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930 // If the template argument list of P contains a pack expansion that is not
4931 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004932 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004934 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4935 break;
4936
John McCallc392f372010-06-11 00:33:02 +00004937 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004938 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004939 Used);
4940 break;
4941 }
4942
John McCallbd8d9bd2010-03-01 23:49:17 +00004943 case Type::TypeOf:
4944 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004945 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004946 cast<TypeOfType>(T)->getUnderlyingType(),
4947 OnlyDeduced, Depth, Used);
4948 break;
4949
4950 case Type::TypeOfExpr:
4951 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004952 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004953 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4954 OnlyDeduced, Depth, Used);
4955 break;
4956
4957 case Type::Decltype:
4958 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004959 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004960 cast<DecltypeType>(T)->getUnderlyingExpr(),
4961 OnlyDeduced, Depth, Used);
4962 break;
4963
Alexis Hunte852b102011-05-24 22:41:36 +00004964 case Type::UnaryTransform:
4965 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004966 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004967 cast<UnaryTransformType>(T)->getUnderlyingType(),
4968 OnlyDeduced, Depth, Used);
4969 break;
4970
Douglas Gregord2fa7662010-12-20 02:24:11 +00004971 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004972 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004973 cast<PackExpansionType>(T)->getPattern(),
4974 OnlyDeduced, Depth, Used);
4975 break;
4976
Richard Smith30482bc2011-02-20 03:19:35 +00004977 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004978 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004979 cast<AutoType>(T)->getDeducedType(),
4980 OnlyDeduced, Depth, Used);
4981
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004982 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004983 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004984 case Type::VariableArray:
4985 case Type::FunctionNoProto:
4986 case Type::Record:
4987 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004988 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004989 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004990 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004991 case Type::UnresolvedUsing:
Douglas Gregor91772d12009-06-13 00:26:55 +00004992#define TYPE(Class, Base)
4993#define ABSTRACT_TYPE(Class, Base)
4994#define DEPENDENT_TYPE(Class, Base)
4995#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4996#include "clang/AST/TypeNodes.def"
4997 break;
4998 }
4999}
5000
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005001/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005002/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005003static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005004MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005005 const TemplateArgument &TemplateArg,
5006 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005007 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005008 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005009 switch (TemplateArg.getKind()) {
5010 case TemplateArgument::Null:
5011 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005012 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005013 break;
Mike Stump11289f42009-09-09 15:08:12 +00005014
Eli Friedmanb826a002012-09-26 02:36:12 +00005015 case TemplateArgument::NullPtr:
5016 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5017 Depth, Used);
5018 break;
5019
Douglas Gregor91772d12009-06-13 00:26:55 +00005020 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005021 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005022 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005023 break;
5024
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005025 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005026 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005027 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005029 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005030 break;
5031
5032 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005033 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005034 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005035 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036
Anders Carlssonbc343912009-06-15 17:04:53 +00005037 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005038 for (const auto &P : TemplateArg.pack_elements())
5039 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005040 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005041 }
5042}
5043
James Dennett41725122012-06-22 10:16:05 +00005044/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005045/// template argument list.
5046///
5047/// \param TemplateArgs the template argument list from which template
5048/// parameters will be deduced.
5049///
James Dennett41725122012-06-22 10:16:05 +00005050/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005051/// to indicate when the corresponding template parameter will be
5052/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005053void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005054Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005055 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005056 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005057 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058 // If the template argument list of P contains a pack expansion that is not
5059 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005060 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005062 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5063 return;
5064
Douglas Gregor91772d12009-06-13 00:26:55 +00005065 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005066 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005067 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005068}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005069
5070/// \brief Marks all of the template parameters that will be deduced by a
5071/// call to the given function template.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005072void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005073Sema::MarkDeducedTemplateParameters(ASTContext &Ctx,
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +00005074 const FunctionTemplateDecl *FunctionTemplate,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005075 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005076 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005077 = FunctionTemplate->getTemplateParameters();
5078 Deduced.clear();
5079 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080
Douglas Gregorce23bae2009-09-18 23:21:38 +00005081 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5082 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005083 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005084 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005085}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005086
5087bool hasDeducibleTemplateParameters(Sema &S,
5088 FunctionTemplateDecl *FunctionTemplate,
5089 QualType T) {
5090 if (!T->isDependentType())
5091 return false;
5092
5093 TemplateParameterList *TemplateParams
5094 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005095 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005096 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005097 Deduced);
5098
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005099 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005100}