blob: 0d43c01d995eec7e1bc06ea331f6df899675cf94 [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 &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000265 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000266 return X;
267
268 // All other combinations are incompatible.
269 return DeducedTemplateArgument();
270
271 case TemplateArgument::NullPtr:
272 // If we deduced a null pointer and a dependent expression, keep the
273 // null pointer.
274 if (Y.getKind() == TemplateArgument::Expression)
275 return X;
276
277 // If we deduced a null pointer and an integral constant, keep the
278 // integral constant.
279 if (Y.getKind() == TemplateArgument::Integral)
280 return Y;
281
282 // If we deduced two null pointers, make sure they have the same type.
283 if (Y.getKind() == TemplateArgument::NullPtr &&
284 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000285 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000286
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000287 // All other combinations are incompatible.
288 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000289
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000290 case TemplateArgument::Pack:
291 if (Y.getKind() != TemplateArgument::Pack ||
292 X.pack_size() != Y.pack_size())
293 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294
295 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000296 XAEnd = X.pack_end(),
297 YA = Y.pack_begin();
298 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000299 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000300 if (checkDeducedTemplateArguments(Context,
301 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000302 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
303 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000304 return DeducedTemplateArgument();
305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000306
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 return X;
308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000309
David Blaikiee4d798f2012-01-20 21:50:17 +0000310 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000311}
312
Mike Stump11289f42009-09-09 15:08:12 +0000313/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000314/// from the given constant.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000315static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000316DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump11289f42009-09-09 15:08:12 +0000317 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor0a29a052010-03-26 05:50:28 +0000318 llvm::APSInt Value, QualType ValueType,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000319 bool DeducedFromArrayBound,
John McCall19c1bfd2010-08-25 05:32:35 +0000320 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000322 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000323 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000324
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000325 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
326 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000328 Deduced[NTTP->getIndex()],
329 NewDeduced);
330 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000331 Info.Param = NTTP;
332 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000333 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000334 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000335 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000336
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000337 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000338 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000339}
340
Mike Stump11289f42009-09-09 15:08:12 +0000341/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000342/// from the given type- or value-dependent expression.
343///
344/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000345static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000346DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000347 NonTypeTemplateParmDecl *NTTP,
348 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000349 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000350 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000351 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000352 "Cannot deduce non-type template argument with depth > 0");
353 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
354 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000355
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000356 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000357 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
358 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000359 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000360
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000361 if (Result.isNull()) {
362 Info.Param = NTTP;
363 Info.FirstArg = Deduced[NTTP->getIndex()];
364 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000365 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000367
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000368 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000369 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000370}
371
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000372/// \brief Deduce the value of the given non-type template parameter
373/// from the given declaration.
374///
375/// \returns true if deduction succeeded, false otherwise.
376static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000377DeduceNonTypeTemplateArgument(Sema &S,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000378 NonTypeTemplateParmDecl *NTTP,
379 ValueDecl *D,
380 TemplateDeductionInfo &Info,
381 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000382 assert(NTTP->getDepth() == 0 &&
383 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Craig Topperc3ec1492014-05-26 06:22:03 +0000385 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
David Blaikie0f62c8d2014-10-16 04:21:25 +0000386 TemplateArgument New(D, NTTP->getType());
Eli Friedmanb826a002012-09-26 02:36:12 +0000387 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000389 Deduced[NTTP->getIndex()],
390 NewDeduced);
391 if (Result.isNull()) {
392 Info.Param = NTTP;
393 Info.FirstArg = Deduced[NTTP->getIndex()];
394 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000395 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000397
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000398 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000399 return Sema::TDK_Success;
400}
401
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000402static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000403DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000404 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000405 TemplateName Param,
406 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000407 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000408 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000409 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000410 if (!ParamDecl) {
411 // The parameter type is dependent and is not a template template parameter,
412 // so there is nothing that we can deduce.
413 return Sema::TDK_Success;
414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
Douglas Gregoradee3e32009-11-11 23:06:43 +0000416 if (TemplateTemplateParmDecl *TempParam
417 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000418 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000420 Deduced[TempParam->getIndex()],
421 NewDeduced);
422 if (Result.isNull()) {
423 Info.Param = TempParam;
424 Info.FirstArg = Deduced[TempParam->getIndex()];
425 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000426 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000429 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000430 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000432
Douglas Gregoradee3e32009-11-11 23:06:43 +0000433 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000434 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000435 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000436
Douglas Gregoradee3e32009-11-11 23:06:43 +0000437 // Mismatch of non-dependent template parameter to argument.
438 Info.FirstArg = TemplateArgument(Param);
439 Info.SecondArg = TemplateArgument(Arg);
440 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000441}
442
Mike Stump11289f42009-09-09 15:08:12 +0000443/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000444/// type (which is a template-id) with the template argument type.
445///
Chandler Carruthc1263112010-02-07 21:33:28 +0000446/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000447///
448/// \param TemplateParams the template parameters that we are deducing
449///
450/// \param Param the parameter type
451///
452/// \param Arg the argument type
453///
454/// \param Info information about the template argument deduction itself
455///
456/// \param Deduced the deduced template arguments
457///
458/// \returns the result of template argument deduction so far. Note that a
459/// "success" result means that template argument deduction has not yet failed,
460/// but it may still fail, later, for other reasons.
461static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000462DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000463 TemplateParameterList *TemplateParams,
464 const TemplateSpecializationType *Param,
465 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000466 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000467 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000468 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000469
Douglas Gregore81f3e72009-07-07 23:09:34 +0000470 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000471 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000472 = dyn_cast<TemplateSpecializationType>(Arg)) {
473 // Perform template argument deduction for the template name.
474 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000475 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000476 Param->getTemplateName(),
477 SpecArg->getTemplateName(),
478 Info, Deduced))
479 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000480
Mike Stump11289f42009-09-09 15:08:12 +0000481
Douglas Gregore81f3e72009-07-07 23:09:34 +0000482 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000483 // argument. Ignore any missing/extra arguments, since they could be
484 // filled in by default arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000485 return DeduceTemplateArguments(S, TemplateParams,
486 Param->getArgs(), Param->getNumArgs(),
Douglas Gregord80ea202010-12-22 18:55:49 +0000487 SpecArg->getArgs(), SpecArg->getNumArgs(),
Richard Smith16b65392012-12-06 06:44:44 +0000488 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000489 }
Mike Stump11289f42009-09-09 15:08:12 +0000490
Douglas Gregore81f3e72009-07-07 23:09:34 +0000491 // If the argument type is a class template specialization, we
492 // perform template argument deduction using its template
493 // arguments.
494 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000495 if (!RecordArg) {
496 Info.FirstArg = TemplateArgument(QualType(Param, 0));
497 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000499 }
Mike Stump11289f42009-09-09 15:08:12 +0000500
501 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000502 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000503 if (!SpecArg) {
504 Info.FirstArg = TemplateArgument(QualType(Param, 0));
505 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000506 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000507 }
Mike Stump11289f42009-09-09 15:08:12 +0000508
Douglas Gregore81f3e72009-07-07 23:09:34 +0000509 // Perform template argument deduction for the template name.
510 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000511 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000512 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000513 Param->getTemplateName(),
514 TemplateName(SpecArg->getSpecializedTemplate()),
515 Info, Deduced))
516 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000517
Douglas Gregor7baabef2010-12-22 18:17:10 +0000518 // Perform template argument deduction for the template arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000519 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000520 Param->getArgs(), Param->getNumArgs(),
521 SpecArg->getTemplateArgs().data(),
522 SpecArg->getTemplateArgs().size(),
523 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000524}
525
John McCall08569062010-08-28 22:14:41 +0000526/// \brief Determines whether the given type is an opaque type that
527/// might be more qualified when instantiated.
528static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
529 switch (T->getTypeClass()) {
530 case Type::TypeOfExpr:
531 case Type::TypeOf:
532 case Type::DependentName:
533 case Type::Decltype:
534 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000535 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000536 return true;
537
538 case Type::ConstantArray:
539 case Type::IncompleteArray:
540 case Type::VariableArray:
541 case Type::DependentSizedArray:
542 return IsPossiblyOpaquelyQualifiedType(
543 cast<ArrayType>(T)->getElementType());
544
545 default:
546 return false;
547 }
548}
549
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000550/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000552getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000553 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
554 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555
Douglas Gregor5499af42011-01-05 23:12:31 +0000556 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
557 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor5499af42011-01-05 23:12:31 +0000559 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
560 return std::make_pair(TTP->getDepth(), TTP->getIndex());
561}
562
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000563/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000565getDepthAndIndex(UnexpandedParameterPack UPP) {
566 if (const TemplateTypeParmType *TTP
567 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
568 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000570 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
571}
572
Douglas Gregor5499af42011-01-05 23:12:31 +0000573/// \brief Helper function to build a TemplateParameter when we don't
574/// know its type statically.
575static TemplateParameter makeTemplateParameter(Decl *D) {
576 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
577 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000578 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000579 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor5499af42011-01-05 23:12:31 +0000581 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
582}
583
Richard Smith0a80d572014-05-29 01:12:14 +0000584/// A pack that we're currently deducing.
585struct clang::DeducedPack {
586 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000587
Richard Smith0a80d572014-05-29 01:12:14 +0000588 // The index of the pack.
589 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Richard Smith0a80d572014-05-29 01:12:14 +0000591 // The old value of the pack before we started deducing it.
592 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000593
Richard Smith0a80d572014-05-29 01:12:14 +0000594 // A deferred value of this pack from an inner deduction, that couldn't be
595 // deduced because this deduction hadn't happened yet.
596 DeducedTemplateArgument DeferredDeduction;
597
598 // The new value of the pack.
599 SmallVector<DeducedTemplateArgument, 4> New;
600
601 // The outer deduction for this pack, if any.
602 DeducedPack *Outer;
603};
604
605/// A scope in which we're performing pack deduction.
606class PackDeductionScope {
607public:
608 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
609 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
610 TemplateDeductionInfo &Info, TemplateArgument Pattern)
611 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
612 // Compute the set of template parameter indices that correspond to
613 // parameter packs expanded by the pack expansion.
614 {
615 llvm::SmallBitVector SawIndices(TemplateParams->size());
616 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
617 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
618 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
619 unsigned Depth, Index;
620 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
621 if (Depth == 0 && !SawIndices[Index]) {
622 SawIndices[Index] = true;
623
624 // Save the deduced template argument for the parameter pack expanded
625 // by this pack expansion, then clear out the deduction.
626 DeducedPack Pack(Index);
627 Pack.Saved = Deduced[Index];
628 Deduced[Index] = TemplateArgument();
629
630 Packs.push_back(Pack);
631 }
632 }
633 }
634 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
635
636 for (auto &Pack : Packs) {
637 if (Info.PendingDeducedPacks.size() > Pack.Index)
638 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
639 else
640 Info.PendingDeducedPacks.resize(Pack.Index + 1);
641 Info.PendingDeducedPacks[Pack.Index] = &Pack;
642
643 if (S.CurrentInstantiationScope) {
644 // If the template argument pack was explicitly specified, add that to
645 // the set of deduced arguments.
646 const TemplateArgument *ExplicitArgs;
647 unsigned NumExplicitArgs;
648 NamedDecl *PartiallySubstitutedPack =
649 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
650 &ExplicitArgs, &NumExplicitArgs);
651 if (PartiallySubstitutedPack &&
652 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
653 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
654 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000655 }
656 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000657
Richard Smith0a80d572014-05-29 01:12:14 +0000658 ~PackDeductionScope() {
659 for (auto &Pack : Packs)
660 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000662
Richard Smith0a80d572014-05-29 01:12:14 +0000663 /// Move to deducing the next element in each pack that is being deduced.
664 void nextPackElement() {
665 // Capture the deduced template arguments for each parameter pack expanded
666 // by this pack expansion, add them to the list of arguments we've deduced
667 // for that pack, then clear out the deduced argument.
668 for (auto &Pack : Packs) {
669 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
670 if (!DeducedArg.isNull()) {
671 Pack.New.push_back(DeducedArg);
672 DeducedArg = DeducedTemplateArgument();
673 }
674 }
675 }
676
677 /// \brief Finish template argument deduction for a set of argument packs,
678 /// producing the argument packs and checking for consistency with prior
679 /// deductions.
680 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
681 // Build argument packs for each of the parameter packs expanded by this
682 // pack expansion.
683 for (auto &Pack : Packs) {
684 // Put back the old value for this pack.
685 Deduced[Pack.Index] = Pack.Saved;
686
687 // Build or find a new value for this pack.
688 DeducedTemplateArgument NewPack;
689 if (HasAnyArguments && Pack.New.empty()) {
690 if (Pack.DeferredDeduction.isNull()) {
691 // We were not able to deduce anything for this parameter pack
692 // (because it only appeared in non-deduced contexts), so just
693 // restore the saved argument pack.
694 continue;
695 }
696
697 NewPack = Pack.DeferredDeduction;
698 Pack.DeferredDeduction = TemplateArgument();
699 } else if (Pack.New.empty()) {
700 // If we deduced an empty argument pack, create it now.
701 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
702 } else {
703 TemplateArgument *ArgumentPack =
704 new (S.Context) TemplateArgument[Pack.New.size()];
705 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
706 NewPack = DeducedTemplateArgument(
707 TemplateArgument(ArgumentPack, Pack.New.size()),
708 Pack.New[0].wasDeducedFromArrayBound());
709 }
710
711 // Pick where we're going to put the merged pack.
712 DeducedTemplateArgument *Loc;
713 if (Pack.Outer) {
714 if (Pack.Outer->DeferredDeduction.isNull()) {
715 // Defer checking this pack until we have a complete pack to compare
716 // it against.
717 Pack.Outer->DeferredDeduction = NewPack;
718 continue;
719 }
720 Loc = &Pack.Outer->DeferredDeduction;
721 } else {
722 Loc = &Deduced[Pack.Index];
723 }
724
725 // Check the new pack matches any previous value.
726 DeducedTemplateArgument OldPack = *Loc;
727 DeducedTemplateArgument Result =
728 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
729
730 // If we deferred a deduction of this pack, check that one now too.
731 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
732 OldPack = Result;
733 NewPack = Pack.DeferredDeduction;
734 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
735 }
736
737 if (Result.isNull()) {
738 Info.Param =
739 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
740 Info.FirstArg = OldPack;
741 Info.SecondArg = NewPack;
742 return Sema::TDK_Inconsistent;
743 }
744
745 *Loc = Result;
746 }
747
748 return Sema::TDK_Success;
749 }
750
751private:
752 Sema &S;
753 TemplateParameterList *TemplateParams;
754 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
755 TemplateDeductionInfo &Info;
756
757 SmallVector<DeducedPack, 2> Packs;
758};
Douglas Gregorb94a6172011-01-10 17:53:52 +0000759
Douglas Gregor5499af42011-01-05 23:12:31 +0000760/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000761/// types to the list of argument types, as in the parameter-type-lists of
762/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000763///
764/// \param S The semantic analysis object within which we are deducing
765///
766/// \param TemplateParams The template parameters that we are deducing
767///
768/// \param Params The list of parameter types
769///
770/// \param NumParams The number of types in \c Params
771///
772/// \param Args The list of argument types
773///
774/// \param NumArgs The number of types in \c Args
775///
776/// \param Info information about the template argument deduction itself
777///
778/// \param Deduced the deduced template arguments
779///
780/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
781/// how template argument deduction is performed.
782///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000783/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000784/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000785/// (C++0x [temp.deduct.partial]).
786///
Douglas Gregor63814022011-01-21 17:29:42 +0000787/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +0000788/// in the context of partial ordering, the set of qualifier comparisons.
789///
Douglas Gregor5499af42011-01-05 23:12:31 +0000790/// \returns the result of template argument deduction so far. Note that a
791/// "success" result means that template argument deduction has not yet failed,
792/// but it may still fail, later, for other reasons.
793static Sema::TemplateDeductionResult
794DeduceTemplateArguments(Sema &S,
795 TemplateParameterList *TemplateParams,
796 const QualType *Params, unsigned NumParams,
797 const QualType *Args, unsigned NumArgs,
798 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000799 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000800 unsigned TDF,
801 bool PartialOrdering = false,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000802 SmallVectorImpl<RefParamPartialOrderingComparison> *
Craig Topperc3ec1492014-05-26 06:22:03 +0000803 RefParamComparisons = nullptr) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000804 // Fast-path check to see if we have too many/too few arguments.
805 if (NumParams != NumArgs &&
806 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
807 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000808 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809
Douglas Gregor5499af42011-01-05 23:12:31 +0000810 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811 // Similarly, if P has a form that contains (T), then each parameter type
812 // Pi of the respective parameter-type- list of P is compared with the
813 // corresponding parameter type Ai of the corresponding parameter-type-list
814 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000815 unsigned ArgIdx = 0, ParamIdx = 0;
816 for (; ParamIdx != NumParams; ++ParamIdx) {
817 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000819 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
820 if (!Expansion) {
821 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822
Douglas Gregor5499af42011-01-05 23:12:31 +0000823 // Make sure we have an argument.
824 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000825 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000826
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000827 if (isa<PackExpansionType>(Args[ArgIdx])) {
828 // C++0x [temp.deduct.type]p22:
829 // If the original function parameter associated with A is a function
830 // parameter pack and the function parameter associated with P is not
831 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000832 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000833 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834
Douglas Gregor5499af42011-01-05 23:12:31 +0000835 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000836 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
837 Params[ParamIdx], Args[ArgIdx],
838 Info, Deduced, TDF,
839 PartialOrdering,
840 RefParamComparisons))
Douglas Gregor5499af42011-01-05 23:12:31 +0000841 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 ++ArgIdx;
844 continue;
845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000846
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000847 // C++0x [temp.deduct.type]p5:
848 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000849 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000850 // parameter-declaration-clause.
851 if (ParamIdx + 1 < NumParams)
852 return Sema::TDK_Success;
853
Douglas Gregor5499af42011-01-05 23:12:31 +0000854 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000856 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000858 // comparison deduces template arguments for subsequent positions in the
859 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000860
Douglas Gregor5499af42011-01-05 23:12:31 +0000861 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000862 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863
Douglas Gregor5499af42011-01-05 23:12:31 +0000864 bool HasAnyArguments = false;
865 for (; ArgIdx < NumArgs; ++ArgIdx) {
866 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor5499af42011-01-05 23:12:31 +0000868 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000869 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000870 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
871 Args[ArgIdx], Info, Deduced,
872 TDF, PartialOrdering,
873 RefParamComparisons))
Douglas Gregor5499af42011-01-05 23:12:31 +0000874 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000875
Richard Smith0a80d572014-05-29 01:12:14 +0000876 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878
Douglas Gregor5499af42011-01-05 23:12:31 +0000879 // Build argument packs for each of the parameter packs expanded by this
880 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000881 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000882 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000883 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000884
Douglas Gregor5499af42011-01-05 23:12:31 +0000885 // Make sure we don't have any extra arguments.
886 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000887 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888
Douglas Gregor5499af42011-01-05 23:12:31 +0000889 return Sema::TDK_Success;
890}
891
Douglas Gregor1d684c22011-04-28 00:56:09 +0000892/// \brief Determine whether the parameter has qualifiers that are either
893/// inconsistent with or a superset of the argument's qualifiers.
894static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
895 QualType ArgType) {
896 Qualifiers ParamQs = ParamType.getQualifiers();
897 Qualifiers ArgQs = ArgType.getQualifiers();
898
899 if (ParamQs == ArgQs)
900 return false;
901
902 // Mismatched (but not missing) Objective-C GC attributes.
903 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
904 ParamQs.hasObjCGCAttr())
905 return true;
906
907 // Mismatched (but not missing) address spaces.
908 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
909 ParamQs.hasAddressSpace())
910 return true;
911
John McCall31168b02011-06-15 23:02:42 +0000912 // Mismatched (but not missing) Objective-C lifetime qualifiers.
913 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
914 ParamQs.hasObjCLifetime())
915 return true;
916
Douglas Gregor1d684c22011-04-28 00:56:09 +0000917 // CVR qualifier superset.
918 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
919 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
920 == ParamQs.getCVRQualifiers());
921}
922
Douglas Gregor19a41f12013-04-17 08:45:07 +0000923/// \brief Compare types for equality with respect to possibly compatible
924/// function types (noreturn adjustment, implicit calling conventions). If any
925/// of parameter and argument is not a function, just perform type comparison.
926///
927/// \param Param the template parameter type.
928///
929/// \param Arg the argument type.
930bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
931 CanQualType Arg) {
932 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
933 *ArgFunction = Arg->getAs<FunctionType>();
934
935 // Just compare if not functions.
936 if (!ParamFunction || !ArgFunction)
937 return Param == Arg;
938
939 // Noreturn adjustment.
940 QualType AdjustedParam;
941 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
942 return Arg == Context.getCanonicalType(AdjustedParam);
943
944 // FIXME: Compatible calling conventions.
945
946 return Param == Arg;
947}
948
Douglas Gregorcceb9752009-06-26 18:27:22 +0000949/// \brief Deduce the template arguments by comparing the parameter type and
950/// the argument type (C++ [temp.deduct.type]).
951///
Chandler Carruthc1263112010-02-07 21:33:28 +0000952/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000953///
954/// \param TemplateParams the template parameters that we are deducing
955///
956/// \param ParamIn the parameter type
957///
958/// \param ArgIn the argument type
959///
960/// \param Info information about the template argument deduction itself
961///
962/// \param Deduced the deduced template arguments
963///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000964/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000965/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000966///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000967/// \param PartialOrdering Whether we're performing template argument deduction
968/// in the context of partial ordering (C++0x [temp.deduct.partial]).
969///
Douglas Gregor63814022011-01-21 17:29:42 +0000970/// \param RefParamComparisons If we're performing template argument deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +0000971/// in the context of partial ordering, the set of qualifier comparisons.
972///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000973/// \returns the result of template argument deduction so far. Note that a
974/// "success" result means that template argument deduction has not yet failed,
975/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000976static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000977DeduceTemplateArgumentsByTypeMatch(Sema &S,
978 TemplateParameterList *TemplateParams,
979 QualType ParamIn, QualType ArgIn,
980 TemplateDeductionInfo &Info,
981 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
982 unsigned TDF,
983 bool PartialOrdering,
984 SmallVectorImpl<RefParamPartialOrderingComparison> *
985 RefParamComparisons) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000986 // We only want to look at the canonical types, since typedefs and
987 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000988 QualType Param = S.Context.getCanonicalType(ParamIn);
989 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000990
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000991 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000992 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000993 if (const PackExpansionType *ArgExpansion
994 = dyn_cast<PackExpansionType>(Arg))
995 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
Douglas Gregorb837ea42011-01-11 17:34:58 +0000997 if (PartialOrdering) {
998 // C++0x [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999 // Before the partial ordering is done, certain transformations are
1000 // performed on the types used for partial ordering:
1001 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001002 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1003 if (ParamRef)
1004 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001005
Douglas Gregorb837ea42011-01-11 17:34:58 +00001006 // - If A is a reference type, A is replaced by the type referred to.
1007 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1008 if (ArgRef)
1009 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
Douglas Gregor63814022011-01-21 17:29:42 +00001011 if (RefParamComparisons && ParamRef && ArgRef) {
Douglas Gregorb837ea42011-01-11 17:34:58 +00001012 // C++0x [temp.deduct.partial]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001013 // If both P and A were reference types (before being replaced with the
1014 // type referred to above), determine which of the two types (if any) is
Douglas Gregorb837ea42011-01-11 17:34:58 +00001015 // more cv-qualified than the other; otherwise the types are considered
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001016 // to be equally cv-qualified for partial ordering purposes. The result
Douglas Gregorb837ea42011-01-11 17:34:58 +00001017 // of this determination will be used below.
1018 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019 // We save this information for later, using it only when deduction
Douglas Gregorb837ea42011-01-11 17:34:58 +00001020 // succeeds in both directions.
Douglas Gregor63814022011-01-21 17:29:42 +00001021 RefParamPartialOrderingComparison Comparison;
1022 Comparison.ParamIsRvalueRef = ParamRef->getAs<RValueReferenceType>();
1023 Comparison.ArgIsRvalueRef = ArgRef->getAs<RValueReferenceType>();
1024 Comparison.Qualifiers = NeitherMoreQualified;
Douglas Gregor85894a82011-04-30 17:07:52 +00001025
1026 Qualifiers ParamQuals = Param.getQualifiers();
1027 Qualifiers ArgQuals = Arg.getQualifiers();
1028 if (ParamQuals.isStrictSupersetOf(ArgQuals))
Douglas Gregor63814022011-01-21 17:29:42 +00001029 Comparison.Qualifiers = ParamMoreQualified;
Douglas Gregor85894a82011-04-30 17:07:52 +00001030 else if (ArgQuals.isStrictSupersetOf(ParamQuals))
Douglas Gregor63814022011-01-21 17:29:42 +00001031 Comparison.Qualifiers = ArgMoreQualified;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001032 else if (ArgQuals.getObjCLifetime() != ParamQuals.getObjCLifetime() &&
1033 ArgQuals.withoutObjCLifetime()
1034 == ParamQuals.withoutObjCLifetime()) {
1035 // Prefer binding to non-__unsafe_autoretained parameters.
1036 if (ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1037 ParamQuals.getObjCLifetime())
1038 Comparison.Qualifiers = ParamMoreQualified;
1039 else if (ParamQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1040 ArgQuals.getObjCLifetime())
1041 Comparison.Qualifiers = ArgMoreQualified;
1042 }
Douglas Gregor63814022011-01-21 17:29:42 +00001043 RefParamComparisons->push_back(Comparison);
Douglas Gregorb837ea42011-01-11 17:34:58 +00001044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045
Douglas Gregorb837ea42011-01-11 17:34:58 +00001046 // C++0x [temp.deduct.partial]p7:
1047 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001049 // version of P.
1050 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001052 // version of A.
1053 Arg = Arg.getUnqualifiedType();
1054 } else {
1055 // C++0x [temp.deduct.call]p4 bullet 1:
1056 // - If the original P is a reference type, the deduced A (i.e., the type
1057 // referred to by the reference) can be more cv-qualified than the
1058 // transformed A.
1059 if (TDF & TDF_ParamWithReferenceType) {
1060 Qualifiers Quals;
1061 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1062 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001063 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001064 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066
Douglas Gregor85f240c2011-01-25 17:19:08 +00001067 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1068 // C++0x [temp.deduct.type]p10:
1069 // If P and A are function types that originated from deduction when
1070 // taking the address of a function template (14.8.2.2) or when deducing
1071 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072 // Ai are parameters of the top-level parameter-type-list of P and A,
1073 // respectively, Pi is adjusted if it is an rvalue reference to a
1074 // cv-unqualified template parameter and Ai is an lvalue reference, in
1075 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001076 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1077 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001078 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001079 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001080
Douglas Gregor85f240c2011-01-25 17:19:08 +00001081 if (const RValueReferenceType *ParamRef
1082 = Param->getAs<RValueReferenceType>()) {
1083 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1084 !ParamRef->getPointeeType().getQualifiers())
1085 if (Arg->isLValueReferenceType())
1086 Param = ParamRef->getPointeeType();
1087 }
1088 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001091 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001092 // A template type argument T, a template template argument TT or a
1093 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001094 // the following forms:
1095 //
1096 // T
1097 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001098 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001099 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001100 // Just skip any attempts to deduce from a placeholder type.
1101 if (Arg->isPlaceholderType())
1102 return Sema::TDK_Success;
1103
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001104 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001105 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001106
Douglas Gregor60454822009-07-22 20:02:25 +00001107 // If the argument type is an array type, move the qualifiers up to the
1108 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001109 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001110 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001111 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001112 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001113 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001114 RecanonicalizeArg = true;
1115 }
1116 }
Mike Stump11289f42009-09-09 15:08:12 +00001117
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001118 // The argument type can not be less qualified than the parameter
1119 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001120 if (!(TDF & TDF_IgnoreQualifiers) &&
1121 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001122 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001123 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001124 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001125 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001126 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001127
1128 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001129 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001130 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001131
Douglas Gregor1d684c22011-04-28 00:56:09 +00001132 // Remove any qualifiers on the parameter from the deduced type.
1133 // We checked the qualifiers for consistency above.
1134 Qualifiers DeducedQs = DeducedType.getQualifiers();
1135 Qualifiers ParamQs = Param.getQualifiers();
1136 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1137 if (ParamQs.hasObjCGCAttr())
1138 DeducedQs.removeObjCGCAttr();
1139 if (ParamQs.hasAddressSpace())
1140 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001141 if (ParamQs.hasObjCLifetime())
1142 DeducedQs.removeObjCLifetime();
Douglas Gregore46db902011-06-17 22:11:49 +00001143
1144 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001145 // If template deduction would produce a lifetime qualifier on a type
1146 // that is not a lifetime type, template argument deduction fails.
1147 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1148 !DeducedType->isDependentType()) {
1149 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1150 Info.FirstArg = TemplateArgument(Param);
1151 Info.SecondArg = TemplateArgument(Arg);
1152 return Sema::TDK_Underqualified;
1153 }
1154
1155 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001156 // If template deduction would produce an argument type with lifetime type
1157 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001158 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001159 DeducedType->isObjCLifetimeType() &&
1160 !DeducedQs.hasObjCLifetime())
1161 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1162
Douglas Gregor1d684c22011-04-28 00:56:09 +00001163 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1164 DeducedQs);
1165
Douglas Gregord6605db2009-07-22 21:30:48 +00001166 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001167 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001169 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001170 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001171 Deduced[Index],
1172 NewDeduced);
1173 if (Result.isNull()) {
1174 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1175 Info.FirstArg = Deduced[Index];
1176 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001177 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001180 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001181 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001182 }
1183
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001184 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001185 Info.FirstArg = TemplateArgument(ParamIn);
1186 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001187
Douglas Gregorfb322d82011-01-14 05:11:40 +00001188 // If the parameter is an already-substituted template parameter
1189 // pack, do nothing: we don't know which of its arguments to look
1190 // at, so we have to wait until all of the parameter packs in this
1191 // expansion have arguments.
1192 if (isa<SubstTemplateTypeParmPackType>(Param))
1193 return Sema::TDK_Success;
1194
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001195 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001196 CanQualType CanParam = S.Context.getCanonicalType(Param);
1197 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001198 if (!(TDF & TDF_IgnoreQualifiers)) {
1199 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001200 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001201 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001202 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001203 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001204 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001205 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001206
1207 // If the parameter type is not dependent, there is nothing to deduce.
1208 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001209 if (!(TDF & TDF_SkipNonDependent)) {
1210 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1211 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1212 Param != Arg;
1213 if (NonDeduced) {
1214 return Sema::TDK_NonDeducedMismatch;
1215 }
1216 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001217 return Sema::TDK_Success;
1218 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001219 } else if (!Param->isDependentType()) {
1220 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1221 ArgUnqualType = CanArg.getUnqualifiedType();
1222 bool Success = (TDF & TDF_InOverloadResolution)?
1223 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1224 ArgUnqualType) :
1225 ParamUnqualType == ArgUnqualType;
1226 if (Success)
1227 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001228 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001229
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001230 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001231 // Non-canonical types cannot appear here.
1232#define NON_CANONICAL_TYPE(Class, Base) \
1233 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1234#define TYPE(Class, Base)
1235#include "clang/AST/TypeNodes.def"
1236
1237 case Type::TemplateTypeParm:
1238 case Type::SubstTemplateTypeParmPack:
1239 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001240
1241 // These types cannot be dependent, so simply check whether the types are
1242 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001243 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001244 case Type::VariableArray:
1245 case Type::Vector:
1246 case Type::FunctionNoProto:
1247 case Type::Record:
1248 case Type::Enum:
1249 case Type::ObjCObject:
1250 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001251 case Type::ObjCObjectPointer: {
1252 if (TDF & TDF_SkipNonDependent)
1253 return Sema::TDK_Success;
1254
1255 if (TDF & TDF_IgnoreQualifiers) {
1256 Param = Param.getUnqualifiedType();
1257 Arg = Arg.getUnqualifiedType();
1258 }
1259
1260 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1261 }
1262
Douglas Gregor39c02722011-06-15 16:02:29 +00001263 // _Complex T [placeholder extension]
1264 case Type::Complex:
1265 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001266 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor39c02722011-06-15 16:02:29 +00001267 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001268 ComplexArg->getElementType(),
1269 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001270
1271 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001272
1273 // _Atomic T [extension]
1274 case Type::Atomic:
1275 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001276 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001277 cast<AtomicType>(Param)->getValueType(),
1278 AtomicArg->getValueType(),
1279 Info, Deduced, TDF);
1280
1281 return Sema::TDK_NonDeducedMismatch;
1282
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001283 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001284 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001285 QualType PointeeType;
1286 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1287 PointeeType = PointerArg->getPointeeType();
1288 } else if (const ObjCObjectPointerType *PointerArg
1289 = Arg->getAs<ObjCObjectPointerType>()) {
1290 PointeeType = PointerArg->getPointeeType();
1291 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001292 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001293 }
Mike Stump11289f42009-09-09 15:08:12 +00001294
Douglas Gregorfc516c92009-06-26 23:27:24 +00001295 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001296 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1297 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001298 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001299 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001300 }
Mike Stump11289f42009-09-09 15:08:12 +00001301
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001302 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001303 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001304 const LValueReferenceType *ReferenceArg =
1305 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: {
Nico Weberc153d242014-07-28 00:02:09 +00001316 const RValueReferenceType *ReferenceArg =
1317 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001318 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001319 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001320
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001321 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1322 cast<RValueReferenceType>(Param)->getPointeeType(),
1323 ReferenceArg->getPointeeType(),
1324 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001325 }
Mike Stump11289f42009-09-09 15:08:12 +00001326
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001327 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001328 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001329 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001330 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001331 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001332 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001333
John McCallf7332682010-08-19 00:20:19 +00001334 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001335 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1336 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1337 IncompleteArrayArg->getElementType(),
1338 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001339 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001340
1341 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001342 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001343 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001344 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001345 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001346 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001347
1348 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001349 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001350 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001351 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001352
John McCallf7332682010-08-19 00:20:19 +00001353 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001354 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1355 ConstantArrayParm->getElementType(),
1356 ConstantArrayArg->getElementType(),
1357 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001358 }
1359
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001360 // type [i]
1361 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001362 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001363 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001364 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001365
John McCallf7332682010-08-19 00:20:19 +00001366 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1367
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001368 // Check the element type of the arrays
1369 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001370 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001371 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001372 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1373 DependentArrayParm->getElementType(),
1374 ArrayArg->getElementType(),
1375 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001376 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001377
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001378 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001379 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001380 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1381 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001382 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001383
1384 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001385 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001386 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001387 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001388 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001389 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1390 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001392 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001393 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001394 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001395 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001396 if (const DependentSizedArrayType *DependentArrayArg
1397 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001398 if (DependentArrayArg->getSizeExpr())
1399 return DeduceNonTypeTemplateArgument(S, NTTP,
1400 DependentArrayArg->getSizeExpr(),
1401 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001402
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001403 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001404 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001405 }
Mike Stump11289f42009-09-09 15:08:12 +00001406
1407 // type(*)(T)
1408 // T(*)()
1409 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001410 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001411 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001412 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001413 dyn_cast<FunctionProtoType>(Arg);
1414 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001415 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001416
1417 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001418 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001419
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001420 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001421 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001423 != FunctionProtoArg->getRefQualifier() ||
1424 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001425 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001426
Anders Carlsson2128ec72009-06-08 15:19:08 +00001427 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001428 if (Sema::TemplateDeductionResult Result =
1429 DeduceTemplateArgumentsByTypeMatch(
1430 S, TemplateParams, FunctionProtoParam->getReturnType(),
1431 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001432 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001433
Alp Toker9cacbab2014-01-20 20:26:09 +00001434 return DeduceTemplateArguments(
1435 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1436 FunctionProtoParam->getNumParams(),
1437 FunctionProtoArg->param_type_begin(),
1438 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001439 }
Mike Stump11289f42009-09-09 15:08:12 +00001440
John McCalle78aac42010-03-10 03:28:59 +00001441 case Type::InjectedClassName: {
1442 // Treat a template's injected-class-name as if the template
1443 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001444 Param = cast<InjectedClassNameType>(Param)
1445 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001446 assert(isa<TemplateSpecializationType>(Param) &&
1447 "injected class name is not a template specialization type");
1448 // fall through
1449 }
1450
Douglas Gregor705c9002009-06-26 20:57:09 +00001451 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001452 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001453 // TT<T>
1454 // TT<i>
1455 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001456 case Type::TemplateSpecialization: {
1457 const TemplateSpecializationType *SpecParam
1458 = cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001459
Douglas Gregore81f3e72009-07-07 23:09:34 +00001460 // Try to deduce template arguments from the template-id.
1461 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001462 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregore81f3e72009-07-07 23:09:34 +00001463 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001464
Douglas Gregor42909752009-09-30 22:13:51 +00001465 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001466 // C++ [temp.deduct.call]p3b3:
1467 // If P is a class, and P has the form template-id, then A can be a
1468 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump11289f42009-09-09 15:08:12 +00001469 // class of the form template-id, A can be a pointer to a derived
Douglas Gregore81f3e72009-07-07 23:09:34 +00001470 // class pointed to by the deduced A.
1471 //
1472 // More importantly:
Mike Stump11289f42009-09-09 15:08:12 +00001473 // These alternatives are considered only if type deduction would
Douglas Gregore81f3e72009-07-07 23:09:34 +00001474 // otherwise fail.
Chandler Carruthc1263112010-02-07 21:33:28 +00001475 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1476 // We cannot inspect base classes as part of deduction when the type
1477 // is incomplete, so either instantiate any templates necessary to
1478 // complete the type, or skip over it if it cannot be completed.
John McCallbc077cf2010-02-08 23:07:23 +00001479 if (S.RequireCompleteType(Info.getLocation(), Arg, 0))
Chandler Carruthc1263112010-02-07 21:33:28 +00001480 return Result;
1481
Douglas Gregore81f3e72009-07-07 23:09:34 +00001482 // Use data recursion to crawl through the list of base classes.
Mike Stump11289f42009-09-09 15:08:12 +00001483 // Visited contains the set of nodes we have already visited, while
Douglas Gregore81f3e72009-07-07 23:09:34 +00001484 // ToVisit is our stack of records that we still need to visit.
1485 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001486 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001487 ToVisit.push_back(RecordT);
1488 bool Successful = false;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001489 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1490 Deduced.end());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001491 while (!ToVisit.empty()) {
1492 // Retrieve the next class in the inheritance hierarchy.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001493 const RecordType *NextT = ToVisit.pop_back_val();
Mike Stump11289f42009-09-09 15:08:12 +00001494
Douglas Gregore81f3e72009-07-07 23:09:34 +00001495 // If we have already seen this type, skip it.
David Blaikie82e95a32014-11-19 07:49:47 +00001496 if (!Visited.insert(NextT).second)
Douglas Gregore81f3e72009-07-07 23:09:34 +00001497 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001498
Douglas Gregore81f3e72009-07-07 23:09:34 +00001499 // If this is a base class, try to perform template argument
1500 // deduction from it.
1501 if (NextT != RecordT) {
Richard Trieu23bafad2012-11-07 21:17:13 +00001502 TemplateDeductionInfo BaseInfo(Info.getLocation());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001503 Sema::TemplateDeductionResult BaseResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001504 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Richard Trieu23bafad2012-11-07 21:17:13 +00001505 QualType(NextT, 0), BaseInfo,
1506 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001507
Douglas Gregore81f3e72009-07-07 23:09:34 +00001508 // If template argument deduction for this base was successful,
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001509 // note that we had some success. Otherwise, ignore any deductions
1510 // from this base class.
1511 if (BaseResult == Sema::TDK_Success) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001512 Successful = true;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001513 DeducedOrig.clear();
1514 DeducedOrig.append(Deduced.begin(), Deduced.end());
Richard Trieu23bafad2012-11-07 21:17:13 +00001515 Info.Param = BaseInfo.Param;
1516 Info.FirstArg = BaseInfo.FirstArg;
1517 Info.SecondArg = BaseInfo.SecondArg;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001518 }
1519 else
1520 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001521 }
Mike Stump11289f42009-09-09 15:08:12 +00001522
Douglas Gregore81f3e72009-07-07 23:09:34 +00001523 // Visit base classes
1524 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
Aaron Ballman574705e2014-03-13 15:41:46 +00001525 for (const auto &Base : Next->bases()) {
1526 assert(Base.getType()->isRecordType() &&
Douglas Gregore81f3e72009-07-07 23:09:34 +00001527 "Base class that isn't a record?");
Aaron Ballman574705e2014-03-13 15:41:46 +00001528 ToVisit.push_back(Base.getType()->getAs<RecordType>());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001529 }
1530 }
Mike Stump11289f42009-09-09 15:08:12 +00001531
Douglas Gregore81f3e72009-07-07 23:09:34 +00001532 if (Successful)
1533 return Sema::TDK_Success;
1534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
Douglas Gregore81f3e72009-07-07 23:09:34 +00001536 }
Mike Stump11289f42009-09-09 15:08:12 +00001537
Douglas Gregore81f3e72009-07-07 23:09:34 +00001538 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001539 }
1540
Douglas Gregor637d9982009-06-10 23:47:09 +00001541 // T type::*
1542 // T T::*
1543 // T (type::*)()
1544 // type (T::*)()
1545 // type (type::*)(T)
1546 // type (T::*)(T)
1547 // T (type::*)(T)
1548 // T (T::*)()
1549 // T (T::*)(T)
1550 case Type::MemberPointer: {
1551 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1552 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1553 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001554 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001555
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001556 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001557 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1558 MemPtrParam->getPointeeType(),
1559 MemPtrArg->getPointeeType(),
1560 Info, Deduced,
1561 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001562 return Result;
1563
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001564 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1565 QualType(MemPtrParam->getClass(), 0),
1566 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001567 Info, Deduced,
1568 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001569 }
1570
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001571 // (clang extension)
1572 //
Mike Stump11289f42009-09-09 15:08:12 +00001573 // type(^)(T)
1574 // T(^)()
1575 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001576 case Type::BlockPointer: {
1577 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1578 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001579
Anders Carlssona767eee2009-06-12 16:23:10 +00001580 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001581 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001582
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001583 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1584 BlockPtrParam->getPointeeType(),
1585 BlockPtrArg->getPointeeType(),
1586 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001587 }
1588
Douglas Gregor39c02722011-06-15 16:02:29 +00001589 // (clang extension)
1590 //
1591 // T __attribute__(((ext_vector_type(<integral constant>))))
1592 case Type::ExtVector: {
1593 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1594 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1595 // Make sure that the vectors have the same number of elements.
1596 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1597 return Sema::TDK_NonDeducedMismatch;
1598
1599 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001600 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1601 VectorParam->getElementType(),
1602 VectorArg->getElementType(),
1603 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001604 }
1605
1606 if (const DependentSizedExtVectorType *VectorArg
1607 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1608 // We can't check the number of elements, since the argument has a
1609 // dependent number of elements. This can only occur during partial
1610 // ordering.
1611
1612 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001613 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1614 VectorParam->getElementType(),
1615 VectorArg->getElementType(),
1616 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001617 }
1618
1619 return Sema::TDK_NonDeducedMismatch;
1620 }
1621
1622 // (clang extension)
1623 //
1624 // T __attribute__(((ext_vector_type(N))))
1625 case Type::DependentSizedExtVector: {
1626 const DependentSizedExtVectorType *VectorParam
1627 = cast<DependentSizedExtVectorType>(Param);
1628
1629 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1630 // Perform deduction on the element types.
1631 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001632 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1633 VectorParam->getElementType(),
1634 VectorArg->getElementType(),
1635 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001636 return Result;
1637
1638 // Perform deduction on the vector size, if we can.
1639 NonTypeTemplateParmDecl *NTTP
1640 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1641 if (!NTTP)
1642 return Sema::TDK_Success;
1643
1644 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1645 ArgSize = VectorArg->getNumElements();
1646 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1647 false, Info, Deduced);
1648 }
1649
1650 if (const DependentSizedExtVectorType *VectorArg
1651 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1652 // Perform deduction on the element types.
1653 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001654 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1655 VectorParam->getElementType(),
1656 VectorArg->getElementType(),
1657 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001658 return Result;
1659
1660 // Perform deduction on the vector size, if we can.
1661 NonTypeTemplateParmDecl *NTTP
1662 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1663 if (!NTTP)
1664 return Sema::TDK_Success;
1665
1666 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1667 Info, Deduced);
1668 }
1669
1670 return Sema::TDK_NonDeducedMismatch;
1671 }
1672
Douglas Gregor637d9982009-06-10 23:47:09 +00001673 case Type::TypeOfExpr:
1674 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001675 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001676 case Type::UnresolvedUsing:
1677 case Type::Decltype:
1678 case Type::UnaryTransform:
1679 case Type::Auto:
1680 case Type::DependentTemplateSpecialization:
1681 case Type::PackExpansion:
Douglas Gregor637d9982009-06-10 23:47:09 +00001682 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001683 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001684 }
1685
David Blaikiee4d798f2012-01-20 21:50:17 +00001686 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001687}
1688
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001689static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001690DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001691 TemplateParameterList *TemplateParams,
1692 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001693 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001694 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001695 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001696 // If the template argument is a pack expansion, perform template argument
1697 // deduction against the pattern of that expansion. This only occurs during
1698 // partial ordering.
1699 if (Arg.isPackExpansion())
1700 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001701
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001702 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001703 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001704 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001705
1706 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001707 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001708 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1709 Param.getAsType(),
1710 Arg.getAsType(),
1711 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001712 Info.FirstArg = Param;
1713 Info.SecondArg = Arg;
1714 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001715
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001716 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001717 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001718 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001719 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001720 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001721 Info.FirstArg = Param;
1722 Info.SecondArg = Arg;
1723 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001724
1725 case TemplateArgument::TemplateExpansion:
1726 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001728 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001729 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001730 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001731 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:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001965 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001966
1967 case TemplateArgument::NullPtr:
1968 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001969
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001970 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001971 case TemplateArgument::TemplateExpansion:
1972 return Context.getCanonicalTemplateName(
1973 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1974 Context.getCanonicalTemplateName(
1975 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976
Douglas Gregor705c9002009-06-26 20:57:09 +00001977 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001978 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001979
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001980 case TemplateArgument::Expression: {
1981 llvm::FoldingSetNodeID XID, YID;
1982 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001983 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001984 return XID == YID;
1985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
Douglas Gregor705c9002009-06-26 20:57:09 +00001987 case TemplateArgument::Pack:
1988 if (X.pack_size() != Y.pack_size())
1989 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001990
1991 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1992 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001993 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001994 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001995 if (!isSameTemplateArg(Context, *XP, *YP))
1996 return false;
1997
1998 return true;
1999 }
2000
David Blaikiee4d798f2012-01-20 21:50:17 +00002001 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002002}
2003
Douglas Gregorca4686d2011-01-04 23:35:54 +00002004/// \brief Allocate a TemplateArgumentLoc where all locations have
2005/// been initialized to the given location.
2006///
2007/// \param S The semantic analysis object.
2008///
James Dennett634962f2012-06-14 21:40:34 +00002009/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002010/// location information for.
2011///
2012/// \param NTTPType For a declaration template argument, the type of
2013/// the non-type template parameter that corresponds to this template
2014/// argument.
2015///
2016/// \param Loc The source location to use for the resulting template
2017/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002018static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00002019getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002020 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002021 QualType NTTPType,
2022 SourceLocation Loc) {
2023 switch (Arg.getKind()) {
2024 case TemplateArgument::Null:
2025 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002026
Douglas Gregorca4686d2011-01-04 23:35:54 +00002027 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002029 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030
Douglas Gregorca4686d2011-01-04 23:35:54 +00002031 case TemplateArgument::Declaration: {
2032 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00002033 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002034 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002035 return TemplateArgumentLoc(TemplateArgument(E), E);
2036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002037
Eli Friedmanb826a002012-09-26 02:36:12 +00002038 case TemplateArgument::NullPtr: {
2039 Expr *E
2040 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002041 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002042 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2043 E);
2044 }
2045
Douglas Gregorca4686d2011-01-04 23:35:54 +00002046 case TemplateArgument::Integral: {
2047 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002048 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002049 return TemplateArgumentLoc(TemplateArgument(E), E);
2050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002051
Douglas Gregor9d802122011-03-02 17:09:35 +00002052 case TemplateArgument::Template:
2053 case TemplateArgument::TemplateExpansion: {
2054 NestedNameSpecifierLocBuilder Builder;
2055 TemplateName Template = Arg.getAsTemplate();
2056 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2057 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002058 else if (QualifiedTemplateName *QTN =
2059 Template.getAsQualifiedTemplateName())
Douglas Gregor9d802122011-03-02 17:09:35 +00002060 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.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003003 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003004 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
Nico Weberc153d242014-07-28 00:02:09 +00003232static bool
3233hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3234 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003235
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,
Nico Weberc153d242014-07-28 00:02:09 +00003491 NumExplicitlySpecified, Specialization,
3492 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;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003582 if (getLangOpts().CPlusPlus14 && 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
Nico Weberc153d242014-07-28 00:02:09 +00003791 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003792 // 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
Nico Weberc153d242014-07-28 00:02:09 +00003845 // to a ptr-to-function, use the deduced arguments from the conversion
3846 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003847 // 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:
Nico Weberc153d242014-07-28 00:02:09 +00003910 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3911 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3912 Replacement(Replacement) {}
3913
Richard Smith30482bc2011-02-20 03:19:35 +00003914 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3915 // If we're building the type pattern to deduce against, don't wrap the
3916 // substituted type in an AutoType. Certain template deduction rules
3917 // apply only when a template type parameter appears directly (and not if
3918 // the parameter is found through desugaring). For instance:
3919 // auto &&lref = lvalue;
3920 // must transform into "rvalue reference to T" not "rvalue reference to
3921 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003922 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003923 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003924 TemplateTypeParmTypeLoc NewTL =
3925 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003926 NewTL.setNameLoc(TL.getNameLoc());
3927 return Result;
3928 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003929 bool Dependent =
3930 !Replacement.isNull() && Replacement->isDependentType();
3931 QualType Result =
3932 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3933 TL.getTypePtr()->isDecltypeAuto(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003934 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003935 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3936 NewTL.setNameLoc(TL.getNameLoc());
3937 return Result;
3938 }
3939 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003940
3941 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3942 // Lambdas never need to be transformed.
3943 return E;
3944 }
Richard Smith061f1e22013-04-30 21:23:01 +00003945
Richard Smith2a7d4812013-05-04 07:00:32 +00003946 QualType Apply(TypeLoc TL) {
3947 // Create some scratch storage for the transformed type locations.
3948 // FIXME: We're just going to throw this information away. Don't build it.
3949 TypeLocBuilder TLB;
3950 TLB.reserve(TL.getFullDataSize());
3951 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003952 }
Richard Smith30482bc2011-02-20 03:19:35 +00003953 };
3954}
3955
Richard Smith2a7d4812013-05-04 07:00:32 +00003956Sema::DeduceAutoResult
3957Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3958 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3959}
3960
Richard Smith061f1e22013-04-30 21:23:01 +00003961/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003962///
3963/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003964/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003965/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003966/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003967Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003968Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003969 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003970 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3971 if (NonPlaceholder.isInvalid())
3972 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003973 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003974 }
3975
Richard Smith2a7d4812013-05-04 07:00:32 +00003976 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003977 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003978 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003979 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00003980 }
3981
Richard Smith74aeef52013-04-26 16:15:35 +00003982 // If this is a 'decltype(auto)' specifier, do the decltype dance.
3983 // Since 'decltype(auto)' can only occur at the top of the type, we
3984 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00003985 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00003986 if (AT->isDecltypeAuto()) {
3987 if (isa<InitListExpr>(Init)) {
3988 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
3989 return DAR_FailedAlreadyDiagnosed;
3990 }
3991
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003992 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
Richard Smith74aeef52013-04-26 16:15:35 +00003993 // FIXME: Support a non-canonical deduced type for 'auto'.
3994 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00003995 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003996 if (Result.isNull())
3997 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00003998 return DAR_Succeeded;
3999 }
4000 }
4001
Richard Smith30482bc2011-02-20 03:19:35 +00004002 SourceLocation Loc = Init->getExprLoc();
4003
4004 LocalInstantiationScope InstScope(*this);
4005
4006 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004007 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004008 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4009 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004010 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4011 NamedDecl *TemplParamPtr = TemplParam;
Richard Smithb2bc2e62011-02-21 20:05:19 +00004012 FixedSizeTemplateParameterList<1> TemplateParams(Loc, Loc, &TemplParamPtr,
4013 Loc);
4014
Richard Smith061f1e22013-04-30 21:23:01 +00004015 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4016 assert(!FuncParam.isNull() &&
4017 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004018
4019 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004020 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004021 Deduced.resize(1);
4022 QualType InitType = Init->getType();
4023 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004024
Craig Toppere6706e42012-09-19 02:26:47 +00004025 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004026
Richard Smith74801c82012-07-08 04:13:07 +00004027 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004028 if (InitList) {
4029 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith74801c82012-07-08 04:13:07 +00004030 if (DeduceTemplateArgumentByListElement(*this, &TemplateParams,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004031 TemplArg,
4032 InitList->getInit(i),
4033 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004034 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004035 }
4036 } else {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004037 if (AdjustFunctionParmAndArgTypesForDeduction(*this, &TemplateParams,
4038 FuncParam, InitType, Init,
4039 TDF))
4040 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004041
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004042 if (DeduceTemplateArgumentsByTypeMatch(*this, &TemplateParams, FuncParam,
4043 InitType, Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004044 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004045 }
Richard Smith30482bc2011-02-20 03:19:35 +00004046
Eli Friedmane4310952012-11-06 23:56:42 +00004047 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004048 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004049
Eli Friedmane4310952012-11-06 23:56:42 +00004050 QualType DeducedType = Deduced[0].getAsType();
4051
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004052 if (InitList) {
4053 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4054 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004055 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004056 }
4057
Richard Smith061f1e22013-04-30 21:23:01 +00004058 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004059 if (Result.isNull())
4060 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004061
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004062 // Check that the deduced argument type is compatible with the original
4063 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004064 if (!InitList && !Result.isNull() &&
4065 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004066 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004067 Result)) {
4068 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004069 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004070 }
4071
Sebastian Redl09edce02012-01-23 22:09:39 +00004072 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004073}
4074
Faisal Vali2b391ab2013-09-26 19:54:12 +00004075QualType Sema::SubstAutoType(QualType TypeWithAuto,
4076 QualType TypeToReplaceAuto) {
4077 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4078 TransformType(TypeWithAuto);
4079}
4080
4081TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4082 QualType TypeToReplaceAuto) {
4083 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4084 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004085}
4086
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004087void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4088 if (isa<InitListExpr>(Init))
4089 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004090 VDecl->isInitCapture()
4091 ? diag::err_init_capture_deduction_failure_from_init_list
4092 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004093 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4094 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004095 Diag(VDecl->getLocation(),
4096 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4097 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004098 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4099 << Init->getSourceRange();
4100}
4101
Richard Smith2a7d4812013-05-04 07:00:32 +00004102bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4103 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004104 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004105
4106 if (FD->getTemplateInstantiationPattern())
4107 InstantiateFunctionDefinition(Loc, FD);
4108
Alp Toker314cc812014-01-25 16:55:45 +00004109 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004110 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4111 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4112 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4113 }
4114
4115 return StillUndeduced;
4116}
4117
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004118static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004119MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004120 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004121 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004122 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004123
4124/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004125static void
4126AddImplicitObjectParameterType(ASTContext &Context,
4127 CXXMethodDecl *Method,
4128 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004129 // C++11 [temp.func.order]p3:
4130 // [...] The new parameter is of type "reference to cv A," where cv are
4131 // the cv-qualifiers of the function template (if any) and A is
4132 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004133 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004134 // The standard doesn't say explicitly, but we pick the appropriate kind of
4135 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004136 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4137 ArgTy = Context.getQualifiedType(ArgTy,
4138 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004139 if (Method->getRefQualifier() == RQ_RValue)
4140 ArgTy = Context.getRValueReferenceType(ArgTy);
4141 else
4142 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004143 ArgTypes.push_back(ArgTy);
4144}
4145
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004146/// \brief Determine whether the function template \p FT1 is at least as
4147/// specialized as \p FT2.
4148static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004149 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004150 FunctionTemplateDecl *FT1,
4151 FunctionTemplateDecl *FT2,
4152 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004153 unsigned NumCallArguments1,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004154 SmallVectorImpl<RefParamPartialOrderingComparison> *RefParamComparisons) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004155 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004156 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004157 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4158 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004159
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004160 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4161 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004162 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004163 Deduced.resize(TemplateParams->size());
4164
4165 // C++0x [temp.deduct.partial]p3:
4166 // The types used to determine the ordering depend on the context in which
4167 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004168 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004169 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004170 switch (TPOC) {
4171 case TPOC_Call: {
4172 // - In the context of a function call, the function parameter types are
4173 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004174 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4175 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004176
Eli Friedman3b5774a2012-09-19 23:27:04 +00004177 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004178 // [...] If only one of the function templates is a non-static
4179 // member, that function template is considered to have a new
4180 // first parameter inserted in its function parameter list. The
4181 // new parameter is of type "reference to cv A," where cv are
4182 // the cv-qualifiers of the function template (if any) and A is
4183 // the class of which the function template is a member.
4184 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004185 // Note that we interpret this to mean "if one of the function
4186 // templates is a non-static member and the other is a non-member";
4187 // otherwise, the ordering rules for static functions against non-static
4188 // functions don't make any sense.
4189 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004190 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4191 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004192 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004193
Richard Smithe5b52202013-09-11 00:52:39 +00004194 unsigned NumComparedArguments = NumCallArguments1;
4195
4196 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004197 // Compare 'this' from Method1 against first parameter from Method2.
4198 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4199 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004200 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004201 // Compare 'this' from Method2 against first parameter from Method1.
4202 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004203 }
4204
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004205 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004206 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004207 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004208 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004209
Douglas Gregorb837ea42011-01-11 17:34:58 +00004210 // C++ [temp.func.order]p5:
4211 // The presence of unused ellipsis and default arguments has no effect on
4212 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004213 if (Args1.size() > NumComparedArguments)
4214 Args1.resize(NumComparedArguments);
4215 if (Args2.size() > NumComparedArguments)
4216 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004217 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4218 Args1.data(), Args1.size(), Info, Deduced,
4219 TDF_None, /*PartialOrdering=*/true,
Douglas Gregor63814022011-01-21 17:29:42 +00004220 RefParamComparisons))
Richard Smith0a80d572014-05-29 01:12:14 +00004221 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004223 break;
4224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004226 case TPOC_Conversion:
4227 // - In the context of a call to a conversion operator, the return types
4228 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004229 if (DeduceTemplateArgumentsByTypeMatch(
4230 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4231 Info, Deduced, TDF_None,
4232 /*PartialOrdering=*/true, RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004233 return false;
4234 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004236 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004237 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004238 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004239 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4240 FD2->getType(), FD1->getType(),
4241 Info, Deduced, TDF_None,
4242 /*PartialOrdering=*/true,
4243 RefParamComparisons))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004244 return false;
4245 break;
4246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004248 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004249 // In most cases, all template parameters must have values in order for
4250 // deduction to succeed, but for partial ordering purposes a template
4251 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004252 // types being used for partial ordering. [ Note: a template parameter used
4253 // in a non-deduced context is considered used. -end note]
4254 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4255 for (; ArgIdx != NumArgs; ++ArgIdx)
4256 if (Deduced[ArgIdx].isNull())
4257 break;
4258
4259 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004261 // as FT2.
4262 return true;
4263 }
4264
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004265 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004266 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004267 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004268 case TPOC_Call:
4269 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4270 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004271 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004272 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004273 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004274
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004275 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004276 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4277 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004278 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004279
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004280 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004281 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004282 TemplateParams->getDepth(),
4283 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004284 break;
4285 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004286
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004287 for (; ArgIdx != NumArgs; ++ArgIdx)
4288 // If this argument had no value deduced but was used in one of the types
4289 // used for partial ordering, then deduction fails.
4290 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4291 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004293 return true;
4294}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004295
Douglas Gregorcef1a032011-01-16 16:03:23 +00004296/// \brief Determine whether this a function template whose parameter-type-list
4297/// ends with a function parameter pack.
4298static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4299 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4300 unsigned NumParams = Function->getNumParams();
4301 if (NumParams == 0)
4302 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004303
Douglas Gregorcef1a032011-01-16 16:03:23 +00004304 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4305 if (!Last->isParameterPack())
4306 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregorcef1a032011-01-16 16:03:23 +00004308 // Make sure that no previous parameter is a parameter pack.
4309 while (--NumParams > 0) {
4310 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4311 return false;
4312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Douglas Gregorcef1a032011-01-16 16:03:23 +00004314 return true;
4315}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004316
Douglas Gregorbe999392009-09-15 16:23:51 +00004317/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004318/// to the rules of function template partial ordering (C++ [temp.func.order]).
4319///
4320/// \param FT1 the first function template
4321///
4322/// \param FT2 the second function template
4323///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004324/// \param TPOC the context in which we are performing partial ordering of
4325/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004326///
Richard Smithe5b52202013-09-11 00:52:39 +00004327/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4328/// only when \c TPOC is \c TPOC_Call.
4329///
4330/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4331/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004332///
Douglas Gregorbe999392009-09-15 16:23:51 +00004333/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004334/// template is more specialized, returns NULL.
4335FunctionTemplateDecl *
4336Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4337 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004338 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004339 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004340 unsigned NumCallArguments1,
4341 unsigned NumCallArguments2) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004342 SmallVector<RefParamPartialOrderingComparison, 4> RefParamComparisons;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Craig Topperc3ec1492014-05-26 06:22:03 +00004344 NumCallArguments1, nullptr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004346 NumCallArguments2,
Douglas Gregor63814022011-01-21 17:29:42 +00004347 &RefParamComparisons);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004349 if (Better1 != Better2) // We have a clear winner
4350 return Better1? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004352 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004353 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004354
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004355 // C++0x [temp.deduct.partial]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356 // If for each type being considered a given template is at least as
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004357 // specialized for all types and more specialized for some set of types and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358 // the other template is not more specialized for any types or is not at
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004359 // least as specialized for any types, then the given template is more
4360 // specialized than the other template. Otherwise, neither template is more
4361 // specialized than the other.
4362 Better1 = false;
4363 Better2 = false;
Douglas Gregor63814022011-01-21 17:29:42 +00004364 for (unsigned I = 0, N = RefParamComparisons.size(); I != N; ++I) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004365 // C++0x [temp.deduct.partial]p9:
4366 // If, for a given type, deduction succeeds in both directions (i.e., the
Douglas Gregor63814022011-01-21 17:29:42 +00004367 // types are identical after the transformations above) and both P and A
4368 // were reference types (before being replaced with the type referred to
4369 // above):
4370
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371 // -- if the type from the argument template was an lvalue reference
Douglas Gregor63814022011-01-21 17:29:42 +00004372 // and the type from the parameter template was not, the argument
4373 // type is considered to be more specialized than the other;
4374 // otherwise,
4375 if (!RefParamComparisons[I].ArgIsRvalueRef &&
4376 RefParamComparisons[I].ParamIsRvalueRef) {
4377 Better2 = true;
4378 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004379 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004380 continue;
4381 } else if (!RefParamComparisons[I].ParamIsRvalueRef &&
4382 RefParamComparisons[I].ArgIsRvalueRef) {
4383 Better1 = true;
4384 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004385 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004386 continue;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004388
Douglas Gregor63814022011-01-21 17:29:42 +00004389 // -- if the type from the argument template is more cv-qualified than
4390 // the type from the parameter template (as described above), the
4391 // argument type is considered to be more specialized than the
4392 // other; otherwise,
4393 switch (RefParamComparisons[I].Qualifiers) {
4394 case NeitherMoreQualified:
4395 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396
Douglas Gregor63814022011-01-21 17:29:42 +00004397 case ParamMoreQualified:
4398 Better1 = true;
4399 if (Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004400 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004401 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402
Douglas Gregor63814022011-01-21 17:29:42 +00004403 case ArgMoreQualified:
4404 Better2 = true;
4405 if (Better1)
Craig Topperc3ec1492014-05-26 06:22:03 +00004406 return nullptr;
Douglas Gregor63814022011-01-21 17:29:42 +00004407 continue;
4408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409
Douglas Gregor63814022011-01-21 17:29:42 +00004410 // -- neither type is more specialized than the other.
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004413 assert(!(Better1 && Better2) && "Should have broken out in the loop above");
Douglas Gregor05155d82009-08-21 23:19:43 +00004414 if (Better1)
4415 return FT1;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004416 else if (Better2)
4417 return FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418
Douglas Gregorcef1a032011-01-16 16:03:23 +00004419 // FIXME: This mimics what GCC implements, but doesn't match up with the
4420 // proposed resolution for core issue 692. This area needs to be sorted out,
4421 // but for now we attempt to maintain compatibility.
4422 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4423 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4424 if (Variadic1 != Variadic2)
4425 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426
Craig Topperc3ec1492014-05-26 06:22:03 +00004427 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004428}
Douglas Gregor9b146582009-07-08 20:55:45 +00004429
Douglas Gregor450f00842009-09-25 18:43:00 +00004430/// \brief Determine if the two templates are equivalent.
4431static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4432 if (T1 == T2)
4433 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434
Douglas Gregor450f00842009-09-25 18:43:00 +00004435 if (!T1 || !T2)
4436 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437
Douglas Gregor450f00842009-09-25 18:43:00 +00004438 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4439}
4440
4441/// \brief Retrieve the most specialized of the given function template
4442/// specializations.
4443///
John McCall58cc69d2010-01-27 01:50:18 +00004444/// \param SpecBegin the start iterator of the function template
4445/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004446///
John McCall58cc69d2010-01-27 01:50:18 +00004447/// \param SpecEnd the end iterator of the function template
4448/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004449///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004451/// diagnostic should occur.
4452///
4453/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4454/// no matching candidates.
4455///
4456/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4457/// occurs.
4458///
4459/// \param CandidateDiag partial diagnostic used for each function template
4460/// specialization that is a candidate in the ambiguous ordering. One parameter
4461/// in this diagnostic should be unbound, which will correspond to the string
4462/// describing the template arguments for the function template specialization.
4463///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004465/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004466UnresolvedSetIterator Sema::getMostSpecialized(
4467 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4468 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004469 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4470 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4471 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004472 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004473 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004474 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004475 FailedCandidates.NoteCandidates(*this, Loc);
4476 }
John McCall58cc69d2010-01-27 01:50:18 +00004477 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479
4480 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004481 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
Douglas Gregor450f00842009-09-25 18:43:00 +00004483 // Find the function template that is better than all of the templates it
4484 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004485 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004486 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004487 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004488 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004489 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4490 FunctionTemplateDecl *Challenger
4491 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004492 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004493 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004494 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004495 Challenger)) {
4496 Best = I;
4497 BestTemplate = Challenger;
4498 }
4499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004500
Douglas Gregor450f00842009-09-25 18:43:00 +00004501 // Make sure that the "best" function template is more specialized than all
4502 // of the others.
4503 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004504 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4505 FunctionTemplateDecl *Challenger
4506 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004507 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004509 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004510 BestTemplate)) {
4511 Ambiguous = true;
4512 break;
4513 }
4514 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004515
Douglas Gregor450f00842009-09-25 18:43:00 +00004516 if (!Ambiguous) {
4517 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004518 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004519 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520
Douglas Gregor450f00842009-09-25 18:43:00 +00004521 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004522 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004523 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004524
Richard Smithb875c432013-05-04 01:51:08 +00004525 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004526 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4527 PartialDiagnostic PD = CandidateDiag;
4528 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004529 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004530 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004531 if (!TargetType.isNull())
4532 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4533 TargetType);
4534 Diag((*I)->getLocation(), PD);
4535 }
Richard Smithb875c432013-05-04 01:51:08 +00004536 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004537
John McCall58cc69d2010-01-27 01:50:18 +00004538 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004539}
4540
Douglas Gregorbe999392009-09-15 16:23:51 +00004541/// \brief Returns the more specialized class template partial specialization
4542/// according to the rules of partial ordering of class template partial
4543/// specializations (C++ [temp.class.order]).
4544///
4545/// \param PS1 the first class template partial specialization
4546///
4547/// \param PS2 the second class template partial specialization
4548///
4549/// \returns the more specialized class template partial specialization. If
4550/// neither partial specialization is more specialized, returns NULL.
4551ClassTemplatePartialSpecializationDecl *
4552Sema::getMoreSpecializedPartialSpecialization(
4553 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004554 ClassTemplatePartialSpecializationDecl *PS2,
4555 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004556 // C++ [temp.class.order]p1:
4557 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004558 // specialized as the second if, given the following rewrite to two
4559 // function templates, the first function template is at least as
4560 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004561 // templates (14.6.6.2):
4562 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563 // first partial specialization and has a single function parameter
4564 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004565 // arguments of the first partial specialization, and
4566 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004567 // second partial specialization and has a single function parameter
4568 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004569 // arguments of the second partial specialization.
4570 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004571 // Rather than synthesize function templates, we merely perform the
4572 // equivalent partial ordering by performing deduction directly on
4573 // the template arguments of the class template partial
4574 // specializations. This computation is slightly simpler than the
4575 // general problem of function template partial ordering, because
4576 // class template partial specializations are more constrained. We
4577 // know that every template parameter is deducible from the class
4578 // template partial specialization's template arguments, for
4579 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004580 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004581 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004582
4583 QualType PT1 = PS1->getInjectedSpecializationType();
4584 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585
Douglas Gregorbe999392009-09-15 16:23:51 +00004586 // Determine whether PS1 is at least as specialized as PS2
4587 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004588 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4589 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004590 PT2, PT1, Info, Deduced, TDF_None,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004592 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004593 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004594 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004595 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004596 Better1 = !::FinishTemplateArgumentDeduction(
4597 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4598 }
4599
4600 // Determine whether PS2 is at least as specialized as PS1
4601 Deduced.clear();
4602 Deduced.resize(PS1->getTemplateParameters()->size());
4603 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4604 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
4605 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004606 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004607 if (Better2) {
4608 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4609 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004610 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004611 Better2 = !::FinishTemplateArgumentDeduction(
4612 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4613 }
4614
4615 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004616 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004617
4618 return Better1 ? PS1 : PS2;
4619}
4620
Larisse Voufo30616382013-08-23 22:21:36 +00004621/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4622/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4623/// VarTemplate(Partial)SpecializationDecl with a new data
4624/// structure Template(Partial)SpecializationDecl, and
4625/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004626VarTemplatePartialSpecializationDecl *
4627Sema::getMoreSpecializedPartialSpecialization(
4628 VarTemplatePartialSpecializationDecl *PS1,
4629 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4630 SmallVector<DeducedTemplateArgument, 4> Deduced;
4631 TemplateDeductionInfo Info(Loc);
4632
Richard Smithf04fd0b2013-12-12 23:14:16 +00004633 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004634 "the partial specializations being compared should specialize"
4635 " the same template.");
4636 TemplateName Name(PS1->getSpecializedTemplate());
4637 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4638 QualType PT1 = Context.getTemplateSpecializationType(
4639 CanonTemplate, PS1->getTemplateArgs().data(),
4640 PS1->getTemplateArgs().size());
4641 QualType PT2 = Context.getTemplateSpecializationType(
4642 CanonTemplate, PS2->getTemplateArgs().data(),
4643 PS2->getTemplateArgs().size());
4644
4645 // Determine whether PS1 is at least as specialized as PS2
4646 Deduced.resize(PS2->getTemplateParameters()->size());
4647 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4648 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
4649 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004650 /*RefParamComparisons=*/nullptr);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004651 if (Better1) {
4652 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4653 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004654 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004655 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4656 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004657 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004659
Douglas Gregorbe999392009-09-15 16:23:51 +00004660 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004661 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004662 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004663 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4664 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004665 PT1, PT2, Info, Deduced, TDF_None,
4666 /*PartialOrdering=*/true,
Craig Topperc3ec1492014-05-26 06:22:03 +00004667 /*RefParamComparisons=*/nullptr);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004668 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004669 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004670 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4672 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004673 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004675
Douglas Gregorbe999392009-09-15 16:23:51 +00004676 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004677 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004678
Douglas Gregorbe999392009-09-15 16:23:51 +00004679 return Better1? PS1 : PS2;
4680}
4681
Mike Stump11289f42009-09-09 15:08:12 +00004682static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004683MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004684 const TemplateArgument &TemplateArg,
4685 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004686 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004687 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004688
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004689/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004690/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004691static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004692MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004693 const Expr *E,
4694 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004695 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004696 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004697 // We can deduce from a pack expansion.
4698 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4699 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700
Richard Smith34349002012-07-09 03:07:20 +00004701 // Skip through any implicit casts we added while type-checking, and any
4702 // substitutions performed by template alias expansion.
4703 while (1) {
4704 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4705 E = ICE->getSubExpr();
4706 else if (const SubstNonTypeTemplateParmExpr *Subst =
4707 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4708 E = Subst->getReplacement();
4709 else
4710 break;
4711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004712
4713 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004714 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004715 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004716 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004717 return;
4718
Mike Stump11289f42009-09-09 15:08:12 +00004719 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004720 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4721 if (!NTTP)
4722 return;
4723
Douglas Gregor21610382009-10-29 00:04:11 +00004724 if (NTTP->getDepth() == Depth)
4725 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004726}
4727
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004728/// \brief Mark the template parameters that are used by the given
4729/// nested name specifier.
4730static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004731MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004732 NestedNameSpecifier *NNS,
4733 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004734 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004735 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004736 if (!NNS)
4737 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004739 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004740 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004741 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004742 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004743}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004745/// \brief Mark the template parameters that are used by the given
4746/// template name.
4747static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004748MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004749 TemplateName Name,
4750 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004751 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004752 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004753 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4754 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004755 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4756 if (TTP->getDepth() == Depth)
4757 Used[TTP->getIndex()] = true;
4758 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004759 return;
4760 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004762 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004763 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004764 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004765 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004766 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004767 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004768}
4769
4770/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004771/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004772static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004773MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004774 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004775 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004776 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004777 if (T.isNull())
4778 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004779
Douglas Gregor91772d12009-06-13 00:26:55 +00004780 // Non-dependent types have nothing deducible
4781 if (!T->isDependentType())
4782 return;
4783
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004784 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004785 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004786 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004787 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004788 cast<PointerType>(T)->getPointeeType(),
4789 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004790 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004791 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004792 break;
4793
4794 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004795 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004796 cast<BlockPointerType>(T)->getPointeeType(),
4797 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004798 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004799 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004800 break;
4801
4802 case Type::LValueReference:
4803 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004804 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004805 cast<ReferenceType>(T)->getPointeeType(),
4806 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004807 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004808 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004809 break;
4810
4811 case Type::MemberPointer: {
4812 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004813 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004814 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004815 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004816 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004817 break;
4818 }
4819
4820 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004821 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004822 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004823 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004824 // Fall through to check the element type
4825
4826 case Type::ConstantArray:
4827 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004828 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004829 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004830 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004831 break;
4832
4833 case Type::Vector:
4834 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004835 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004836 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004837 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004838 break;
4839
Douglas Gregor758a8692009-06-17 21:51:59 +00004840 case Type::DependentSizedExtVector: {
4841 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004842 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004843 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004844 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004845 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004846 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004847 break;
4848 }
4849
Douglas Gregor91772d12009-06-13 00:26:55 +00004850 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004851 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004852 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4853 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004854 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4855 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004856 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004857 break;
4858 }
4859
Douglas Gregor21610382009-10-29 00:04:11 +00004860 case Type::TemplateTypeParm: {
4861 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4862 if (TTP->getDepth() == Depth)
4863 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004864 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004865 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004866
Douglas Gregorfb322d82011-01-14 05:11:40 +00004867 case Type::SubstTemplateTypeParmPack: {
4868 const SubstTemplateTypeParmPackType *Subst
4869 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004870 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004871 QualType(Subst->getReplacedParameter(), 0),
4872 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004873 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004874 OnlyDeduced, Depth, Used);
4875 break;
4876 }
4877
John McCall2408e322010-04-27 00:57:59 +00004878 case Type::InjectedClassName:
4879 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4880 // fall through
4881
Douglas Gregor91772d12009-06-13 00:26:55 +00004882 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004883 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004884 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004885 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004886 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004887
Douglas Gregord0ad2942010-12-23 01:24:45 +00004888 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004889 // If the template argument list of P contains a pack expansion that is
4890 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004891 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004892 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004893 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4894 break;
4895
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004896 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004897 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004898 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004899 break;
4900 }
4901
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004902 case Type::Complex:
4903 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004904 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004905 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004906 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004907 break;
4908
Eli Friedman0dfb8892011-10-06 23:00:33 +00004909 case Type::Atomic:
4910 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004911 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004912 cast<AtomicType>(T)->getValueType(),
4913 OnlyDeduced, Depth, Used);
4914 break;
4915
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004916 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004917 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004918 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004919 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004920 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004921 break;
4922
John McCallc392f372010-06-11 00:33:02 +00004923 case Type::DependentTemplateSpecialization: {
4924 const DependentTemplateSpecializationType *Spec
4925 = cast<DependentTemplateSpecializationType>(T);
4926 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004927 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
John McCallc392f372010-06-11 00:33:02 +00004928 OnlyDeduced, Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004929
Douglas Gregord0ad2942010-12-23 01:24:45 +00004930 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004931 // If the template argument list of P contains a pack expansion that is not
4932 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004933 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004934 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004935 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4936 break;
4937
John McCallc392f372010-06-11 00:33:02 +00004938 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004939 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004940 Used);
4941 break;
4942 }
4943
John McCallbd8d9bd2010-03-01 23:49:17 +00004944 case Type::TypeOf:
4945 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004946 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004947 cast<TypeOfType>(T)->getUnderlyingType(),
4948 OnlyDeduced, Depth, Used);
4949 break;
4950
4951 case Type::TypeOfExpr:
4952 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004953 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004954 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4955 OnlyDeduced, Depth, Used);
4956 break;
4957
4958 case Type::Decltype:
4959 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004960 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004961 cast<DecltypeType>(T)->getUnderlyingExpr(),
4962 OnlyDeduced, Depth, Used);
4963 break;
4964
Alexis Hunte852b102011-05-24 22:41:36 +00004965 case Type::UnaryTransform:
4966 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004967 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004968 cast<UnaryTransformType>(T)->getUnderlyingType(),
4969 OnlyDeduced, Depth, Used);
4970 break;
4971
Douglas Gregord2fa7662010-12-20 02:24:11 +00004972 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004973 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004974 cast<PackExpansionType>(T)->getPattern(),
4975 OnlyDeduced, Depth, Used);
4976 break;
4977
Richard Smith30482bc2011-02-20 03:19:35 +00004978 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004979 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004980 cast<AutoType>(T)->getDeducedType(),
4981 OnlyDeduced, Depth, Used);
4982
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004983 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004984 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004985 case Type::VariableArray:
4986 case Type::FunctionNoProto:
4987 case Type::Record:
4988 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004989 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004990 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004991 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004992 case Type::UnresolvedUsing:
Douglas Gregor91772d12009-06-13 00:26:55 +00004993#define TYPE(Class, Base)
4994#define ABSTRACT_TYPE(Class, Base)
4995#define DEPENDENT_TYPE(Class, Base)
4996#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4997#include "clang/AST/TypeNodes.def"
4998 break;
4999 }
5000}
5001
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005002/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005003/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005004static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005005MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005006 const TemplateArgument &TemplateArg,
5007 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005008 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005009 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005010 switch (TemplateArg.getKind()) {
5011 case TemplateArgument::Null:
5012 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005013 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005014 break;
Mike Stump11289f42009-09-09 15:08:12 +00005015
Eli Friedmanb826a002012-09-26 02:36:12 +00005016 case TemplateArgument::NullPtr:
5017 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5018 Depth, Used);
5019 break;
5020
Douglas Gregor91772d12009-06-13 00:26:55 +00005021 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005022 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005023 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005024 break;
5025
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005026 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005027 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005028 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005029 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005030 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005031 break;
5032
5033 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005034 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005035 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005036 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005037
Anders Carlssonbc343912009-06-15 17:04:53 +00005038 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005039 for (const auto &P : TemplateArg.pack_elements())
5040 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005041 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005042 }
5043}
5044
James Dennett41725122012-06-22 10:16:05 +00005045/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005046/// template argument list.
5047///
5048/// \param TemplateArgs the template argument list from which template
5049/// parameters will be deduced.
5050///
James Dennett41725122012-06-22 10:16:05 +00005051/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005052/// to indicate when the corresponding template parameter will be
5053/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005054void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005055Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005056 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005057 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005058 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005059 // If the template argument list of P contains a pack expansion that is not
5060 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005061 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005063 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5064 return;
5065
Douglas Gregor91772d12009-06-13 00:26:55 +00005066 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005067 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005068 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005069}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005070
5071/// \brief Marks all of the template parameters that will be deduced by a
5072/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005073void Sema::MarkDeducedTemplateParameters(
5074 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5075 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}