blob: 3bfa34c63f5d3c4f09bf46c5f725132fefe68168 [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 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +000061}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000062
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 Gregor7baabef2010-12-22 18:17:10 +000094static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +000095DeduceTemplateArgumentsByTypeMatch(Sema &S,
96 TemplateParameterList *TemplateParams,
97 QualType Param,
98 QualType Arg,
99 TemplateDeductionInfo &Info,
100 SmallVectorImpl<DeducedTemplateArgument> &
101 Deduced,
102 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000103 bool PartialOrdering = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000104
105static Sema::TemplateDeductionResult
106DeduceTemplateArguments(Sema &S,
107 TemplateParameterList *TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000108 const TemplateArgument *Params, unsigned NumParams,
109 const TemplateArgument *Args, unsigned NumArgs,
110 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +0000111 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000112
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000113/// \brief If the given expression is of a form that permits the deduction
114/// of a non-type template parameter, return the declaration of that
115/// non-type template parameter.
116static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000117 // If we are within an alias template, the expression may have undergone
118 // any number of parameter substitutions already.
119 while (1) {
120 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
121 E = IC->getSubExpr();
122 else if (SubstNonTypeTemplateParmExpr *Subst =
123 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
124 E = Subst->getReplacement();
125 else
126 break;
127 }
Mike Stump11289f42009-09-09 15:08:12 +0000128
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000129 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
130 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000131
Craig Topperc3ec1492014-05-26 06:22:03 +0000132 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000133}
134
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000135/// \brief Determine whether two declaration pointers refer to the same
136/// declaration.
137static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000138 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
139 X = NX->getUnderlyingDecl();
140 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
141 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000142
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000143 return X->getCanonicalDecl() == Y->getCanonicalDecl();
144}
145
146/// \brief Verify that the given, deduced template arguments are compatible.
147///
148/// \returns The deduced template argument, or a NULL template argument if
149/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000150static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000151checkDeducedTemplateArguments(ASTContext &Context,
152 const DeducedTemplateArgument &X,
153 const DeducedTemplateArgument &Y) {
154 // We have no deduction for one or both of the arguments; they're compatible.
155 if (X.isNull())
156 return Y;
157 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000158 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000159
160 switch (X.getKind()) {
161 case TemplateArgument::Null:
162 llvm_unreachable("Non-deduced template arguments handled above");
163
164 case TemplateArgument::Type:
165 // If two template type arguments have the same type, they're compatible.
166 if (Y.getKind() == TemplateArgument::Type &&
167 Context.hasSameType(X.getAsType(), Y.getAsType()))
168 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000169
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000170 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000171
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000172 case TemplateArgument::Integral:
173 // If we deduced a constant in one case and either a dependent expression or
174 // declaration in another case, keep the integral constant.
175 // If both are integral constants with the same value, keep that value.
176 if (Y.getKind() == TemplateArgument::Expression ||
177 Y.getKind() == TemplateArgument::Declaration ||
178 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000179 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000180 return DeducedTemplateArgument(X,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000181 X.wasDeducedFromArrayBound() &&
182 Y.wasDeducedFromArrayBound());
183
184 // All other combinations are incompatible.
185 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000186
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000187 case TemplateArgument::Template:
188 if (Y.getKind() == TemplateArgument::Template &&
189 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
190 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000191
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000192 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000194
195 case TemplateArgument::TemplateExpansion:
196 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000197 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000198 Y.getAsTemplateOrTemplatePattern()))
199 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000200
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000201 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000202 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000203
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000204 case TemplateArgument::Expression:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000205 // If we deduced a dependent expression in one case and either an integral
206 // constant or a declaration in another case, keep the integral constant
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000207 // or declaration.
208 if (Y.getKind() == TemplateArgument::Integral ||
209 Y.getKind() == TemplateArgument::Declaration)
210 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
211 Y.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000213 if (Y.getKind() == TemplateArgument::Expression) {
214 // Compare the expressions for equality
215 llvm::FoldingSetNodeID ID1, ID2;
216 X.getAsExpr()->Profile(ID1, Context, true);
217 Y.getAsExpr()->Profile(ID2, Context, true);
218 if (ID1 == ID2)
219 return X;
220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000222 // All other combinations are incompatible.
223 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000225 case TemplateArgument::Declaration:
226 // If we deduced a declaration and a dependent expression, keep the
227 // declaration.
228 if (Y.getKind() == TemplateArgument::Expression)
229 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000230
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000231 // If we deduced a declaration and an integral constant, keep the
232 // integral constant.
233 if (Y.getKind() == TemplateArgument::Integral)
234 return Y;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000235
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000236 // If we deduced two declarations, make sure they they refer to the
237 // same declaration.
238 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000239 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000240 return X;
241
242 // All other combinations are incompatible.
243 return DeducedTemplateArgument();
244
245 case TemplateArgument::NullPtr:
246 // If we deduced a null pointer and a dependent expression, keep the
247 // null pointer.
248 if (Y.getKind() == TemplateArgument::Expression)
249 return X;
250
251 // If we deduced a null pointer and an integral constant, keep the
252 // integral constant.
253 if (Y.getKind() == TemplateArgument::Integral)
254 return Y;
255
256 // If we deduced two null pointers, make sure they have the same type.
257 if (Y.getKind() == TemplateArgument::NullPtr &&
258 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000259 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000260
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000261 // All other combinations are incompatible.
262 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000263
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000264 case TemplateArgument::Pack:
265 if (Y.getKind() != TemplateArgument::Pack ||
266 X.pack_size() != Y.pack_size())
267 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000268
269 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000270 XAEnd = X.pack_end(),
271 YA = Y.pack_begin();
272 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000273 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000274 if (checkDeducedTemplateArguments(Context,
275 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000276 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
277 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000278 return DeducedTemplateArgument();
279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000280
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000281 return X;
282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000283
David Blaikiee4d798f2012-01-20 21:50:17 +0000284 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000285}
286
Mike Stump11289f42009-09-09 15:08:12 +0000287/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000288/// from the given constant.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000289static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
290 Sema &S, NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
291 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
292 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000293 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000294 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000295
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000296 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
297 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000298 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000299 Deduced[NTTP->getIndex()],
300 NewDeduced);
301 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000302 Info.Param = NTTP;
303 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000304 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000307
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000308 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000309 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000310}
311
Mike Stump11289f42009-09-09 15:08:12 +0000312/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000313/// from the given type- or value-dependent expression.
314///
315/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000316static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000317DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000318 NonTypeTemplateParmDecl *NTTP,
319 Expr *Value,
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");
324 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
325 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000326
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000327 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000328 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
329 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000330 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000332 if (Result.isNull()) {
333 Info.Param = NTTP;
334 Info.FirstArg = Deduced[NTTP->getIndex()];
335 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000336 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000337 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000338
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000339 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000340 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000341}
342
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000343/// \brief Deduce the value of the given non-type template parameter
344/// from the given declaration.
345///
346/// \returns true if deduction succeeded, false otherwise.
347static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000348DeduceNonTypeTemplateArgument(Sema &S,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000349 NonTypeTemplateParmDecl *NTTP,
350 ValueDecl *D,
351 TemplateDeductionInfo &Info,
352 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000353 assert(NTTP->getDepth() == 0 &&
354 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
Craig Topperc3ec1492014-05-26 06:22:03 +0000356 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
David Blaikie0f62c8d2014-10-16 04:21:25 +0000357 TemplateArgument New(D, NTTP->getType());
Eli Friedmanb826a002012-09-26 02:36:12 +0000358 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000360 Deduced[NTTP->getIndex()],
361 NewDeduced);
362 if (Result.isNull()) {
363 Info.Param = NTTP;
364 Info.FirstArg = Deduced[NTTP->getIndex()];
365 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000366 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000368
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000369 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000370 return Sema::TDK_Success;
371}
372
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000373static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000374DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000375 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000376 TemplateName Param,
377 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000378 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000379 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000380 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000381 if (!ParamDecl) {
382 // The parameter type is dependent and is not a template template parameter,
383 // so there is nothing that we can deduce.
384 return Sema::TDK_Success;
385 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386
Douglas Gregoradee3e32009-11-11 23:06:43 +0000387 if (TemplateTemplateParmDecl *TempParam
388 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000389 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000391 Deduced[TempParam->getIndex()],
392 NewDeduced);
393 if (Result.isNull()) {
394 Info.Param = TempParam;
395 Info.FirstArg = Deduced[TempParam->getIndex()];
396 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000397 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000399
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000400 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000401 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000403
Douglas Gregoradee3e32009-11-11 23:06:43 +0000404 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000405 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000406 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000407
Douglas Gregoradee3e32009-11-11 23:06:43 +0000408 // Mismatch of non-dependent template parameter to argument.
409 Info.FirstArg = TemplateArgument(Param);
410 Info.SecondArg = TemplateArgument(Arg);
411 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000412}
413
Mike Stump11289f42009-09-09 15:08:12 +0000414/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000415/// type (which is a template-id) with the template argument type.
416///
Chandler Carruthc1263112010-02-07 21:33:28 +0000417/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000418///
419/// \param TemplateParams the template parameters that we are deducing
420///
421/// \param Param the parameter type
422///
423/// \param Arg the argument type
424///
425/// \param Info information about the template argument deduction itself
426///
427/// \param Deduced the deduced template arguments
428///
429/// \returns the result of template argument deduction so far. Note that a
430/// "success" result means that template argument deduction has not yet failed,
431/// but it may still fail, later, for other reasons.
432static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000433DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000434 TemplateParameterList *TemplateParams,
435 const TemplateSpecializationType *Param,
436 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000437 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000438 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000439 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000440
Douglas Gregore81f3e72009-07-07 23:09:34 +0000441 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000442 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000443 = dyn_cast<TemplateSpecializationType>(Arg)) {
444 // Perform template argument deduction for the template name.
445 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000446 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000447 Param->getTemplateName(),
448 SpecArg->getTemplateName(),
449 Info, Deduced))
450 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000451
Mike Stump11289f42009-09-09 15:08:12 +0000452
Douglas Gregore81f3e72009-07-07 23:09:34 +0000453 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000454 // argument. Ignore any missing/extra arguments, since they could be
455 // filled in by default arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000456 return DeduceTemplateArguments(S, TemplateParams,
457 Param->getArgs(), Param->getNumArgs(),
Douglas Gregord80ea202010-12-22 18:55:49 +0000458 SpecArg->getArgs(), SpecArg->getNumArgs(),
Richard Smith16b65392012-12-06 06:44:44 +0000459 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000460 }
Mike Stump11289f42009-09-09 15:08:12 +0000461
Douglas Gregore81f3e72009-07-07 23:09:34 +0000462 // If the argument type is a class template specialization, we
463 // perform template argument deduction using its template
464 // arguments.
465 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000466 if (!RecordArg) {
467 Info.FirstArg = TemplateArgument(QualType(Param, 0));
468 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000469 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000470 }
Mike Stump11289f42009-09-09 15:08:12 +0000471
472 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000473 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000474 if (!SpecArg) {
475 Info.FirstArg = TemplateArgument(QualType(Param, 0));
476 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000477 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000478 }
Mike Stump11289f42009-09-09 15:08:12 +0000479
Douglas Gregore81f3e72009-07-07 23:09:34 +0000480 // Perform template argument deduction for the template name.
481 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000482 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000483 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000484 Param->getTemplateName(),
485 TemplateName(SpecArg->getSpecializedTemplate()),
486 Info, Deduced))
487 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000488
Douglas Gregor7baabef2010-12-22 18:17:10 +0000489 // Perform template argument deduction for the template arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000491 Param->getArgs(), Param->getNumArgs(),
492 SpecArg->getTemplateArgs().data(),
493 SpecArg->getTemplateArgs().size(),
494 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000495}
496
John McCall08569062010-08-28 22:14:41 +0000497/// \brief Determines whether the given type is an opaque type that
498/// might be more qualified when instantiated.
499static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
500 switch (T->getTypeClass()) {
501 case Type::TypeOfExpr:
502 case Type::TypeOf:
503 case Type::DependentName:
504 case Type::Decltype:
505 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000506 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000507 return true;
508
509 case Type::ConstantArray:
510 case Type::IncompleteArray:
511 case Type::VariableArray:
512 case Type::DependentSizedArray:
513 return IsPossiblyOpaquelyQualifiedType(
514 cast<ArrayType>(T)->getElementType());
515
516 default:
517 return false;
518 }
519}
520
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000521/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000522static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000523getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000524 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
525 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000526
Douglas Gregor5499af42011-01-05 23:12:31 +0000527 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
528 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529
Douglas Gregor5499af42011-01-05 23:12:31 +0000530 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
531 return std::make_pair(TTP->getDepth(), TTP->getIndex());
532}
533
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000534/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000535static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000536getDepthAndIndex(UnexpandedParameterPack UPP) {
537 if (const TemplateTypeParmType *TTP
538 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
539 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000541 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
542}
543
Douglas Gregor5499af42011-01-05 23:12:31 +0000544/// \brief Helper function to build a TemplateParameter when we don't
545/// know its type statically.
546static TemplateParameter makeTemplateParameter(Decl *D) {
547 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
548 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000549 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000550 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
Douglas Gregor5499af42011-01-05 23:12:31 +0000552 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
553}
554
Richard Smith0a80d572014-05-29 01:12:14 +0000555/// A pack that we're currently deducing.
556struct clang::DeducedPack {
557 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000558
Richard Smith0a80d572014-05-29 01:12:14 +0000559 // The index of the pack.
560 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000561
Richard Smith0a80d572014-05-29 01:12:14 +0000562 // The old value of the pack before we started deducing it.
563 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000564
Richard Smith0a80d572014-05-29 01:12:14 +0000565 // A deferred value of this pack from an inner deduction, that couldn't be
566 // deduced because this deduction hadn't happened yet.
567 DeducedTemplateArgument DeferredDeduction;
568
569 // The new value of the pack.
570 SmallVector<DeducedTemplateArgument, 4> New;
571
572 // The outer deduction for this pack, if any.
573 DeducedPack *Outer;
574};
575
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000576namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000577/// A scope in which we're performing pack deduction.
578class PackDeductionScope {
579public:
580 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
581 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
582 TemplateDeductionInfo &Info, TemplateArgument Pattern)
583 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
584 // Compute the set of template parameter indices that correspond to
585 // parameter packs expanded by the pack expansion.
586 {
587 llvm::SmallBitVector SawIndices(TemplateParams->size());
588 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
589 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
590 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
591 unsigned Depth, Index;
592 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
593 if (Depth == 0 && !SawIndices[Index]) {
594 SawIndices[Index] = true;
595
596 // Save the deduced template argument for the parameter pack expanded
597 // by this pack expansion, then clear out the deduction.
598 DeducedPack Pack(Index);
599 Pack.Saved = Deduced[Index];
600 Deduced[Index] = TemplateArgument();
601
602 Packs.push_back(Pack);
603 }
604 }
605 }
606 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
607
608 for (auto &Pack : Packs) {
609 if (Info.PendingDeducedPacks.size() > Pack.Index)
610 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
611 else
612 Info.PendingDeducedPacks.resize(Pack.Index + 1);
613 Info.PendingDeducedPacks[Pack.Index] = &Pack;
614
615 if (S.CurrentInstantiationScope) {
616 // If the template argument pack was explicitly specified, add that to
617 // the set of deduced arguments.
618 const TemplateArgument *ExplicitArgs;
619 unsigned NumExplicitArgs;
620 NamedDecl *PartiallySubstitutedPack =
621 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
622 &ExplicitArgs, &NumExplicitArgs);
623 if (PartiallySubstitutedPack &&
624 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
625 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
626 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000627 }
628 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000629
Richard Smith0a80d572014-05-29 01:12:14 +0000630 ~PackDeductionScope() {
631 for (auto &Pack : Packs)
632 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000634
Richard Smith0a80d572014-05-29 01:12:14 +0000635 /// Move to deducing the next element in each pack that is being deduced.
636 void nextPackElement() {
637 // Capture the deduced template arguments for each parameter pack expanded
638 // by this pack expansion, add them to the list of arguments we've deduced
639 // for that pack, then clear out the deduced argument.
640 for (auto &Pack : Packs) {
641 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
642 if (!DeducedArg.isNull()) {
643 Pack.New.push_back(DeducedArg);
644 DeducedArg = DeducedTemplateArgument();
645 }
646 }
647 }
648
649 /// \brief Finish template argument deduction for a set of argument packs,
650 /// producing the argument packs and checking for consistency with prior
651 /// deductions.
652 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
653 // Build argument packs for each of the parameter packs expanded by this
654 // pack expansion.
655 for (auto &Pack : Packs) {
656 // Put back the old value for this pack.
657 Deduced[Pack.Index] = Pack.Saved;
658
659 // Build or find a new value for this pack.
660 DeducedTemplateArgument NewPack;
661 if (HasAnyArguments && Pack.New.empty()) {
662 if (Pack.DeferredDeduction.isNull()) {
663 // We were not able to deduce anything for this parameter pack
664 // (because it only appeared in non-deduced contexts), so just
665 // restore the saved argument pack.
666 continue;
667 }
668
669 NewPack = Pack.DeferredDeduction;
670 Pack.DeferredDeduction = TemplateArgument();
671 } else if (Pack.New.empty()) {
672 // If we deduced an empty argument pack, create it now.
673 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
674 } else {
675 TemplateArgument *ArgumentPack =
676 new (S.Context) TemplateArgument[Pack.New.size()];
677 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
678 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000679 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000680 Pack.New[0].wasDeducedFromArrayBound());
681 }
682
683 // Pick where we're going to put the merged pack.
684 DeducedTemplateArgument *Loc;
685 if (Pack.Outer) {
686 if (Pack.Outer->DeferredDeduction.isNull()) {
687 // Defer checking this pack until we have a complete pack to compare
688 // it against.
689 Pack.Outer->DeferredDeduction = NewPack;
690 continue;
691 }
692 Loc = &Pack.Outer->DeferredDeduction;
693 } else {
694 Loc = &Deduced[Pack.Index];
695 }
696
697 // Check the new pack matches any previous value.
698 DeducedTemplateArgument OldPack = *Loc;
699 DeducedTemplateArgument Result =
700 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
701
702 // If we deferred a deduction of this pack, check that one now too.
703 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
704 OldPack = Result;
705 NewPack = Pack.DeferredDeduction;
706 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
707 }
708
709 if (Result.isNull()) {
710 Info.Param =
711 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
712 Info.FirstArg = OldPack;
713 Info.SecondArg = NewPack;
714 return Sema::TDK_Inconsistent;
715 }
716
717 *Loc = Result;
718 }
719
720 return Sema::TDK_Success;
721 }
722
723private:
724 Sema &S;
725 TemplateParameterList *TemplateParams;
726 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
727 TemplateDeductionInfo &Info;
728
729 SmallVector<DeducedPack, 2> Packs;
730};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000731} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000732
Douglas Gregor5499af42011-01-05 23:12:31 +0000733/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000734/// types to the list of argument types, as in the parameter-type-lists of
735/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000736///
737/// \param S The semantic analysis object within which we are deducing
738///
739/// \param TemplateParams The template parameters that we are deducing
740///
741/// \param Params The list of parameter types
742///
743/// \param NumParams The number of types in \c Params
744///
745/// \param Args The list of argument types
746///
747/// \param NumArgs The number of types in \c Args
748///
749/// \param Info information about the template argument deduction itself
750///
751/// \param Deduced the deduced template arguments
752///
753/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
754/// how template argument deduction is performed.
755///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000756/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000757/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000758/// (C++0x [temp.deduct.partial]).
759///
Douglas Gregor5499af42011-01-05 23:12:31 +0000760/// \returns the result of template argument deduction so far. Note that a
761/// "success" result means that template argument deduction has not yet failed,
762/// but it may still fail, later, for other reasons.
763static Sema::TemplateDeductionResult
764DeduceTemplateArguments(Sema &S,
765 TemplateParameterList *TemplateParams,
766 const QualType *Params, unsigned NumParams,
767 const QualType *Args, unsigned NumArgs,
768 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000769 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000770 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000771 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000772 // Fast-path check to see if we have too many/too few arguments.
773 if (NumParams != NumArgs &&
774 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
775 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000776 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777
Douglas Gregor5499af42011-01-05 23:12:31 +0000778 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000779 // Similarly, if P has a form that contains (T), then each parameter type
780 // Pi of the respective parameter-type- list of P is compared with the
781 // corresponding parameter type Ai of the corresponding parameter-type-list
782 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000783 unsigned ArgIdx = 0, ParamIdx = 0;
784 for (; ParamIdx != NumParams; ++ParamIdx) {
785 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000786 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000787 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
788 if (!Expansion) {
789 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000790
Douglas Gregor5499af42011-01-05 23:12:31 +0000791 // Make sure we have an argument.
792 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000793 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000794
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000795 if (isa<PackExpansionType>(Args[ArgIdx])) {
796 // C++0x [temp.deduct.type]p22:
797 // If the original function parameter associated with A is a function
798 // parameter pack and the function parameter associated with P is not
799 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000800 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000801 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802
Douglas Gregor5499af42011-01-05 23:12:31 +0000803 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000804 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
805 Params[ParamIdx], Args[ArgIdx],
806 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000807 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000808 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809
Douglas Gregor5499af42011-01-05 23:12:31 +0000810 ++ArgIdx;
811 continue;
812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000814 // C++0x [temp.deduct.type]p5:
815 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000817 // parameter-declaration-clause.
818 if (ParamIdx + 1 < NumParams)
819 return Sema::TDK_Success;
820
Douglas Gregor5499af42011-01-05 23:12:31 +0000821 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000823 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000825 // comparison deduces template arguments for subsequent positions in the
826 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Douglas Gregor5499af42011-01-05 23:12:31 +0000828 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000829 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830
Douglas Gregor5499af42011-01-05 23:12:31 +0000831 bool HasAnyArguments = false;
832 for (; ArgIdx < NumArgs; ++ArgIdx) {
833 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000834
Douglas Gregor5499af42011-01-05 23:12:31 +0000835 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000836 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000837 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
838 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000839 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000840 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000841
Richard Smith0a80d572014-05-29 01:12:14 +0000842 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Douglas Gregor5499af42011-01-05 23:12:31 +0000845 // Build argument packs for each of the parameter packs expanded by this
846 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000847 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000850
Douglas Gregor5499af42011-01-05 23:12:31 +0000851 // Make sure we don't have any extra arguments.
852 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000853 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000854
Douglas Gregor5499af42011-01-05 23:12:31 +0000855 return Sema::TDK_Success;
856}
857
Douglas Gregor1d684c22011-04-28 00:56:09 +0000858/// \brief Determine whether the parameter has qualifiers that are either
859/// inconsistent with or a superset of the argument's qualifiers.
860static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
861 QualType ArgType) {
862 Qualifiers ParamQs = ParamType.getQualifiers();
863 Qualifiers ArgQs = ArgType.getQualifiers();
864
865 if (ParamQs == ArgQs)
866 return false;
867
868 // Mismatched (but not missing) Objective-C GC attributes.
869 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
870 ParamQs.hasObjCGCAttr())
871 return true;
872
873 // Mismatched (but not missing) address spaces.
874 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
875 ParamQs.hasAddressSpace())
876 return true;
877
John McCall31168b02011-06-15 23:02:42 +0000878 // Mismatched (but not missing) Objective-C lifetime qualifiers.
879 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
880 ParamQs.hasObjCLifetime())
881 return true;
882
Douglas Gregor1d684c22011-04-28 00:56:09 +0000883 // CVR qualifier superset.
884 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
885 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
886 == ParamQs.getCVRQualifiers());
887}
888
Douglas Gregor19a41f12013-04-17 08:45:07 +0000889/// \brief Compare types for equality with respect to possibly compatible
890/// function types (noreturn adjustment, implicit calling conventions). If any
891/// of parameter and argument is not a function, just perform type comparison.
892///
893/// \param Param the template parameter type.
894///
895/// \param Arg the argument type.
896bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
897 CanQualType Arg) {
898 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
899 *ArgFunction = Arg->getAs<FunctionType>();
900
901 // Just compare if not functions.
902 if (!ParamFunction || !ArgFunction)
903 return Param == Arg;
904
905 // Noreturn adjustment.
906 QualType AdjustedParam;
907 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
908 return Arg == Context.getCanonicalType(AdjustedParam);
909
910 // FIXME: Compatible calling conventions.
911
912 return Param == Arg;
913}
914
Douglas Gregorcceb9752009-06-26 18:27:22 +0000915/// \brief Deduce the template arguments by comparing the parameter type and
916/// the argument type (C++ [temp.deduct.type]).
917///
Chandler Carruthc1263112010-02-07 21:33:28 +0000918/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000919///
920/// \param TemplateParams the template parameters that we are deducing
921///
922/// \param ParamIn the parameter type
923///
924/// \param ArgIn the argument type
925///
926/// \param Info information about the template argument deduction itself
927///
928/// \param Deduced the deduced template arguments
929///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000930/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000931/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000932///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000933/// \param PartialOrdering Whether we're performing template argument deduction
934/// in the context of partial ordering (C++0x [temp.deduct.partial]).
935///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000936/// \returns the result of template argument deduction so far. Note that a
937/// "success" result means that template argument deduction has not yet failed,
938/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000939static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000940DeduceTemplateArgumentsByTypeMatch(Sema &S,
941 TemplateParameterList *TemplateParams,
942 QualType ParamIn, QualType ArgIn,
943 TemplateDeductionInfo &Info,
944 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
945 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000946 bool PartialOrdering) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000947 // We only want to look at the canonical types, since typedefs and
948 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000949 QualType Param = S.Context.getCanonicalType(ParamIn);
950 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000951
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000952 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000953 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000954 if (const PackExpansionType *ArgExpansion
955 = dyn_cast<PackExpansionType>(Arg))
956 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000957
Douglas Gregorb837ea42011-01-11 17:34:58 +0000958 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000959 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000960 // Before the partial ordering is done, certain transformations are
961 // performed on the types used for partial ordering:
962 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +0000963 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
964 if (ParamRef)
965 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000966
Douglas Gregorb837ea42011-01-11 17:34:58 +0000967 // - If A is a reference type, A is replaced by the type referred to.
968 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
969 if (ArgRef)
970 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000971
Richard Smithed563c22015-02-20 04:45:22 +0000972 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
973 // C++11 [temp.deduct.partial]p9:
974 // If, for a given type, deduction succeeds in both directions (i.e.,
975 // the types are identical after the transformations above) and both
976 // P and A were reference types [...]:
977 // - if [one type] was an lvalue reference and [the other type] was
978 // not, [the other type] is not considered to be at least as
979 // specialized as [the first type]
980 // - if [one type] is more cv-qualified than [the other type],
981 // [the other type] is not considered to be at least as specialized
982 // as [the first type]
983 // Objective-C ARC adds:
984 // - [one type] has non-trivial lifetime, [the other type] has
985 // __unsafe_unretained lifetime, and the types are otherwise
986 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +0000987 //
Richard Smithed563c22015-02-20 04:45:22 +0000988 // A is "considered to be at least as specialized" as P iff deduction
989 // succeeds, so we model this as a deduction failure. Note that
990 // [the first type] is P and [the other type] is A here; the standard
991 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +0000992 Qualifiers ParamQuals = Param.getQualifiers();
993 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +0000994 if ((ParamRef->isLValueReferenceType() &&
995 !ArgRef->isLValueReferenceType()) ||
996 ParamQuals.isStrictSupersetOf(ArgQuals) ||
997 (ParamQuals.hasNonTrivialObjCLifetime() &&
998 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
999 ParamQuals.withoutObjCLifetime() ==
1000 ArgQuals.withoutObjCLifetime())) {
1001 Info.FirstArg = TemplateArgument(ParamIn);
1002 Info.SecondArg = TemplateArgument(ArgIn);
1003 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001004 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001005 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Richard Smithed563c22015-02-20 04:45:22 +00001007 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001008 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001010 // version of P.
1011 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001013 // version of A.
1014 Arg = Arg.getUnqualifiedType();
1015 } else {
1016 // C++0x [temp.deduct.call]p4 bullet 1:
1017 // - If the original P is a reference type, the deduced A (i.e., the type
1018 // referred to by the reference) can be more cv-qualified than the
1019 // transformed A.
1020 if (TDF & TDF_ParamWithReferenceType) {
1021 Qualifiers Quals;
1022 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1023 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001024 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001025 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1026 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001027
Douglas Gregor85f240c2011-01-25 17:19:08 +00001028 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1029 // C++0x [temp.deduct.type]p10:
1030 // If P and A are function types that originated from deduction when
1031 // taking the address of a function template (14.8.2.2) or when deducing
1032 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033 // Ai are parameters of the top-level parameter-type-list of P and A,
1034 // respectively, Pi is adjusted if it is an rvalue reference to a
1035 // cv-unqualified template parameter and Ai is an lvalue reference, in
1036 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001037 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1038 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001039 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001040 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001041
Douglas Gregor85f240c2011-01-25 17:19:08 +00001042 if (const RValueReferenceType *ParamRef
1043 = Param->getAs<RValueReferenceType>()) {
1044 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1045 !ParamRef->getPointeeType().getQualifiers())
1046 if (Arg->isLValueReferenceType())
1047 Param = ParamRef->getPointeeType();
1048 }
1049 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001050 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001051
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001052 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001053 // A template type argument T, a template template argument TT or a
1054 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001055 // the following forms:
1056 //
1057 // T
1058 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001059 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001060 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001061 // Just skip any attempts to deduce from a placeholder type.
1062 if (Arg->isPlaceholderType())
1063 return Sema::TDK_Success;
1064
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001065 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001066 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001067
Douglas Gregor60454822009-07-22 20:02:25 +00001068 // If the argument type is an array type, move the qualifiers up to the
1069 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001070 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001071 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001072 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001073 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001074 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001075 RecanonicalizeArg = true;
1076 }
1077 }
Mike Stump11289f42009-09-09 15:08:12 +00001078
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001079 // The argument type can not be less qualified than the parameter
1080 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001081 if (!(TDF & TDF_IgnoreQualifiers) &&
1082 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001083 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001084 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001085 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001086 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001087 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001088
1089 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001090 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001091 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001092
Douglas Gregor1d684c22011-04-28 00:56:09 +00001093 // Remove any qualifiers on the parameter from the deduced type.
1094 // We checked the qualifiers for consistency above.
1095 Qualifiers DeducedQs = DeducedType.getQualifiers();
1096 Qualifiers ParamQs = Param.getQualifiers();
1097 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1098 if (ParamQs.hasObjCGCAttr())
1099 DeducedQs.removeObjCGCAttr();
1100 if (ParamQs.hasAddressSpace())
1101 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001102 if (ParamQs.hasObjCLifetime())
1103 DeducedQs.removeObjCLifetime();
Douglas Gregore46db902011-06-17 22:11:49 +00001104
1105 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001106 // If template deduction would produce a lifetime qualifier on a type
1107 // that is not a lifetime type, template argument deduction fails.
1108 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1109 !DeducedType->isDependentType()) {
1110 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1111 Info.FirstArg = TemplateArgument(Param);
1112 Info.SecondArg = TemplateArgument(Arg);
1113 return Sema::TDK_Underqualified;
1114 }
1115
1116 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001117 // If template deduction would produce an argument type with lifetime type
1118 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001119 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001120 DeducedType->isObjCLifetimeType() &&
1121 !DeducedQs.hasObjCLifetime())
1122 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1123
Douglas Gregor1d684c22011-04-28 00:56:09 +00001124 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1125 DeducedQs);
1126
Douglas Gregord6605db2009-07-22 21:30:48 +00001127 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001128 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001129
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001130 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001131 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001132 Deduced[Index],
1133 NewDeduced);
1134 if (Result.isNull()) {
1135 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1136 Info.FirstArg = Deduced[Index];
1137 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001140
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001141 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001142 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001143 }
1144
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001145 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001146 Info.FirstArg = TemplateArgument(ParamIn);
1147 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001148
Douglas Gregorfb322d82011-01-14 05:11:40 +00001149 // If the parameter is an already-substituted template parameter
1150 // pack, do nothing: we don't know which of its arguments to look
1151 // at, so we have to wait until all of the parameter packs in this
1152 // expansion have arguments.
1153 if (isa<SubstTemplateTypeParmPackType>(Param))
1154 return Sema::TDK_Success;
1155
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001156 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001157 CanQualType CanParam = S.Context.getCanonicalType(Param);
1158 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001159 if (!(TDF & TDF_IgnoreQualifiers)) {
1160 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001161 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001162 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001163 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001164 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001165 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001166 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001167
1168 // If the parameter type is not dependent, there is nothing to deduce.
1169 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001170 if (!(TDF & TDF_SkipNonDependent)) {
1171 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1172 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1173 Param != Arg;
1174 if (NonDeduced) {
1175 return Sema::TDK_NonDeducedMismatch;
1176 }
1177 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001178 return Sema::TDK_Success;
1179 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001180 } else if (!Param->isDependentType()) {
1181 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1182 ArgUnqualType = CanArg.getUnqualifiedType();
1183 bool Success = (TDF & TDF_InOverloadResolution)?
1184 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1185 ArgUnqualType) :
1186 ParamUnqualType == ArgUnqualType;
1187 if (Success)
1188 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001189 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001190
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001191 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001192 // Non-canonical types cannot appear here.
1193#define NON_CANONICAL_TYPE(Class, Base) \
1194 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1195#define TYPE(Class, Base)
1196#include "clang/AST/TypeNodes.def"
1197
1198 case Type::TemplateTypeParm:
1199 case Type::SubstTemplateTypeParmPack:
1200 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001201
1202 // These types cannot be dependent, so simply check whether the types are
1203 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001204 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001205 case Type::VariableArray:
1206 case Type::Vector:
1207 case Type::FunctionNoProto:
1208 case Type::Record:
1209 case Type::Enum:
1210 case Type::ObjCObject:
1211 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001212 case Type::ObjCObjectPointer: {
1213 if (TDF & TDF_SkipNonDependent)
1214 return Sema::TDK_Success;
1215
1216 if (TDF & TDF_IgnoreQualifiers) {
1217 Param = Param.getUnqualifiedType();
1218 Arg = Arg.getUnqualifiedType();
1219 }
1220
1221 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1222 }
1223
Douglas Gregor39c02722011-06-15 16:02:29 +00001224 // _Complex T [placeholder extension]
1225 case Type::Complex:
1226 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001227 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor39c02722011-06-15 16:02:29 +00001228 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001229 ComplexArg->getElementType(),
1230 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001231
1232 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001233
1234 // _Atomic T [extension]
1235 case Type::Atomic:
1236 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001237 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001238 cast<AtomicType>(Param)->getValueType(),
1239 AtomicArg->getValueType(),
1240 Info, Deduced, TDF);
1241
1242 return Sema::TDK_NonDeducedMismatch;
1243
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001244 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001245 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001246 QualType PointeeType;
1247 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1248 PointeeType = PointerArg->getPointeeType();
1249 } else if (const ObjCObjectPointerType *PointerArg
1250 = Arg->getAs<ObjCObjectPointerType>()) {
1251 PointeeType = PointerArg->getPointeeType();
1252 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001253 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001254 }
Mike Stump11289f42009-09-09 15:08:12 +00001255
Douglas Gregorfc516c92009-06-26 23:27:24 +00001256 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001257 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1258 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001259 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001260 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001261 }
Mike Stump11289f42009-09-09 15:08:12 +00001262
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001263 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001264 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001265 const LValueReferenceType *ReferenceArg =
1266 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001267 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001268 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001269
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001270 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001271 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001272 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001273 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001274
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001275 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001276 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001277 const RValueReferenceType *ReferenceArg =
1278 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001279 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001280 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001281
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001282 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1283 cast<RValueReferenceType>(Param)->getPointeeType(),
1284 ReferenceArg->getPointeeType(),
1285 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001286 }
Mike Stump11289f42009-09-09 15:08:12 +00001287
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001288 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001289 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001290 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001291 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001292 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001293 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001294
John McCallf7332682010-08-19 00:20:19 +00001295 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001296 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1297 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1298 IncompleteArrayArg->getElementType(),
1299 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001300 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001301
1302 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001303 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001304 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001305 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001306 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001307 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001308
1309 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001310 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001311 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001312 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001313
John McCallf7332682010-08-19 00:20:19 +00001314 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001315 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1316 ConstantArrayParm->getElementType(),
1317 ConstantArrayArg->getElementType(),
1318 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001319 }
1320
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001321 // type [i]
1322 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001323 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001324 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001325 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001326
John McCallf7332682010-08-19 00:20:19 +00001327 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1328
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001329 // Check the element type of the arrays
1330 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001331 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001332 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001333 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1334 DependentArrayParm->getElementType(),
1335 ArrayArg->getElementType(),
1336 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001337 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001338
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001339 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001340 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001341 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1342 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001343 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001344
1345 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001346 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001347 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001348 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001349 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001350 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1351 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001352 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001353 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001354 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001355 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001356 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001357 if (const DependentSizedArrayType *DependentArrayArg
1358 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001359 if (DependentArrayArg->getSizeExpr())
1360 return DeduceNonTypeTemplateArgument(S, NTTP,
1361 DependentArrayArg->getSizeExpr(),
1362 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001364 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001365 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001366 }
Mike Stump11289f42009-09-09 15:08:12 +00001367
1368 // type(*)(T)
1369 // T(*)()
1370 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001371 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001372 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001373 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001374 dyn_cast<FunctionProtoType>(Arg);
1375 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001376 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001377
1378 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001379 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001380
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001382 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001384 != FunctionProtoArg->getRefQualifier() ||
1385 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001386 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001387
Anders Carlsson2128ec72009-06-08 15:19:08 +00001388 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001389 if (Sema::TemplateDeductionResult Result =
1390 DeduceTemplateArgumentsByTypeMatch(
1391 S, TemplateParams, FunctionProtoParam->getReturnType(),
1392 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001393 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001394
Alp Toker9cacbab2014-01-20 20:26:09 +00001395 return DeduceTemplateArguments(
1396 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1397 FunctionProtoParam->getNumParams(),
1398 FunctionProtoArg->param_type_begin(),
1399 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001400 }
Mike Stump11289f42009-09-09 15:08:12 +00001401
John McCalle78aac42010-03-10 03:28:59 +00001402 case Type::InjectedClassName: {
1403 // Treat a template's injected-class-name as if the template
1404 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001405 Param = cast<InjectedClassNameType>(Param)
1406 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001407 assert(isa<TemplateSpecializationType>(Param) &&
1408 "injected class name is not a template specialization type");
1409 // fall through
1410 }
1411
Douglas Gregor705c9002009-06-26 20:57:09 +00001412 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001413 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001414 // TT<T>
1415 // TT<i>
1416 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001417 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001418 const TemplateSpecializationType *SpecParam =
1419 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001420
Richard Smith9b296e32016-04-25 19:09:05 +00001421 // When Arg cannot be a derived class, we can just try to deduce template
1422 // arguments from the template-id.
1423 const RecordType *RecordT = Arg->getAs<RecordType>();
1424 if (!(TDF & TDF_DerivedClass) || !RecordT)
1425 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1426 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001427
Richard Smith9b296e32016-04-25 19:09:05 +00001428 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1429 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001430
Richard Smith9b296e32016-04-25 19:09:05 +00001431 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1432 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001433
Richard Smith9b296e32016-04-25 19:09:05 +00001434 if (Result == Sema::TDK_Success)
1435 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001436
Richard Smith9b296e32016-04-25 19:09:05 +00001437 // We cannot inspect base classes as part of deduction when the type
1438 // is incomplete, so either instantiate any templates necessary to
1439 // complete the type, or skip over it if it cannot be completed.
1440 if (!S.isCompleteType(Info.getLocation(), Arg))
1441 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001442
Richard Smith9b296e32016-04-25 19:09:05 +00001443 // C++14 [temp.deduct.call] p4b3:
1444 // If P is a class and P has the form simple-template-id, then the
1445 // transformed A can be a derived class of the deduced A. Likewise if
1446 // P is a pointer to a class of the form simple-template-id, the
1447 // transformed A can be a pointer to a derived class pointed to by the
1448 // deduced A.
1449 //
1450 // These alternatives are considered only if type deduction would
1451 // otherwise fail. If they yield more than one possible deduced A, the
1452 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001453
Faisal Vali683b0742016-05-19 02:28:21 +00001454 // Reset the incorrectly deduced argument from above.
1455 Deduced = DeducedOrig;
1456
1457 // Use data recursion to crawl through the list of base classes.
1458 // Visited contains the set of nodes we have already visited, while
1459 // ToVisit is our stack of records that we still need to visit.
1460 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1461 SmallVector<const RecordType *, 8> ToVisit;
1462 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001463 bool Successful = false;
Faisal Vali683b0742016-05-19 02:28:21 +00001464 while (!ToVisit.empty()) {
1465 // Retrieve the next class in the inheritance hierarchy.
1466 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001467
Faisal Vali683b0742016-05-19 02:28:21 +00001468 // If we have already seen this type, skip it.
1469 if (!Visited.insert(NextT).second)
1470 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001471
Faisal Vali683b0742016-05-19 02:28:21 +00001472 // If this is a base class, try to perform template argument
1473 // deduction from it.
1474 if (NextT != RecordT) {
1475 TemplateDeductionInfo BaseInfo(Info.getLocation());
1476 Sema::TemplateDeductionResult BaseResult =
1477 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1478 QualType(NextT, 0), BaseInfo, Deduced);
1479
1480 // If template argument deduction for this base was successful,
1481 // note that we had some success. Otherwise, ignore any deductions
1482 // from this base class.
1483 if (BaseResult == Sema::TDK_Success) {
1484 Successful = true;
1485 DeducedOrig.clear();
1486 DeducedOrig.append(Deduced.begin(), Deduced.end());
1487 Info.Param = BaseInfo.Param;
1488 Info.FirstArg = BaseInfo.FirstArg;
1489 Info.SecondArg = BaseInfo.SecondArg;
1490 } else
1491 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
Faisal Vali683b0742016-05-19 02:28:21 +00001494 // Visit base classes
1495 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1496 for (const auto &Base : Next->bases()) {
1497 assert(Base.getType()->isRecordType() &&
1498 "Base class that isn't a record?");
1499 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1500 }
1501 }
Mike Stump11289f42009-09-09 15:08:12 +00001502
Richard Smith9b296e32016-04-25 19:09:05 +00001503 if (Successful)
1504 return Sema::TDK_Success;
1505
Douglas Gregore81f3e72009-07-07 23:09:34 +00001506 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001507 }
1508
Douglas Gregor637d9982009-06-10 23:47:09 +00001509 // T type::*
1510 // T T::*
1511 // T (type::*)()
1512 // type (T::*)()
1513 // type (type::*)(T)
1514 // type (T::*)(T)
1515 // T (type::*)(T)
1516 // T (T::*)()
1517 // T (T::*)(T)
1518 case Type::MemberPointer: {
1519 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1520 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1521 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001522 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001523
David Majnemera381cda2015-11-30 20:34:28 +00001524 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1525 if (ParamPointeeType->isFunctionType())
1526 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1527 /*IsCtorOrDtor=*/false, Info.getLocation());
1528 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1529 if (ArgPointeeType->isFunctionType())
1530 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1531 /*IsCtorOrDtor=*/false, Info.getLocation());
1532
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001533 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001534 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001535 ParamPointeeType,
1536 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001537 Info, Deduced,
1538 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001539 return Result;
1540
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001541 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1542 QualType(MemPtrParam->getClass(), 0),
1543 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001544 Info, Deduced,
1545 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001546 }
1547
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001548 // (clang extension)
1549 //
Mike Stump11289f42009-09-09 15:08:12 +00001550 // type(^)(T)
1551 // T(^)()
1552 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001553 case Type::BlockPointer: {
1554 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1555 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001556
Anders Carlssona767eee2009-06-12 16:23:10 +00001557 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001558 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001559
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001560 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1561 BlockPtrParam->getPointeeType(),
1562 BlockPtrArg->getPointeeType(),
1563 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001564 }
1565
Douglas Gregor39c02722011-06-15 16:02:29 +00001566 // (clang extension)
1567 //
1568 // T __attribute__(((ext_vector_type(<integral constant>))))
1569 case Type::ExtVector: {
1570 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1571 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1572 // Make sure that the vectors have the same number of elements.
1573 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1574 return Sema::TDK_NonDeducedMismatch;
1575
1576 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001577 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1578 VectorParam->getElementType(),
1579 VectorArg->getElementType(),
1580 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001581 }
1582
1583 if (const DependentSizedExtVectorType *VectorArg
1584 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1585 // We can't check the number of elements, since the argument has a
1586 // dependent number of elements. This can only occur during partial
1587 // ordering.
1588
1589 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001590 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1591 VectorParam->getElementType(),
1592 VectorArg->getElementType(),
1593 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001594 }
1595
1596 return Sema::TDK_NonDeducedMismatch;
1597 }
1598
1599 // (clang extension)
1600 //
1601 // T __attribute__(((ext_vector_type(N))))
1602 case Type::DependentSizedExtVector: {
1603 const DependentSizedExtVectorType *VectorParam
1604 = cast<DependentSizedExtVectorType>(Param);
1605
1606 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1607 // Perform deduction on the element types.
1608 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001609 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1610 VectorParam->getElementType(),
1611 VectorArg->getElementType(),
1612 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001613 return Result;
1614
1615 // Perform deduction on the vector size, if we can.
1616 NonTypeTemplateParmDecl *NTTP
1617 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1618 if (!NTTP)
1619 return Sema::TDK_Success;
1620
1621 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1622 ArgSize = VectorArg->getNumElements();
1623 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1624 false, Info, Deduced);
1625 }
1626
1627 if (const DependentSizedExtVectorType *VectorArg
1628 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1629 // Perform deduction on the element types.
1630 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001631 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1632 VectorParam->getElementType(),
1633 VectorArg->getElementType(),
1634 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001635 return Result;
1636
1637 // Perform deduction on the vector size, if we can.
1638 NonTypeTemplateParmDecl *NTTP
1639 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1640 if (!NTTP)
1641 return Sema::TDK_Success;
1642
1643 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1644 Info, Deduced);
1645 }
1646
1647 return Sema::TDK_NonDeducedMismatch;
1648 }
1649
Douglas Gregor637d9982009-06-10 23:47:09 +00001650 case Type::TypeOfExpr:
1651 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001652 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001653 case Type::UnresolvedUsing:
1654 case Type::Decltype:
1655 case Type::UnaryTransform:
1656 case Type::Auto:
1657 case Type::DependentTemplateSpecialization:
1658 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001659 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001660 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001661 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001662 }
1663
David Blaikiee4d798f2012-01-20 21:50:17 +00001664 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001665}
1666
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001667static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001668DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001669 TemplateParameterList *TemplateParams,
1670 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001671 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001672 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001673 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001674 // If the template argument is a pack expansion, perform template argument
1675 // deduction against the pattern of that expansion. This only occurs during
1676 // partial ordering.
1677 if (Arg.isPackExpansion())
1678 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001679
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001680 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001681 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001682 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001683
1684 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001685 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001686 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1687 Param.getAsType(),
1688 Arg.getAsType(),
1689 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001690 Info.FirstArg = Param;
1691 Info.SecondArg = Arg;
1692 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001693
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001694 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001695 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001696 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001697 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001698 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001699 Info.FirstArg = Param;
1700 Info.SecondArg = Arg;
1701 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001702
1703 case TemplateArgument::TemplateExpansion:
1704 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001705
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001706 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001707 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001708 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001709 return Sema::TDK_Success;
1710
1711 Info.FirstArg = Param;
1712 Info.SecondArg = Arg;
1713 return Sema::TDK_NonDeducedMismatch;
1714
1715 case TemplateArgument::NullPtr:
1716 if (Arg.getKind() == TemplateArgument::NullPtr &&
1717 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001718 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001719
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001720 Info.FirstArg = Param;
1721 Info.SecondArg = Arg;
1722 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001723
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001724 case TemplateArgument::Integral:
1725 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001726 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001727 return Sema::TDK_Success;
1728
1729 Info.FirstArg = Param;
1730 Info.SecondArg = Arg;
1731 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001732 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001733
1734 if (Arg.getKind() == TemplateArgument::Expression) {
1735 Info.FirstArg = Param;
1736 Info.SecondArg = Arg;
1737 return Sema::TDK_NonDeducedMismatch;
1738 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001739
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001740 Info.FirstArg = Param;
1741 Info.SecondArg = Arg;
1742 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001743
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001744 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001745 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001746 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1747 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001748 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001749 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001750 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001751 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001752 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001753 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001754 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001755 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001756 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001757 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001758 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001759
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001760 Info.FirstArg = Param;
1761 Info.SecondArg = Arg;
1762 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001763 }
Mike Stump11289f42009-09-09 15:08:12 +00001764
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001765 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001766 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001767 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001768 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001769 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001770 }
Mike Stump11289f42009-09-09 15:08:12 +00001771
David Blaikiee4d798f2012-01-20 21:50:17 +00001772 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001773}
1774
Douglas Gregor7baabef2010-12-22 18:17:10 +00001775/// \brief Determine whether there is a template argument to be used for
1776/// deduction.
1777///
1778/// This routine "expands" argument packs in-place, overriding its input
1779/// parameters so that \c Args[ArgIdx] will be the available template argument.
1780///
1781/// \returns true if there is another template argument (which will be at
1782/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001783static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001784 unsigned &ArgIdx,
1785 unsigned &NumArgs) {
1786 if (ArgIdx == NumArgs)
1787 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001788
Douglas Gregor7baabef2010-12-22 18:17:10 +00001789 const TemplateArgument &Arg = Args[ArgIdx];
1790 if (Arg.getKind() != TemplateArgument::Pack)
1791 return true;
1792
1793 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1794 Args = Arg.pack_begin();
1795 NumArgs = Arg.pack_size();
1796 ArgIdx = 0;
1797 return ArgIdx < NumArgs;
1798}
1799
Douglas Gregord0ad2942010-12-23 01:24:45 +00001800/// \brief Determine whether the given set of template arguments has a pack
1801/// expansion that is not the last template argument.
1802static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1803 unsigned NumArgs) {
1804 unsigned ArgIdx = 0;
1805 while (ArgIdx < NumArgs) {
1806 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807
Douglas Gregord0ad2942010-12-23 01:24:45 +00001808 // Unwrap argument packs.
1809 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1810 Args = Arg.pack_begin();
1811 NumArgs = Arg.pack_size();
1812 ArgIdx = 0;
1813 continue;
1814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001815
Douglas Gregord0ad2942010-12-23 01:24:45 +00001816 ++ArgIdx;
1817 if (ArgIdx == NumArgs)
1818 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001819
Douglas Gregord0ad2942010-12-23 01:24:45 +00001820 if (Arg.isPackExpansion())
1821 return true;
1822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823
Douglas Gregord0ad2942010-12-23 01:24:45 +00001824 return false;
1825}
1826
Douglas Gregor7baabef2010-12-22 18:17:10 +00001827static Sema::TemplateDeductionResult
1828DeduceTemplateArguments(Sema &S,
1829 TemplateParameterList *TemplateParams,
1830 const TemplateArgument *Params, unsigned NumParams,
1831 const TemplateArgument *Args, unsigned NumArgs,
1832 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +00001833 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001834 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001835 // If the template argument list of P contains a pack expansion that is not
1836 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001837 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001838 if (hasPackExpansionBeforeEnd(Params, NumParams))
1839 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001840
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001841 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001842 // If P has a form that contains <T> or <i>, then each argument Pi of the
1843 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001844 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001845 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001847 ++ParamIdx) {
1848 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001849 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001850
Douglas Gregor7baabef2010-12-22 18:17:10 +00001851 // Check whether we have enough arguments.
1852 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Richard Smith16b65392012-12-06 06:44:44 +00001853 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001854
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001855 if (Args[ArgIdx].isPackExpansion()) {
1856 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1857 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001858 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001859 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001860
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001861 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001862 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001863 = DeduceTemplateArguments(S, TemplateParams,
1864 Params[ParamIdx], Args[ArgIdx],
1865 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001866 return Result;
1867
Douglas Gregor7baabef2010-12-22 18:17:10 +00001868 // Move to the next argument.
1869 ++ArgIdx;
1870 continue;
1871 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001872
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001873 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001874
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001875 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001876 // If Pi is a pack expansion, then the pattern of Pi is compared with
1877 // each remaining argument in the template argument list of A. Each
1878 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001879 // template parameter packs expanded by Pi.
1880 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001882 // FIXME: If there are no remaining arguments, we can bail out early
1883 // and set any deduced parameter packs to an empty argument pack.
1884 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885
Richard Smith0a80d572014-05-29 01:12:14 +00001886 // Prepare to deduce the packs within the pattern.
1887 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001888
1889 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001891 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001892 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001893 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001894 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001896 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001898 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1899 Info, Deduced))
1900 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001901
Richard Smith0a80d572014-05-29 01:12:14 +00001902 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001904
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001905 // Build argument packs for each of the parameter packs expanded by this
1906 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001907 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001908 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001910
Douglas Gregor7baabef2010-12-22 18:17:10 +00001911 return Sema::TDK_Success;
1912}
1913
Mike Stump11289f42009-09-09 15:08:12 +00001914static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001915DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001916 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001917 const TemplateArgumentList &ParamList,
1918 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001919 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001920 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001921 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001922 ParamList.data(), ParamList.size(),
1923 ArgList.data(), ArgList.size(),
1924 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001925}
1926
Douglas Gregor705c9002009-06-26 20:57:09 +00001927/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001928static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001929 const TemplateArgument &X,
1930 const TemplateArgument &Y) {
1931 if (X.getKind() != Y.getKind())
1932 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001933
Douglas Gregor705c9002009-06-26 20:57:09 +00001934 switch (X.getKind()) {
1935 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001936 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001937
Douglas Gregor705c9002009-06-26 20:57:09 +00001938 case TemplateArgument::Type:
1939 return Context.getCanonicalType(X.getAsType()) ==
1940 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001941
Douglas Gregor705c9002009-06-26 20:57:09 +00001942 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001943 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001944
1945 case TemplateArgument::NullPtr:
1946 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001947
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001948 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001949 case TemplateArgument::TemplateExpansion:
1950 return Context.getCanonicalTemplateName(
1951 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1952 Context.getCanonicalTemplateName(
1953 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954
Douglas Gregor705c9002009-06-26 20:57:09 +00001955 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001956 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001957
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001958 case TemplateArgument::Expression: {
1959 llvm::FoldingSetNodeID XID, YID;
1960 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001961 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001962 return XID == YID;
1963 }
Mike Stump11289f42009-09-09 15:08:12 +00001964
Douglas Gregor705c9002009-06-26 20:57:09 +00001965 case TemplateArgument::Pack:
1966 if (X.pack_size() != Y.pack_size())
1967 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001968
1969 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1970 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001971 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001972 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001973 if (!isSameTemplateArg(Context, *XP, *YP))
1974 return false;
1975
1976 return true;
1977 }
1978
David Blaikiee4d798f2012-01-20 21:50:17 +00001979 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00001980}
1981
Douglas Gregorca4686d2011-01-04 23:35:54 +00001982/// \brief Allocate a TemplateArgumentLoc where all locations have
1983/// been initialized to the given location.
1984///
1985/// \param S The semantic analysis object.
1986///
James Dennett634962f2012-06-14 21:40:34 +00001987/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00001988/// location information for.
1989///
1990/// \param NTTPType For a declaration template argument, the type of
1991/// the non-type template parameter that corresponds to this template
1992/// argument.
1993///
1994/// \param Loc The source location to use for the resulting template
1995/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001996static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00001997getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001998 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00001999 QualType NTTPType,
2000 SourceLocation Loc) {
2001 switch (Arg.getKind()) {
2002 case TemplateArgument::Null:
2003 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004
Douglas Gregorca4686d2011-01-04 23:35:54 +00002005 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002006 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002007 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
Douglas Gregorca4686d2011-01-04 23:35:54 +00002009 case TemplateArgument::Declaration: {
2010 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00002011 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002012 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002013 return TemplateArgumentLoc(TemplateArgument(E), E);
2014 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Eli Friedmanb826a002012-09-26 02:36:12 +00002016 case TemplateArgument::NullPtr: {
2017 Expr *E
2018 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002019 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002020 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2021 E);
2022 }
2023
Douglas Gregorca4686d2011-01-04 23:35:54 +00002024 case TemplateArgument::Integral: {
2025 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002026 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002027 return TemplateArgumentLoc(TemplateArgument(E), E);
2028 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002029
Douglas Gregor9d802122011-03-02 17:09:35 +00002030 case TemplateArgument::Template:
2031 case TemplateArgument::TemplateExpansion: {
2032 NestedNameSpecifierLocBuilder Builder;
2033 TemplateName Template = Arg.getAsTemplate();
2034 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2035 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002036 else if (QualifiedTemplateName *QTN =
2037 Template.getAsQualifiedTemplateName())
Douglas Gregor9d802122011-03-02 17:09:35 +00002038 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2039
2040 if (Arg.getKind() == TemplateArgument::Template)
2041 return TemplateArgumentLoc(Arg,
2042 Builder.getWithLocInContext(S.Context),
2043 Loc);
2044
2045
2046 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2047 Loc, Loc);
2048 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002049
Douglas Gregorca4686d2011-01-04 23:35:54 +00002050 case TemplateArgument::Expression:
2051 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052
Douglas Gregorca4686d2011-01-04 23:35:54 +00002053 case TemplateArgument::Pack:
2054 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056
David Blaikiee4d798f2012-01-20 21:50:17 +00002057 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002058}
2059
2060
2061/// \brief Convert the given deduced template argument and add it to the set of
2062/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002063static bool
2064ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2065 DeducedTemplateArgument Arg,
2066 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002067 TemplateDeductionInfo &Info,
2068 bool InFunctionTemplate,
2069 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002070 // First, for a non-type template parameter type that is
2071 // initialized by a declaration, we need the type of the
2072 // corresponding non-type template parameter.
2073 QualType NTTPType;
2074 if (NonTypeTemplateParmDecl *NTTP =
2075 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2076 NTTPType = NTTP->getType();
2077 if (NTTPType->isDependentType()) {
2078 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2079 Output.data(), Output.size());
2080 NTTPType = S.SubstType(NTTPType,
2081 MultiLevelTemplateArgumentList(TemplateArgs),
2082 NTTP->getLocation(),
2083 NTTP->getDeclName());
2084 if (NTTPType.isNull())
2085 return true;
2086 }
2087 }
2088
2089 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2090 unsigned ArgumentPackIndex) {
2091 // Convert the deduced template argument into a template
2092 // argument that we can check, almost as if the user had written
2093 // the template argument explicitly.
2094 TemplateArgumentLoc ArgLoc =
2095 getTrivialTemplateArgumentLoc(S, Arg, NTTPType, Info.getLocation());
2096
2097 // Check the template argument, converting it as necessary.
2098 return S.CheckTemplateArgument(
2099 Param, ArgLoc, Template, Template->getLocation(),
2100 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2101 InFunctionTemplate
2102 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2103 : Sema::CTAK_Deduced)
2104 : Sema::CTAK_Specified);
2105 };
2106
Douglas Gregorca4686d2011-01-04 23:35:54 +00002107 if (Arg.getKind() == TemplateArgument::Pack) {
2108 // This is a template argument pack, so check each of its arguments against
2109 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002110 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002111 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002112 // When converting the deduced template argument, append it to the
2113 // general output list. We need to do this so that the template argument
2114 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002115 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002116 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002117 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2118 "deduced nested pack");
2119 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002120 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Douglas Gregor51bc5712011-01-05 20:52:18 +00002122 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002123 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002125
Richard Smithdf18ee92016-02-03 20:40:30 +00002126 // If the pack is empty, we still need to substitute into the parameter
2127 // itself, in case that substitution fails. For non-type parameters, we did
2128 // this above. For type parameters, no substitution is ever required.
2129 auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param);
2130 if (TTP && PackedArgsBuilder.empty()) {
2131 // Set up a template instantiation context.
2132 LocalInstantiationScope Scope(S);
2133 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2134 TTP, Output,
2135 Template->getSourceRange());
2136 if (Inst.isInvalid())
2137 return true;
2138
2139 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2140 Output.data(), Output.size());
2141 if (!S.SubstDecl(TTP, S.CurContext,
2142 MultiLevelTemplateArgumentList(TemplateArgs)))
2143 return true;
2144 }
Richard Smith37acb792016-02-03 20:15:01 +00002145
Douglas Gregorca4686d2011-01-04 23:35:54 +00002146 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002147 Output.push_back(
2148 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002149 return false;
2150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002151
Richard Smith37acb792016-02-03 20:15:01 +00002152 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002153}
2154
Douglas Gregor684268d2010-04-29 06:21:43 +00002155/// Complete template argument deduction for a class template partial
2156/// specialization.
2157static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002158FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002159 ClassTemplatePartialSpecializationDecl *Partial,
2160 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002161 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002162 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002163 // Unevaluated SFINAE context.
2164 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002165 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002166
Douglas Gregor684268d2010-04-29 06:21:43 +00002167 Sema::ContextRAII SavedContext(S, Partial);
2168
2169 // C++ [temp.deduct.type]p2:
2170 // [...] or if any template argument remains neither deduced nor
2171 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002172 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002173 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2174 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002175 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002176 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002177 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002178 return Sema::TDK_Incomplete;
2179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002180
Douglas Gregorca4686d2011-01-04 23:35:54 +00002181 // We have deduced this argument, so it still needs to be
2182 // checked and converted.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002183 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002184 Partial, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002185 Builder)) {
2186 Info.Param = makeTemplateParameter(Param);
2187 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2189 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002190 return Sema::TDK_SubstitutionFailure;
2191 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002193
Douglas Gregor684268d2010-04-29 06:21:43 +00002194 // Form the template argument list from the deduced template arguments.
2195 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002197 Builder.size());
2198
Douglas Gregor684268d2010-04-29 06:21:43 +00002199 Info.reset(DeducedArgumentList);
2200
2201 // Substitute the deduced template arguments into the template
2202 // arguments of the class template partial specialization, and
2203 // verify that the instantiated template arguments are both valid
2204 // and are equivalent to the template arguments originally provided
2205 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002206 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002207 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002208 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002209 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002210 const TemplateArgumentLoc *PartialTemplateArgs
2211 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002212
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002213 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2214 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002215
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002216 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002217 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2218 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2219 if (ParamIdx >= Partial->getTemplateParameters()->size())
2220 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2221
2222 Decl *Param
2223 = const_cast<NamedDecl *>(
2224 Partial->getTemplateParameters()->getParam(ParamIdx));
2225 Info.Param = makeTemplateParameter(Param);
2226 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2227 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002228 }
2229
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002230 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002231 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002232 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002233 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002234
Douglas Gregorca4686d2011-01-04 23:35:54 +00002235 TemplateParameterList *TemplateParams
2236 = ClassTemplate->getTemplateParameters();
2237 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002238 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002239 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002240 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002241 Info.FirstArg = TemplateArgs[I];
2242 Info.SecondArg = InstArg;
2243 return Sema::TDK_NonDeducedMismatch;
2244 }
2245 }
2246
2247 if (Trap.hasErrorOccurred())
2248 return Sema::TDK_SubstitutionFailure;
2249
2250 return Sema::TDK_Success;
2251}
2252
Douglas Gregor170bc422009-06-12 22:31:52 +00002253/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002254/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002255/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002256Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002257Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002258 const TemplateArgumentList &TemplateArgs,
2259 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002260 if (Partial->isInvalidDecl())
2261 return TDK_Invalid;
2262
Douglas Gregor170bc422009-06-12 22:31:52 +00002263 // C++ [temp.class.spec.match]p2:
2264 // A partial specialization matches a given actual template
2265 // argument list if the template arguments of the partial
2266 // specialization can be deduced from the actual template argument
2267 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002268
2269 // Unevaluated SFINAE context.
2270 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002271 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002272
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002273 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002274 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002275 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002276 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002277 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002278 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002279 TemplateArgs, Info, Deduced))
2280 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002281
Richard Smith80934652012-07-16 01:09:10 +00002282 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002283 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2284 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002285 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002286 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002287
Douglas Gregore1416332009-06-14 08:02:22 +00002288 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002289 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290
2291 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002292 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002293}
Douglas Gregor91772d12009-06-13 00:26:55 +00002294
Larisse Voufo39a1e502013-08-06 01:03:05 +00002295/// Complete template argument deduction for a variable template partial
2296/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002297/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2298/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2299/// VarTemplate(Partial)SpecializationDecl with a new data
2300/// structure Template(Partial)SpecializationDecl, and
2301/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002302static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2303 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2304 const TemplateArgumentList &TemplateArgs,
2305 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2306 TemplateDeductionInfo &Info) {
2307 // Unevaluated SFINAE context.
2308 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2309 Sema::SFINAETrap Trap(S);
2310
2311 // C++ [temp.deduct.type]p2:
2312 // [...] or if any template argument remains neither deduced nor
2313 // explicitly specified, template argument deduction fails.
2314 SmallVector<TemplateArgument, 4> Builder;
2315 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2316 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2317 NamedDecl *Param = PartialParams->getParam(I);
2318 if (Deduced[I].isNull()) {
2319 Info.Param = makeTemplateParameter(Param);
2320 return Sema::TDK_Incomplete;
2321 }
2322
2323 // We have deduced this argument, so it still needs to be
2324 // checked and converted.
Richard Smith37acb792016-02-03 20:15:01 +00002325 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial,
2326 Info, false, Builder)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002327 Info.Param = makeTemplateParameter(Param);
2328 // FIXME: These template arguments are temporary. Free them!
2329 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2330 Builder.size()));
2331 return Sema::TDK_SubstitutionFailure;
2332 }
2333 }
2334
2335 // Form the template argument list from the deduced template arguments.
2336 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2337 S.Context, Builder.data(), Builder.size());
2338
2339 Info.reset(DeducedArgumentList);
2340
2341 // Substitute the deduced template arguments into the template
2342 // arguments of the class template partial specialization, and
2343 // verify that the instantiated template arguments are both valid
2344 // and are equivalent to the template arguments originally provided
2345 // to the class template.
2346 LocalInstantiationScope InstScope(S);
2347 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002348 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2349 = Partial->getTemplateArgsAsWritten();
2350 const TemplateArgumentLoc *PartialTemplateArgs
2351 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002352
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002353 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2354 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002355
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002356 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002357 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2358 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2359 if (ParamIdx >= Partial->getTemplateParameters()->size())
2360 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2361
2362 Decl *Param = const_cast<NamedDecl *>(
2363 Partial->getTemplateParameters()->getParam(ParamIdx));
2364 Info.Param = makeTemplateParameter(Param);
2365 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2366 return Sema::TDK_SubstitutionFailure;
2367 }
2368 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2369 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2370 false, ConvertedInstArgs))
2371 return Sema::TDK_SubstitutionFailure;
2372
2373 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2374 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2375 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2376 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2377 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2378 Info.FirstArg = TemplateArgs[I];
2379 Info.SecondArg = InstArg;
2380 return Sema::TDK_NonDeducedMismatch;
2381 }
2382 }
2383
2384 if (Trap.hasErrorOccurred())
2385 return Sema::TDK_SubstitutionFailure;
2386
2387 return Sema::TDK_Success;
2388}
2389
2390/// \brief Perform template argument deduction to determine whether
2391/// the given template arguments match the given variable template
2392/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002393/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2394/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2395/// VarTemplate(Partial)SpecializationDecl with a new data
2396/// structure Template(Partial)SpecializationDecl, and
2397/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002398Sema::TemplateDeductionResult
2399Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2400 const TemplateArgumentList &TemplateArgs,
2401 TemplateDeductionInfo &Info) {
2402 if (Partial->isInvalidDecl())
2403 return TDK_Invalid;
2404
2405 // C++ [temp.class.spec.match]p2:
2406 // A partial specialization matches a given actual template
2407 // argument list if the template arguments of the partial
2408 // specialization can be deduced from the actual template argument
2409 // list (14.8.2).
2410
2411 // Unevaluated SFINAE context.
2412 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2413 SFINAETrap Trap(*this);
2414
2415 SmallVector<DeducedTemplateArgument, 4> Deduced;
2416 Deduced.resize(Partial->getTemplateParameters()->size());
2417 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2418 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2419 TemplateArgs, Info, Deduced))
2420 return Result;
2421
2422 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002423 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2424 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002425 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002426 return TDK_InstantiationDepth;
2427
2428 if (Trap.hasErrorOccurred())
2429 return Sema::TDK_SubstitutionFailure;
2430
2431 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2432 Deduced, Info);
2433}
2434
Douglas Gregorfc516c92009-06-26 23:27:24 +00002435/// \brief Determine whether the given type T is a simple-template-id type.
2436static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002437 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002438 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002439 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002440
Douglas Gregorfc516c92009-06-26 23:27:24 +00002441 return false;
2442}
Douglas Gregor9b146582009-07-08 20:55:45 +00002443
2444/// \brief Substitute the explicitly-provided template arguments into the
2445/// given function template according to C++ [temp.arg.explicit].
2446///
2447/// \param FunctionTemplate the function template into which the explicit
2448/// template arguments will be substituted.
2449///
James Dennett634962f2012-06-14 21:40:34 +00002450/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002451/// arguments.
2452///
Mike Stump11289f42009-09-09 15:08:12 +00002453/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002454/// with the converted and checked explicit template arguments.
2455///
Mike Stump11289f42009-09-09 15:08:12 +00002456/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002457/// parameters.
2458///
2459/// \param FunctionType if non-NULL, the result type of the function template
2460/// will also be instantiated and the pointed-to value will be updated with
2461/// the instantiated function type.
2462///
2463/// \param Info if substitution fails for any reason, this object will be
2464/// populated with more information about the failure.
2465///
2466/// \returns TDK_Success if substitution was successful, or some failure
2467/// condition.
2468Sema::TemplateDeductionResult
2469Sema::SubstituteExplicitTemplateArguments(
2470 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002471 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002472 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2473 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002474 QualType *FunctionType,
2475 TemplateDeductionInfo &Info) {
2476 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2477 TemplateParameterList *TemplateParams
2478 = FunctionTemplate->getTemplateParameters();
2479
John McCall6b51f282009-11-23 01:53:49 +00002480 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002481 // No arguments to substitute; just copy over the parameter types and
2482 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002483 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002484 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002485
Douglas Gregor9b146582009-07-08 20:55:45 +00002486 if (FunctionType)
2487 *FunctionType = Function->getType();
2488 return TDK_Success;
2489 }
Mike Stump11289f42009-09-09 15:08:12 +00002490
Eli Friedman77dcc722012-02-08 03:07:05 +00002491 // Unevaluated SFINAE context.
2492 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002493 SFINAETrap Trap(*this);
2494
Douglas Gregor9b146582009-07-08 20:55:45 +00002495 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002496 // Template arguments that are present shall be specified in the
2497 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002498 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002499 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002500 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002501
2502 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002503 // explicitly-specified template arguments against this function template,
2504 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002505 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002506 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2507 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002508 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2509 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002510 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002511 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002512
Douglas Gregor9b146582009-07-08 20:55:45 +00002513 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002514 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002515 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002516 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002517 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002518 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002519 if (Index >= TemplateParams->size())
2520 Index = TemplateParams->size() - 1;
2521 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002522 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002523 }
Mike Stump11289f42009-09-09 15:08:12 +00002524
Douglas Gregor9b146582009-07-08 20:55:45 +00002525 // Form the template argument list from the explicitly-specified
2526 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002527 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002528 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002529 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002530
John McCall036855a2010-10-12 19:40:14 +00002531 // Template argument deduction and the final substitution should be
2532 // done in the context of the templated declaration. Explicit
2533 // argument substitution, on the other hand, needs to happen in the
2534 // calling context.
2535 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2536
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002537 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002538 // note that the template argument pack is partially substituted and record
2539 // the explicit template arguments. They'll be used as part of deduction
2540 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002541 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2542 const TemplateArgument &Arg = Builder[I];
2543 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002544 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002545 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002546 Arg.pack_begin(),
2547 Arg.pack_size());
2548 break;
2549 }
2550 }
2551
Richard Smith5e580292012-02-10 09:58:53 +00002552 const FunctionProtoType *Proto
2553 = Function->getType()->getAs<FunctionProtoType>();
2554 assert(Proto && "Function template does not have a prototype?");
2555
Richard Smith70b13042015-01-09 01:19:56 +00002556 // Isolate our substituted parameters from our caller.
2557 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2558
John McCallc8e321d2016-03-01 02:09:25 +00002559 ExtParameterInfoBuilder ExtParamInfos;
2560
Douglas Gregor9b146582009-07-08 20:55:45 +00002561 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002562 // explicitly-specified template arguments. If the function has a trailing
2563 // return type, substitute it after the arguments to ensure we substitute
2564 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002565 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002566 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002567 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002568 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002569 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002570 return TDK_SubstitutionFailure;
2571 }
2572
Richard Smith5e580292012-02-10 09:58:53 +00002573 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002574 QualType ResultType;
2575 {
2576 // C++11 [expr.prim.general]p3:
2577 // If a declaration declares a member function or member function
2578 // template of a class X, the expression this is a prvalue of type
2579 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2580 // and the end of the function-definition, member-declarator, or
2581 // declarator.
2582 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002583 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002584 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2585 ThisContext = Method->getParent();
2586 ThisTypeQuals = Method->getTypeQualifiers();
2587 }
2588
2589 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002590 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002591
2592 ResultType =
2593 SubstType(Proto->getReturnType(),
2594 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2595 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002596 if (ResultType.isNull() || Trap.hasErrorOccurred())
2597 return TDK_SubstitutionFailure;
2598 }
John McCallc8e321d2016-03-01 02:09:25 +00002599
Richard Smith5e580292012-02-10 09:58:53 +00002600 // Instantiate the types of each of the function parameters given the
2601 // explicitly-specified template arguments if we didn't do so earlier.
2602 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002603 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002604 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002605 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002606 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002607 return TDK_SubstitutionFailure;
2608
Douglas Gregor9b146582009-07-08 20:55:45 +00002609 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002610 auto EPI = Proto->getExtProtoInfo();
2611 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002612 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002613 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002614 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002615 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002616 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2617 return TDK_SubstitutionFailure;
2618 }
Mike Stump11289f42009-09-09 15:08:12 +00002619
Douglas Gregor9b146582009-07-08 20:55:45 +00002620 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002621 // Trailing template arguments that can be deduced (14.8.2) may be
2622 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002623 // template arguments can be deduced, they may all be omitted; in this
2624 // case, the empty template argument list <> itself may also be omitted.
2625 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002626 // Take all of the explicitly-specified arguments and put them into
2627 // the set of deduced template arguments. Explicitly-specified
2628 // parameter packs, however, will be set to NULL since the deduction
2629 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002630 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002631 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2632 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2633 if (Arg.getKind() == TemplateArgument::Pack)
2634 Deduced.push_back(DeducedTemplateArgument());
2635 else
2636 Deduced.push_back(Arg);
2637 }
Mike Stump11289f42009-09-09 15:08:12 +00002638
Douglas Gregor9b146582009-07-08 20:55:45 +00002639 return TDK_Success;
2640}
2641
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002642/// \brief Check whether the deduced argument type for a call to a function
2643/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2644static bool
2645CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2646 QualType DeducedA) {
2647 ASTContext &Context = S.Context;
2648
2649 QualType A = OriginalArg.OriginalArgType;
2650 QualType OriginalParamType = OriginalArg.OriginalParamType;
2651
2652 // Check for type equality (top-level cv-qualifiers are ignored).
2653 if (Context.hasSameUnqualifiedType(A, DeducedA))
2654 return false;
2655
2656 // Strip off references on the argument types; they aren't needed for
2657 // the following checks.
2658 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2659 DeducedA = DeducedARef->getPointeeType();
2660 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2661 A = ARef->getPointeeType();
2662
2663 // C++ [temp.deduct.call]p4:
2664 // [...] However, there are three cases that allow a difference:
2665 // - If the original P is a reference type, the deduced A (i.e., the
2666 // type referred to by the reference) can be more cv-qualified than
2667 // the transformed A.
2668 if (const ReferenceType *OriginalParamRef
2669 = OriginalParamType->getAs<ReferenceType>()) {
2670 // We don't want to keep the reference around any more.
2671 OriginalParamType = OriginalParamRef->getPointeeType();
2672
2673 Qualifiers AQuals = A.getQualifiers();
2674 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002675
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002676 // Under Objective-C++ ARC, the deduced type may have implicitly
2677 // been given strong or (when dealing with a const reference)
2678 // unsafe_unretained lifetime. If so, update the original
2679 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002680 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002681 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2682 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2683 (DeducedAQuals.hasConst() &&
2684 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2685 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002686 }
2687
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002688 if (AQuals == DeducedAQuals) {
2689 // Qualifiers match; there's nothing to do.
2690 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002691 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002692 } else {
2693 // Qualifiers are compatible, so have the argument type adopt the
2694 // deduced argument type's qualifiers as if we had performed the
2695 // qualification conversion.
2696 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2697 }
2698 }
2699
2700 // - The transformed A can be another pointer or pointer to member
2701 // type that can be converted to the deduced A via a qualification
2702 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002703 //
2704 // Also allow conversions which merely strip [[noreturn]] from function types
2705 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002706 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002707 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002708 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002709 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002710 (S.IsQualificationConversion(A, DeducedA, false,
2711 ObjCLifetimeConversion) ||
2712 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002713 return false;
2714
2715
2716 // - If P is a class and P has the form simple-template-id, then the
2717 // transformed A can be a derived class of the deduced A. [...]
2718 // [...] Likewise, if P is a pointer to a class of the form
2719 // simple-template-id, the transformed A can be a pointer to a
2720 // derived class pointed to by the deduced A.
2721 if (const PointerType *OriginalParamPtr
2722 = OriginalParamType->getAs<PointerType>()) {
2723 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2724 if (const PointerType *APtr = A->getAs<PointerType>()) {
2725 if (A->getPointeeType()->isRecordType()) {
2726 OriginalParamType = OriginalParamPtr->getPointeeType();
2727 DeducedA = DeducedAPtr->getPointeeType();
2728 A = APtr->getPointeeType();
2729 }
2730 }
2731 }
2732 }
2733
2734 if (Context.hasSameUnqualifiedType(A, DeducedA))
2735 return false;
2736
2737 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002738 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002739 return false;
2740
2741 return true;
2742}
2743
Mike Stump11289f42009-09-09 15:08:12 +00002744/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002745/// checking the deduced template arguments for completeness and forming
2746/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002747///
2748/// \param OriginalCallArgs If non-NULL, the original call arguments against
2749/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002750Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002751Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002752 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002753 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002754 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002755 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002756 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2757 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002758 TemplateParameterList *TemplateParams
2759 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002760
Eli Friedman77dcc722012-02-08 03:07:05 +00002761 // Unevaluated SFINAE context.
2762 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002763 SFINAETrap Trap(*this);
2764
Douglas Gregor9b146582009-07-08 20:55:45 +00002765 // Enter a new template instantiation context while we instantiate the
2766 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002767 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002768 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2769 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002770 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2771 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002772 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002773 return TDK_InstantiationDepth;
2774
John McCalle23b8712010-04-29 01:18:58 +00002775 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002776
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002777 // C++ [temp.deduct.type]p2:
2778 // [...] or if any template argument remains neither deduced nor
2779 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002780 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002781 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2782 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002783
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002784 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002785 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002786 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002787 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002788 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002789 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002790 // We may have had explicitly-specified template arguments for a
2791 // template parameter pack (that may or may not have been extended
2792 // via additional deduced arguments).
2793 if (Param->isParameterPack() && CurrentInstantiationScope) {
2794 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2795 Param) {
2796 // Forget the partially-substituted pack; its substitution is now
2797 // complete.
2798 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2799 }
2800 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002801 continue;
2802 }
Richard Smith37acb792016-02-03 20:15:01 +00002803
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002804 // We have deduced this argument, so it still needs to be
2805 // checked and converted.
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002806 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002807 FunctionTemplate, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002808 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002809 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002810 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002811 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2812 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002813 return TDK_SubstitutionFailure;
2814 }
2815
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002816 continue;
2817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002819 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002820 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002821 // be deduced to an empty sequence of template arguments.
2822 // FIXME: Where did the word "trailing" come from?
2823 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002824 // We may have had explicitly-specified template arguments for this
2825 // template parameter pack. If so, our empty deduction extends the
2826 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2827 const TemplateArgument *ExplicitArgs;
2828 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002829 if (CurrentInstantiationScope &&
2830 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002831 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002832 == Param) {
Benjamin Kramercce63472015-08-05 09:40:22 +00002833 Builder.push_back(TemplateArgument(
2834 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002835
Richard Smithdf18ee92016-02-03 20:40:30 +00002836 // Forget the partially-substituted pack; its substitution is now
Douglas Gregorcaddba92013-01-18 22:27:09 +00002837 // complete.
2838 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2839 } else {
Richard Smithdf18ee92016-02-03 20:40:30 +00002840 // Go through the motions of checking the empty argument pack against
2841 // the parameter pack.
2842 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2843 if (ConvertDeducedTemplateArgument(*this, Param, DeducedPack,
2844 FunctionTemplate, Info, true,
2845 Builder)) {
2846 Info.Param = makeTemplateParameter(Param);
2847 // FIXME: These template arguments are temporary. Free them!
2848 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2849 Builder.size()));
2850 return TDK_SubstitutionFailure;
2851 }
Douglas Gregorcaddba92013-01-18 22:27:09 +00002852 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002853 continue;
2854 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002855
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002856 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002857 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002858 TemplateArgumentLoc DefArg
2859 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2860 FunctionTemplate->getLocation(),
2861 FunctionTemplate->getSourceRange().getEnd(),
2862 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002863 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002864
2865 // If there was no default argument, deduction is incomplete.
2866 if (DefArg.getArgument().isNull()) {
2867 Info.Param = makeTemplateParameter(
2868 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002869 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2870 Builder.size()));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002871 if (PartialOverloading) break;
2872
Richard Smithc87b9382013-07-04 01:01:24 +00002873 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002875
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002876 // Check whether we can actually use the default argument.
2877 if (CheckTemplateArgument(Param, DefArg,
2878 FunctionTemplate,
2879 FunctionTemplate->getLocation(),
2880 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002881 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002882 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002883 Info.Param = makeTemplateParameter(
2884 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002885 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002886 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002887 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002888 return TDK_SubstitutionFailure;
2889 }
2890
2891 // If we get here, we successfully used the default template argument.
2892 }
2893
2894 // Form the template argument list from the deduced template arguments.
2895 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002896 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002897 Info.reset(DeducedArgumentList);
2898
Mike Stump11289f42009-09-09 15:08:12 +00002899 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002900 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002901 DeclContext *Owner = FunctionTemplate->getDeclContext();
2902 if (FunctionTemplate->getFriendObjectKind())
2903 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002904 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002905 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002906 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002907 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002908 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002909
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002910 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002911 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002912
Mike Stump11289f42009-09-09 15:08:12 +00002913 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002914 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002915 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2916 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002917 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002918
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002919 // There may have been an error that did not prevent us from constructing a
2920 // declaration. Mark the declaration invalid and return with a substitution
2921 // failure.
2922 if (Trap.hasErrorOccurred()) {
2923 Specialization->setInvalidDecl(true);
2924 return TDK_SubstitutionFailure;
2925 }
2926
Douglas Gregore65aacb2011-06-16 16:50:48 +00002927 if (OriginalCallArgs) {
2928 // C++ [temp.deduct.call]p4:
2929 // In general, the deduction process attempts to find template argument
2930 // values that will make the deduced A identical to A (after the type A
2931 // is transformed as described above). [...]
2932 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2933 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002934 unsigned ParamIdx = OriginalArg.ArgIdx;
2935
2936 if (ParamIdx >= Specialization->getNumParams())
2937 continue;
2938
2939 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002940 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2941 Info.FirstArg = TemplateArgument(DeducedA);
2942 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2943 Info.CallArgIndex = OriginalArg.ArgIdx;
2944 return TDK_DeducedMismatch;
2945 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002946 }
2947 }
2948
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002949 // If we suppressed any diagnostics while performing template argument
2950 // deduction, and if we haven't already instantiated this declaration,
2951 // keep track of these diagnostics. They'll be emitted if this specialization
2952 // is actually used.
2953 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002954 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002955 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2956 if (Pos == SuppressedDiagnostics.end())
2957 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2958 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002959 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002960
Mike Stump11289f42009-09-09 15:08:12 +00002961 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002962}
2963
John McCall8d08b9b2010-08-27 09:08:28 +00002964/// Gets the type of a function for template-argument-deducton
2965/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002966static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002967 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002968 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002969 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002970 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002971 return QualType();
2972
John McCallc1f69982010-02-02 02:21:27 +00002973 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002974 if (Method->isInstance()) {
2975 // An instance method that's referenced in a form that doesn't
2976 // look like a member pointer is just invalid.
2977 if (!R.HasFormOfMemberPointer) return QualType();
2978
Richard Smith2a7d4812013-05-04 07:00:32 +00002979 return S.Context.getMemberPointerType(Fn->getType(),
2980 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002981 }
2982
2983 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002984 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002985}
2986
2987/// Apply the deduction rules for overload sets.
2988///
2989/// \return the null type if this argument should be treated as an
2990/// undeduced context
2991static QualType
2992ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002993 Expr *Arg, QualType ParamType,
2994 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002995
John McCall8d08b9b2010-08-27 09:08:28 +00002996 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00002997
John McCall8d08b9b2010-08-27 09:08:28 +00002998 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00002999
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003000 // C++0x [temp.deduct.call]p4
3001 unsigned TDF = 0;
3002 if (ParamWasReference)
3003 TDF |= TDF_ParamWithReferenceType;
3004 if (R.IsAddressOfOperand)
3005 TDF |= TDF_IgnoreQualifiers;
3006
John McCallc1f69982010-02-02 02:21:27 +00003007 // C++0x [temp.deduct.call]p6:
3008 // When P is a function type, pointer to function type, or pointer
3009 // to member function type:
3010
3011 if (!ParamType->isFunctionType() &&
3012 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003013 !ParamType->isMemberFunctionPointerType()) {
3014 if (Ovl->hasExplicitTemplateArgs()) {
3015 // But we can still look for an explicit specialization.
3016 if (FunctionDecl *ExplicitSpec
3017 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003018 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003019 }
John McCallc1f69982010-02-02 02:21:27 +00003020
George Burgess IVcc2f3552016-03-19 21:51:45 +00003021 DeclAccessPair DAP;
3022 if (FunctionDecl *Viable =
3023 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3024 return GetTypeOfFunction(S, R, Viable);
3025
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003026 return QualType();
3027 }
3028
3029 // Gather the explicit template arguments, if any.
3030 TemplateArgumentListInfo ExplicitTemplateArgs;
3031 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003032 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003033 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003034 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3035 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003036 NamedDecl *D = (*I)->getUnderlyingDecl();
3037
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003038 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3039 // - If the argument is an overload set containing one or more
3040 // function templates, the parameter is treated as a
3041 // non-deduced context.
3042 if (!Ovl->hasExplicitTemplateArgs())
3043 return QualType();
3044
3045 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003046 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003047 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003048 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3049 Specialization, Info))
3050 continue;
3051
3052 D = Specialization;
3053 }
John McCallc1f69982010-02-02 02:21:27 +00003054
3055 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003056 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003057 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003058
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003059 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003061 ArgType->isFunctionType())
3062 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003063
John McCallc1f69982010-02-02 02:21:27 +00003064 // - If the argument is an overload set (not containing function
3065 // templates), trial argument deduction is attempted using each
3066 // of the members of the set. If deduction succeeds for only one
3067 // of the overload set members, that member is used as the
3068 // argument value for the deduction. If deduction succeeds for
3069 // more than one member of the overload set the parameter is
3070 // treated as a non-deduced context.
3071
3072 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3073 // Type deduction is done independently for each P/A pair, and
3074 // the deduced template argument values are then combined.
3075 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003076 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003077 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003078 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003079 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003080 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3081 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003082 if (Result) continue;
3083 if (!Match.isNull()) return QualType();
3084 Match = ArgType;
3085 }
3086
3087 return Match;
3088}
3089
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003090/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003091/// described in C++ [temp.deduct.call].
3092///
3093/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003094/// argument deduction based on this P/A pair because the argument is an
3095/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003096static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3097 TemplateParameterList *TemplateParams,
3098 QualType &ParamType,
3099 QualType &ArgType,
3100 Expr *Arg,
3101 unsigned &TDF) {
3102 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003103 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003104 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003105 if (ParamType.hasQualifiers())
3106 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003107
3108 // [...] If P is a reference type, the type referred to by P is
3109 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003110 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003111 if (ParamRefType)
3112 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003113
Nathan Sidwell96090022015-01-16 15:20:14 +00003114 // Overload sets usually make this parameter an undeduced context,
3115 // but there are sometimes special circumstances. Typically
3116 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003117 if (ArgType == S.Context.OverloadTy) {
3118 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3119 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003120 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003121 if (ArgType.isNull())
3122 return true;
3123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003124
Douglas Gregor7825bf32011-01-06 22:09:01 +00003125 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003126 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003127 if (ArgType->isIncompleteArrayType()) {
3128 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003129 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003130 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003131
Douglas Gregor7825bf32011-01-06 22:09:01 +00003132 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003133 // If P is an rvalue reference to a cv-unqualified template
3134 // parameter and the argument is an lvalue, the type "lvalue
3135 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003136 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003137 !ParamType.getQualifiers() &&
3138 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003139 Arg->isLValue())
3140 ArgType = S.Context.getLValueReferenceType(ArgType);
3141 } else {
3142 // C++ [temp.deduct.call]p2:
3143 // If P is not a reference type:
3144 // - If A is an array type, the pointer type produced by the
3145 // array-to-pointer standard conversion (4.2) is used in place of
3146 // A for type deduction; otherwise,
3147 if (ArgType->isArrayType())
3148 ArgType = S.Context.getArrayDecayedType(ArgType);
3149 // - If A is a function type, the pointer type produced by the
3150 // function-to-pointer standard conversion (4.3) is used in place
3151 // of A for type deduction; otherwise,
3152 else if (ArgType->isFunctionType())
3153 ArgType = S.Context.getPointerType(ArgType);
3154 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003155 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003156 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003157 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003158 }
3159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003160
Douglas Gregor7825bf32011-01-06 22:09:01 +00003161 // C++0x [temp.deduct.call]p4:
3162 // In general, the deduction process attempts to find template argument
3163 // values that will make the deduced A identical to A (after the type A
3164 // is transformed as described above). [...]
3165 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003166
Douglas Gregor7825bf32011-01-06 22:09:01 +00003167 // - If the original P is a reference type, the deduced A (i.e., the
3168 // type referred to by the reference) can be more cv-qualified than
3169 // the transformed A.
3170 if (ParamRefType)
3171 TDF |= TDF_ParamWithReferenceType;
3172 // - The transformed A can be another pointer or pointer to member
3173 // type that can be converted to the deduced A via a qualification
3174 // conversion (4.4).
3175 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3176 ArgType->isObjCObjectPointerType())
3177 TDF |= TDF_IgnoreQualifiers;
3178 // - If P is a class and P has the form simple-template-id, then the
3179 // transformed A can be a derived class of the deduced A. Likewise,
3180 // if P is a pointer to a class of the form simple-template-id, the
3181 // transformed A can be a pointer to a derived class pointed to by
3182 // the deduced A.
3183 if (isSimpleTemplateIdType(ParamType) ||
3184 (isa<PointerType>(ParamType) &&
3185 isSimpleTemplateIdType(
3186 ParamType->getAs<PointerType>()->getPointeeType())))
3187 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188
Douglas Gregor7825bf32011-01-06 22:09:01 +00003189 return false;
3190}
3191
Nico Weberc153d242014-07-28 00:02:09 +00003192static bool
3193hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3194 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003195
Hubert Tong3280b332015-06-25 00:25:49 +00003196static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3197 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3198 Expr *Arg, TemplateDeductionInfo &Info,
3199 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3200
3201/// \brief Attempt template argument deduction from an initializer list
3202/// deemed to be an argument in a function call.
3203static bool
3204DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3205 QualType AdjustedParamType, InitListExpr *ILE,
3206 TemplateDeductionInfo &Info,
3207 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3208 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003209
3210 // [temp.deduct.call] p1 (post CWG-1591)
3211 // If removing references and cv-qualifiers from P gives
3212 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3213 // non-empty initializer list (8.5.4), then deduction is performed instead for
3214 // each element of the initializer list, taking P0 as a function template
3215 // parameter type and the initializer element as its argument, and in the
3216 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3217 // length of the initializer list. Otherwise, an initializer list argument
3218 // causes the parameter to be considered a non-deduced context
3219
3220 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3221
3222 const bool IsDependentSizedArray =
3223 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3224
Faisal Validd76cc12015-12-10 12:29:11 +00003225 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003226
3227 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3228 S.isStdInitializerList(AdjustedParamType, &ElTy);
3229
3230 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003231 return false;
3232
3233 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003234 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3235 // deduce against the 'T' in T[N].
3236 if (ElTy.isNull()) {
3237 assert(!IsSTDList);
3238 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003239 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003240 // Deduction only needs to be done for dependent types.
3241 if (ElTy->isDependentType()) {
3242 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003243 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3244 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003245 return true;
3246 }
3247 }
3248 if (IsDependentSizedArray) {
3249 const DependentSizedArrayType *ArrTy =
3250 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3251 // Determine the array bound is something we can deduce.
3252 if (NonTypeTemplateParmDecl *NTTP =
3253 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3254 // We can perform template argument deduction for the given non-type
3255 // template parameter.
3256 assert(NTTP->getDepth() == 0 &&
3257 "Cannot deduce non-type template argument at depth > 0");
3258 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3259 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003260
Faisal Valif6dfdb32015-12-10 05:36:39 +00003261 Result = DeduceNonTypeTemplateArgument(
3262 S, NTTP, llvm::APSInt(Size), NTTP->getType(),
3263 /*ArrayBound=*/true, Info, Deduced);
3264 }
3265 }
Hubert Tong3280b332015-06-25 00:25:49 +00003266 return true;
3267}
3268
Sebastian Redl19181662012-03-15 21:40:51 +00003269/// \brief Perform template argument deduction by matching a parameter type
3270/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003271/// an initializer list that was originally matched against a parameter
3272/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003273static Sema::TemplateDeductionResult
3274DeduceTemplateArgumentByListElement(Sema &S,
3275 TemplateParameterList *TemplateParams,
3276 QualType ParamType, Expr *Arg,
3277 TemplateDeductionInfo &Info,
3278 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3279 unsigned TDF) {
3280 // Handle the case where an init list contains another init list as the
3281 // element.
3282 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003283 Sema::TemplateDeductionResult Result;
3284 if (!DeduceFromInitializerList(S, TemplateParams,
3285 ParamType.getNonReferenceType(), ILE, Info,
3286 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003287 return Sema::TDK_Success; // Just ignore this expression.
3288
Hubert Tong3280b332015-06-25 00:25:49 +00003289 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003290 }
3291
3292 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003293 QualType ArgType = Arg->getType();
3294 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003295 ArgType, Arg, TDF)) {
3296 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003297 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003298 }
Sebastian Redl19181662012-03-15 21:40:51 +00003299 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003300 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003301}
3302
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003303/// \brief Perform template argument deduction from a function call
3304/// (C++ [temp.deduct.call]).
3305///
3306/// \param FunctionTemplate the function template for which we are performing
3307/// template argument deduction.
3308///
James Dennett18348b62012-06-22 08:52:37 +00003309/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003310/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003311///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003312/// \param Args the function call arguments
3313///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003314/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003315/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003316/// template argument deduction.
3317///
3318/// \param Info the argument will be updated to provide additional information
3319/// about template argument deduction.
3320///
3321/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003322Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3323 FunctionTemplateDecl *FunctionTemplate,
3324 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003325 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3326 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003327 if (FunctionTemplate->isInvalidDecl())
3328 return TDK_Invalid;
3329
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003330 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003331 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003332
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003333 // C++ [temp.deduct.call]p1:
3334 // Template argument deduction is done by comparing each function template
3335 // parameter type (call it P) with the type of the corresponding argument
3336 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003337 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003338 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003339 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003340 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003341 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003342 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003343 if (Proto->isTemplateVariadic())
3344 /* Do nothing */;
3345 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003346 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003347 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003348 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003349 }
Mike Stump11289f42009-09-09 15:08:12 +00003350
Douglas Gregor89026b52009-06-30 23:57:56 +00003351 // The types of the parameters from which we will perform template argument
3352 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003353 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003354 TemplateParameterList *TemplateParams
3355 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003356 SmallVector<DeducedTemplateArgument, 4> Deduced;
3357 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003358 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003359 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003360 TemplateDeductionResult Result =
3361 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003362 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003363 Deduced,
3364 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003365 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003366 Info);
3367 if (Result)
3368 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003369
3370 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003371 } else {
3372 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003373 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003374 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3375 }
Mike Stump11289f42009-09-09 15:08:12 +00003376
Douglas Gregor89026b52009-06-30 23:57:56 +00003377 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003378 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003379 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003380 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003381 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3382 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003383 QualType OrigParamType = ParamTypes[ParamIdx];
3384 QualType ParamType = OrigParamType;
3385
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003386 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003387 = dyn_cast<PackExpansionType>(ParamType);
3388 if (!ParamExpansion) {
3389 // Simple case: matching a function parameter to a function argument.
3390 if (ArgIdx >= CheckArgs)
3391 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392
Douglas Gregor7825bf32011-01-06 22:09:01 +00003393 Expr *Arg = Args[ArgIdx++];
3394 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003395
Douglas Gregor7825bf32011-01-06 22:09:01 +00003396 unsigned TDF = 0;
3397 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3398 ParamType, ArgType, Arg,
3399 TDF))
3400 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003401
Douglas Gregor0c83c812011-10-09 22:06:46 +00003402 // If we have nothing to deduce, we're done.
3403 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3404 continue;
3405
Sebastian Redl43144e72012-01-17 22:49:58 +00003406 // If the argument is an initializer list ...
3407 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003408 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003409 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003410 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3411 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003412 continue;
3413
Hubert Tong3280b332015-06-25 00:25:49 +00003414 if (Result)
3415 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003416 // Don't track the argument type, since an initializer list has none.
3417 continue;
3418 }
3419
Douglas Gregore65aacb2011-06-16 16:50:48 +00003420 // Keep track of the argument type and corresponding parameter index,
3421 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003422 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3423 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003424
Douglas Gregor7825bf32011-01-06 22:09:01 +00003425 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003426 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3427 ParamType, ArgType,
3428 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003429 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003430
Douglas Gregor7825bf32011-01-06 22:09:01 +00003431 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433
Douglas Gregor7825bf32011-01-06 22:09:01 +00003434 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435 // For a function parameter pack that occurs at the end of the
3436 // parameter-declaration-list, the type A of each remaining argument of
3437 // the call is compared with the type P of the declarator-id of the
3438 // function parameter pack. Each comparison deduces template arguments
3439 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003440 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003442 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003443 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003444 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445
Douglas Gregor7825bf32011-01-06 22:09:01 +00003446 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003447 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3448 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Douglas Gregor7825bf32011-01-06 22:09:01 +00003450 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003451 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003452 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003453
Douglas Gregore65aacb2011-06-16 16:50:48 +00003454 QualType OrigParamType = ParamPattern;
3455 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003456 Expr *Arg = Args[ArgIdx];
3457 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003458
Douglas Gregor7825bf32011-01-06 22:09:01 +00003459 unsigned TDF = 0;
3460 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3461 ParamType, ArgType, Arg,
3462 TDF)) {
3463 // We can't actually perform any deduction for this argument, so stop
3464 // deduction at this point.
3465 ++ArgIdx;
3466 break;
3467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468
Sebastian Redl43144e72012-01-17 22:49:58 +00003469 // As above, initializer lists need special handling.
3470 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003471 TemplateDeductionResult Result;
3472 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3473 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003474 ++ArgIdx;
3475 break;
3476 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003477
Hubert Tong3280b332015-06-25 00:25:49 +00003478 if (Result)
3479 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003480 } else {
3481
3482 // Keep track of the argument type and corresponding argument index,
3483 // so we can check for compatibility between the deduced A and A.
3484 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3485 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3486 ArgType));
3487
3488 if (TemplateDeductionResult Result
3489 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3490 ParamType, ArgType, Info,
3491 Deduced, TDF))
3492 return Result;
3493 }
Mike Stump11289f42009-09-09 15:08:12 +00003494
Richard Smith0a80d572014-05-29 01:12:14 +00003495 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003497
Douglas Gregor7825bf32011-01-06 22:09:01 +00003498 // Build argument packs for each of the parameter packs expanded by this
3499 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003500 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003502
Douglas Gregor7825bf32011-01-06 22:09:01 +00003503 // After we've matching against a parameter pack, we're done.
3504 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003505 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003506
Mike Stump11289f42009-09-09 15:08:12 +00003507 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003508 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003509 Info, &OriginalCallArgs,
3510 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003511}
3512
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003513QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3514 QualType FunctionType) {
3515 if (ArgFunctionType.isNull())
3516 return ArgFunctionType;
3517
3518 const FunctionProtoType *FunctionTypeP =
3519 FunctionType->castAs<FunctionProtoType>();
3520 CallingConv CC = FunctionTypeP->getCallConv();
3521 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3522 const FunctionProtoType *ArgFunctionTypeP =
3523 ArgFunctionType->getAs<FunctionProtoType>();
3524 if (ArgFunctionTypeP->getCallConv() == CC &&
3525 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3526 return ArgFunctionType;
3527
3528 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3529 EI = EI.withNoReturn(NoReturn);
3530 ArgFunctionTypeP =
3531 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3532 return QualType(ArgFunctionTypeP, 0);
3533}
3534
Douglas Gregor9b146582009-07-08 20:55:45 +00003535/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003536/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3537/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003538///
3539/// \param FunctionTemplate the function template for which we are performing
3540/// template argument deduction.
3541///
James Dennett18348b62012-06-22 08:52:37 +00003542/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003543/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003544///
3545/// \param ArgFunctionType the function type that will be used as the
3546/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003547/// function template's function type. This type may be NULL, if there is no
3548/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003549///
3550/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003551/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003552/// template argument deduction.
3553///
3554/// \param Info the argument will be updated to provide additional information
3555/// about template argument deduction.
3556///
3557/// \returns the result of template argument deduction.
3558Sema::TemplateDeductionResult
3559Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003560 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003561 QualType ArgFunctionType,
3562 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003563 TemplateDeductionInfo &Info,
3564 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003565 if (FunctionTemplate->isInvalidDecl())
3566 return TDK_Invalid;
3567
Douglas Gregor9b146582009-07-08 20:55:45 +00003568 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3569 TemplateParameterList *TemplateParams
3570 = FunctionTemplate->getTemplateParameters();
3571 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003572 if (!InOverloadResolution)
3573 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003574
Douglas Gregor9b146582009-07-08 20:55:45 +00003575 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003576 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003577 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003578 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003579 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003580 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003581 if (TemplateDeductionResult Result
3582 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003583 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003584 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003585 &FunctionType, Info))
3586 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003587
3588 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003589 }
3590
Eli Friedman77dcc722012-02-08 03:07:05 +00003591 // Unevaluated SFINAE context.
3592 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003593 SFINAETrap Trap(*this);
3594
John McCallc1f69982010-02-02 02:21:27 +00003595 Deduced.resize(TemplateParams->size());
3596
Richard Smith2a7d4812013-05-04 07:00:32 +00003597 // If the function has a deduced return type, substitute it for a dependent
3598 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003599 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003600 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003601 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003602 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003603 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003604 }
3605
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003606 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003607 unsigned TDF = TDF_TopLevelParameterTypeList;
3608 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003609 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003610 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003611 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003612 FunctionType, ArgFunctionType,
3613 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003614 return Result;
3615 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003616
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003618 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3619 NumExplicitlySpecified,
3620 Specialization, Info))
3621 return Result;
3622
Richard Smith2a7d4812013-05-04 07:00:32 +00003623 // If the function has a deduced return type, deduce it now, so we can check
3624 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003625 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003626 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003627 DeduceReturnType(Specialization, Info.getLocation(), false))
3628 return TDK_MiscellaneousDeductionFailure;
3629
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003630 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003631 // specialization with respect to arguments of compatible pointer to function
3632 // types, template argument deduction fails.
3633 if (!ArgFunctionType.isNull()) {
3634 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3635 Context.getCanonicalType(Specialization->getType()),
3636 Context.getCanonicalType(ArgFunctionType)))
3637 return TDK_MiscellaneousDeductionFailure;
3638 else if(!InOverloadResolution &&
3639 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3640 return TDK_MiscellaneousDeductionFailure;
3641 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003642
3643 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003644}
3645
Faisal Vali850da1a2013-09-29 17:08:32 +00003646/// \brief Given a function declaration (e.g. a generic lambda conversion
3647/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003648/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3649/// to replace 'auto' with and not the actual result type you want
3650/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003651static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003652SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003653 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003654 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003655 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003656 assert(AutoResultType->getContainedAutoType());
3657 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003658 TypeToReplaceAutoWith);
3659 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3660}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003661
3662/// \brief Given a specialized conversion operator of a generic lambda
3663/// create the corresponding specializations of the call operator and
3664/// the static-invoker. If the return type of the call operator is auto,
3665/// deduce its return type and check if that matches the
3666/// return type of the destination function ptr.
3667
3668static inline Sema::TemplateDeductionResult
3669SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3670 CXXConversionDecl *ConversionSpecialized,
3671 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3672 QualType ReturnTypeOfDestFunctionPtr,
3673 TemplateDeductionInfo &TDInfo,
3674 Sema &S) {
3675
3676 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3677 assert(LambdaClass && LambdaClass->isGenericLambda());
3678
3679 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003680 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003681 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3682 CallOpResultType->getContainedAutoType();
3683
3684 FunctionTemplateDecl *CallOpTemplate =
3685 CallOpGeneric->getDescribedFunctionTemplate();
3686
Craig Topperc3ec1492014-05-26 06:22:03 +00003687 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003688 // Use the deduced arguments of the conversion function, to specialize our
3689 // generic lambda's call operator.
3690 if (Sema::TemplateDeductionResult Result
3691 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3692 DeducedArguments,
3693 0, CallOpSpecialized, TDInfo))
3694 return Result;
3695
3696 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003697 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3698 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003699 S.DeduceReturnType(CallOpSpecialized,
3700 CallOpSpecialized->getPointOfInstantiation(),
3701 /*Diagnose*/ true);
3702
3703 // Check to see if the return type of the destination ptr-to-function
3704 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003705 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003706 ReturnTypeOfDestFunctionPtr))
3707 return Sema::TDK_NonDeducedMismatch;
3708 // Since we have succeeded in matching the source and destination
3709 // ptr-to-functions (now including return type), and have successfully
3710 // specialized our corresponding call operator, we are ready to
3711 // specialize the static invoker with the deduced arguments of our
3712 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003713 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003714 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3715 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3716
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003717#ifndef NDEBUG
3718 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3719#endif
3720 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003721 InvokerSpecialized, TDInfo);
3722 assert(Result == Sema::TDK_Success &&
3723 "If the call operator succeeded so should the invoker!");
3724 // Set the result type to match the corresponding call operator
3725 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003726 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3727 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003728 // Be sure to get the type to replace 'auto' with and not
3729 // the full result type of the call op specialization
3730 // to substitute into the 'auto' of the invoker and conversion
3731 // function.
3732 // For e.g.
3733 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3734 // We don't want to subst 'int*' into 'auto' to get int**.
3735
Alp Toker314cc812014-01-25 16:55:45 +00003736 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3737 ->getContainedAutoType()
3738 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003739 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3740 TypeToReplaceAutoWith, S);
3741 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3742 TypeToReplaceAutoWith, S);
3743 }
3744
3745 // Ensure that static invoker doesn't have a const qualifier.
3746 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3747 // do not use the CallOperator's TypeSourceInfo which allows
3748 // the const qualifier to leak through.
3749 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3750 getType().getTypePtr()->castAs<FunctionProtoType>();
3751 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3752 EPI.TypeQuals = 0;
3753 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003754 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003755 return Sema::TDK_Success;
3756}
Douglas Gregor05155d82009-08-21 23:19:43 +00003757/// \brief Deduce template arguments for a templated conversion
3758/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3759/// conversion function template specialization.
3760Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003761Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003762 QualType ToType,
3763 CXXConversionDecl *&Specialization,
3764 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003765 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003766 return TDK_Invalid;
3767
Faisal Vali2b3a3012013-10-24 23:40:02 +00003768 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003769 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3770
Faisal Vali2b3a3012013-10-24 23:40:02 +00003771 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003772
3773 // Canonicalize the types for deduction.
3774 QualType P = Context.getCanonicalType(FromType);
3775 QualType A = Context.getCanonicalType(ToType);
3776
Douglas Gregord99609a2011-03-06 09:03:20 +00003777 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003778 // If P is a reference type, the type referred to by P is used for
3779 // type deduction.
3780 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3781 P = PRef->getPointeeType();
3782
Douglas Gregord99609a2011-03-06 09:03:20 +00003783 // C++0x [temp.deduct.conv]p4:
3784 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003785 // for type deduction.
3786 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003787 A = ARef->getPointeeType().getUnqualifiedType();
3788 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003789 //
Mike Stump11289f42009-09-09 15:08:12 +00003790 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003791 else {
3792 assert(!A->isReferenceType() && "Reference types were handled above");
3793
3794 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003795 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003796 // of P for type deduction; otherwise,
3797 if (P->isArrayType())
3798 P = Context.getArrayDecayedType(P);
3799 // - If P is a function type, the pointer type produced by the
3800 // function-to-pointer standard conversion (4.3) is used in
3801 // place of P for type deduction; otherwise,
3802 else if (P->isFunctionType())
3803 P = Context.getPointerType(P);
3804 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003805 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003806 else
3807 P = P.getUnqualifiedType();
3808
Douglas Gregord99609a2011-03-06 09:03:20 +00003809 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003810 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003811 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003812 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003813 A = A.getUnqualifiedType();
3814 }
3815
Eli Friedman77dcc722012-02-08 03:07:05 +00003816 // Unevaluated SFINAE context.
3817 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003818 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003819
3820 // C++ [temp.deduct.conv]p1:
3821 // Template argument deduction is done by comparing the return
3822 // type of the template conversion function (call it P) with the
3823 // type that is required as the result of the conversion (call it
3824 // A) as described in 14.8.2.4.
3825 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003826 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003827 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003828 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003829
3830 // C++0x [temp.deduct.conv]p4:
3831 // In general, the deduction process attempts to find template
3832 // argument values that will make the deduced A identical to
3833 // A. However, there are two cases that allow a difference:
3834 unsigned TDF = 0;
3835 // - If the original A is a reference type, A can be more
3836 // cv-qualified than the deduced A (i.e., the type referred to
3837 // by the reference)
3838 if (ToType->isReferenceType())
3839 TDF |= TDF_ParamWithReferenceType;
3840 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003841 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003842 // conversion.
3843 //
3844 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3845 // both P and A are pointers or member pointers. In this case, we
3846 // just ignore cv-qualifiers completely).
3847 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003848 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003849 TDF |= TDF_IgnoreQualifiers;
3850 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003851 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3852 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003853 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003854
3855 // Create an Instantiation Scope for finalizing the operator.
3856 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003857 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003858 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003859 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003860 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3861 ConversionSpecialized, Info);
3862 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3863
3864 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003865 // to a ptr-to-function, use the deduced arguments from the conversion
3866 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003867 // e.g., int (*fp)(int) = [](auto a) { return a; };
3868 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3869
3870 // Get the return type of the destination ptr-to-function we are converting
3871 // to. This is necessary for matching the lambda call operator's return
3872 // type to that of the destination ptr-to-function's return type.
3873 assert(A->isPointerType() &&
3874 "Can only convert from lambda to ptr-to-function");
3875 const FunctionType *ToFunType =
3876 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003877 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3878
Faisal Vali2b3a3012013-10-24 23:40:02 +00003879 // Create the corresponding specializations of the call operator and
3880 // the static-invoker; and if the return type is auto,
3881 // deduce the return type and check if it matches the
3882 // DestFunctionPtrReturnType.
3883 // For instance:
3884 // auto L = [](auto a) { return f(a); };
3885 // int (*fp)(int) = L;
3886 // char (*fp2)(int) = L; <-- Not OK.
3887
3888 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3889 Specialization, Deduced, DestFunctionPtrReturnType,
3890 Info, *this);
3891 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003892 return Result;
3893}
3894
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003895/// \brief Deduce template arguments for a function template when there is
3896/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3897///
3898/// \param FunctionTemplate the function template for which we are performing
3899/// template argument deduction.
3900///
James Dennett18348b62012-06-22 08:52:37 +00003901/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003902/// arguments.
3903///
3904/// \param Specialization if template argument deduction was successful,
3905/// this will be set to the function template specialization produced by
3906/// template argument deduction.
3907///
3908/// \param Info the argument will be updated to provide additional information
3909/// about template argument deduction.
3910///
3911/// \returns the result of template argument deduction.
3912Sema::TemplateDeductionResult
3913Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003914 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003915 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003916 TemplateDeductionInfo &Info,
3917 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003918 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003919 QualType(), Specialization, Info,
3920 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003921}
3922
Richard Smith30482bc2011-02-20 03:19:35 +00003923namespace {
3924 /// Substitute the 'auto' type specifier within a type for a given replacement
3925 /// type.
3926 class SubstituteAutoTransform :
3927 public TreeTransform<SubstituteAutoTransform> {
3928 QualType Replacement;
3929 public:
Nico Weberc153d242014-07-28 00:02:09 +00003930 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3931 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3932 Replacement(Replacement) {}
3933
Richard Smith30482bc2011-02-20 03:19:35 +00003934 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3935 // If we're building the type pattern to deduce against, don't wrap the
3936 // substituted type in an AutoType. Certain template deduction rules
3937 // apply only when a template type parameter appears directly (and not if
3938 // the parameter is found through desugaring). For instance:
3939 // auto &&lref = lvalue;
3940 // must transform into "rvalue reference to T" not "rvalue reference to
3941 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003942 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003943 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003944 TemplateTypeParmTypeLoc NewTL =
3945 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003946 NewTL.setNameLoc(TL.getNameLoc());
3947 return Result;
3948 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003949 bool Dependent =
3950 !Replacement.isNull() && Replacement->isDependentType();
3951 QualType Result =
3952 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00003953 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003954 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003955 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3956 NewTL.setNameLoc(TL.getNameLoc());
3957 return Result;
3958 }
3959 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003960
3961 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3962 // Lambdas never need to be transformed.
3963 return E;
3964 }
Richard Smith061f1e22013-04-30 21:23:01 +00003965
Richard Smith2a7d4812013-05-04 07:00:32 +00003966 QualType Apply(TypeLoc TL) {
3967 // Create some scratch storage for the transformed type locations.
3968 // FIXME: We're just going to throw this information away. Don't build it.
3969 TypeLocBuilder TLB;
3970 TLB.reserve(TL.getFullDataSize());
3971 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003972 }
Richard Smith30482bc2011-02-20 03:19:35 +00003973 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003974}
Richard Smith30482bc2011-02-20 03:19:35 +00003975
Richard Smith2a7d4812013-05-04 07:00:32 +00003976Sema::DeduceAutoResult
3977Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3978 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3979}
3980
Richard Smith061f1e22013-04-30 21:23:01 +00003981/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003982///
3983/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003984/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003985/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003986/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003987Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003988Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003989 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003990 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3991 if (NonPlaceholder.isInvalid())
3992 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003993 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003994 }
3995
Richard Smith2a7d4812013-05-04 07:00:32 +00003996 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003997 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003998 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003999 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004000 }
4001
Richard Smith74aeef52013-04-26 16:15:35 +00004002 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4003 // Since 'decltype(auto)' can only occur at the top of the type, we
4004 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004005 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004006 if (AT->isDecltypeAuto()) {
4007 if (isa<InitListExpr>(Init)) {
4008 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4009 return DAR_FailedAlreadyDiagnosed;
4010 }
4011
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004012 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004013 if (Deduced.isNull())
4014 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004015 // FIXME: Support a non-canonical deduced type for 'auto'.
4016 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004017 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004018 if (Result.isNull())
4019 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004020 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004021 } else if (!getLangOpts().CPlusPlus) {
4022 if (isa<InitListExpr>(Init)) {
4023 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4024 return DAR_FailedAlreadyDiagnosed;
4025 }
Richard Smith74aeef52013-04-26 16:15:35 +00004026 }
4027 }
4028
Richard Smith30482bc2011-02-20 03:19:35 +00004029 SourceLocation Loc = Init->getExprLoc();
4030
4031 LocalInstantiationScope InstScope(*this);
4032
4033 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004034 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004035 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4036 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004037 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4038 NamedDecl *TemplParamPtr = TemplParam;
James Y Knight7a22b242015-08-06 20:26:32 +00004039 FixedSizeTemplateParameterListStorage<1> TemplateParamsSt(
David Majnemer902f8c62015-12-27 07:16:27 +00004040 Loc, Loc, TemplParamPtr, Loc);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004041
Richard Smith061f1e22013-04-30 21:23:01 +00004042 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4043 assert(!FuncParam.isNull() &&
4044 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004045
4046 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004047 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004048 Deduced.resize(1);
4049 QualType InitType = Init->getType();
4050 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004051
Craig Toppere6706e42012-09-19 02:26:47 +00004052 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004053
Richard Smith74801c82012-07-08 04:13:07 +00004054 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004055 if (InitList) {
4056 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004057 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4058 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004059 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004060 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004061 }
4062 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004063 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4064 Diag(Loc, diag::err_auto_bitfield);
4065 return DAR_FailedAlreadyDiagnosed;
4066 }
4067
James Y Knight7a22b242015-08-06 20:26:32 +00004068 if (AdjustFunctionParmAndArgTypesForDeduction(
4069 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004070 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004071
James Y Knight7a22b242015-08-06 20:26:32 +00004072 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4073 FuncParam, InitType, Info, Deduced,
4074 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004075 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004076 }
Richard Smith30482bc2011-02-20 03:19:35 +00004077
Eli Friedmane4310952012-11-06 23:56:42 +00004078 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004079 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004080
Eli Friedmane4310952012-11-06 23:56:42 +00004081 QualType DeducedType = Deduced[0].getAsType();
4082
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004083 if (InitList) {
4084 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4085 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004086 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004087 }
4088
Richard Smith061f1e22013-04-30 21:23:01 +00004089 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004090 if (Result.isNull())
4091 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004092
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004093 // Check that the deduced argument type is compatible with the original
4094 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004095 if (!InitList && !Result.isNull() &&
4096 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004097 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004098 Result)) {
4099 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004100 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004101 }
4102
Sebastian Redl09edce02012-01-23 22:09:39 +00004103 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004104}
4105
Faisal Vali2b391ab2013-09-26 19:54:12 +00004106QualType Sema::SubstAutoType(QualType TypeWithAuto,
4107 QualType TypeToReplaceAuto) {
4108 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4109 TransformType(TypeWithAuto);
4110}
4111
4112TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4113 QualType TypeToReplaceAuto) {
4114 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4115 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004116}
4117
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004118void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4119 if (isa<InitListExpr>(Init))
4120 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004121 VDecl->isInitCapture()
4122 ? diag::err_init_capture_deduction_failure_from_init_list
4123 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004124 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4125 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004126 Diag(VDecl->getLocation(),
4127 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4128 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004129 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4130 << Init->getSourceRange();
4131}
4132
Richard Smith2a7d4812013-05-04 07:00:32 +00004133bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4134 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004135 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004136
4137 if (FD->getTemplateInstantiationPattern())
4138 InstantiateFunctionDefinition(Loc, FD);
4139
Alp Toker314cc812014-01-25 16:55:45 +00004140 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004141 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4142 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4143 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4144 }
4145
4146 return StillUndeduced;
4147}
4148
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004149static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004150MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004151 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004152 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004153 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004154
4155/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004156static void
4157AddImplicitObjectParameterType(ASTContext &Context,
4158 CXXMethodDecl *Method,
4159 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004160 // C++11 [temp.func.order]p3:
4161 // [...] The new parameter is of type "reference to cv A," where cv are
4162 // the cv-qualifiers of the function template (if any) and A is
4163 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004164 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004165 // The standard doesn't say explicitly, but we pick the appropriate kind of
4166 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004167 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4168 ArgTy = Context.getQualifiedType(ArgTy,
4169 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004170 if (Method->getRefQualifier() == RQ_RValue)
4171 ArgTy = Context.getRValueReferenceType(ArgTy);
4172 else
4173 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004174 ArgTypes.push_back(ArgTy);
4175}
4176
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004177/// \brief Determine whether the function template \p FT1 is at least as
4178/// specialized as \p FT2.
4179static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004180 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004181 FunctionTemplateDecl *FT1,
4182 FunctionTemplateDecl *FT2,
4183 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004184 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004185 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004186 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004187 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4188 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004190 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4191 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004192 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004193 Deduced.resize(TemplateParams->size());
4194
4195 // C++0x [temp.deduct.partial]p3:
4196 // The types used to determine the ordering depend on the context in which
4197 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004198 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004199 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004200 switch (TPOC) {
4201 case TPOC_Call: {
4202 // - In the context of a function call, the function parameter types are
4203 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004204 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4205 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004206
Eli Friedman3b5774a2012-09-19 23:27:04 +00004207 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004208 // [...] If only one of the function templates is a non-static
4209 // member, that function template is considered to have a new
4210 // first parameter inserted in its function parameter list. The
4211 // new parameter is of type "reference to cv A," where cv are
4212 // the cv-qualifiers of the function template (if any) and A is
4213 // the class of which the function template is a member.
4214 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004215 // Note that we interpret this to mean "if one of the function
4216 // templates is a non-static member and the other is a non-member";
4217 // otherwise, the ordering rules for static functions against non-static
4218 // functions don't make any sense.
4219 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004220 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4221 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004222 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004223
Richard Smithe5b52202013-09-11 00:52:39 +00004224 unsigned NumComparedArguments = NumCallArguments1;
4225
4226 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004227 // Compare 'this' from Method1 against first parameter from Method2.
4228 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4229 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004230 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004231 // Compare 'this' from Method2 against first parameter from Method1.
4232 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004233 }
4234
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004235 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004236 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004237 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004238 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004239
Douglas Gregorb837ea42011-01-11 17:34:58 +00004240 // C++ [temp.func.order]p5:
4241 // The presence of unused ellipsis and default arguments has no effect on
4242 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004243 if (Args1.size() > NumComparedArguments)
4244 Args1.resize(NumComparedArguments);
4245 if (Args2.size() > NumComparedArguments)
4246 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004247 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4248 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004249 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004250 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004251
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004252 break;
4253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004254
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004255 case TPOC_Conversion:
4256 // - In the context of a call to a conversion operator, the return types
4257 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004258 if (DeduceTemplateArgumentsByTypeMatch(
4259 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4260 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004261 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004262 return false;
4263 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004264
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004265 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004266 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004267 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004268 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4269 FD2->getType(), FD1->getType(),
4270 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004271 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004272 return false;
4273 break;
4274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004276 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277 // In most cases, all template parameters must have values in order for
4278 // deduction to succeed, but for partial ordering purposes a template
4279 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004280 // types being used for partial ordering. [ Note: a template parameter used
4281 // in a non-deduced context is considered used. -end note]
4282 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4283 for (; ArgIdx != NumArgs; ++ArgIdx)
4284 if (Deduced[ArgIdx].isNull())
4285 break;
4286
4287 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004289 // as FT2.
4290 return true;
4291 }
4292
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004293 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004294 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004295 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004296 case TPOC_Call:
4297 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4298 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004299 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004300 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004301 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004303 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004304 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4305 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004306 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004308 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004309 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004310 TemplateParams->getDepth(),
4311 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004312 break;
4313 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004315 for (; ArgIdx != NumArgs; ++ArgIdx)
4316 // If this argument had no value deduced but was used in one of the types
4317 // used for partial ordering, then deduction fails.
4318 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4319 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004321 return true;
4322}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323
Douglas Gregorcef1a032011-01-16 16:03:23 +00004324/// \brief Determine whether this a function template whose parameter-type-list
4325/// ends with a function parameter pack.
4326static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4327 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4328 unsigned NumParams = Function->getNumParams();
4329 if (NumParams == 0)
4330 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331
Douglas Gregorcef1a032011-01-16 16:03:23 +00004332 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4333 if (!Last->isParameterPack())
4334 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335
Douglas Gregorcef1a032011-01-16 16:03:23 +00004336 // Make sure that no previous parameter is a parameter pack.
4337 while (--NumParams > 0) {
4338 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4339 return false;
4340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341
Douglas Gregorcef1a032011-01-16 16:03:23 +00004342 return true;
4343}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Douglas Gregorbe999392009-09-15 16:23:51 +00004345/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004346/// to the rules of function template partial ordering (C++ [temp.func.order]).
4347///
4348/// \param FT1 the first function template
4349///
4350/// \param FT2 the second function template
4351///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004352/// \param TPOC the context in which we are performing partial ordering of
4353/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004354///
Richard Smithe5b52202013-09-11 00:52:39 +00004355/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4356/// only when \c TPOC is \c TPOC_Call.
4357///
4358/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4359/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004360///
Douglas Gregorbe999392009-09-15 16:23:51 +00004361/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004362/// template is more specialized, returns NULL.
4363FunctionTemplateDecl *
4364Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4365 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004366 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004367 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004368 unsigned NumCallArguments1,
4369 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004371 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004373 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004374
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004375 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004376 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004377
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004378 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004379 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004380
Douglas Gregorcef1a032011-01-16 16:03:23 +00004381 // FIXME: This mimics what GCC implements, but doesn't match up with the
4382 // proposed resolution for core issue 692. This area needs to be sorted out,
4383 // but for now we attempt to maintain compatibility.
4384 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4385 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4386 if (Variadic1 != Variadic2)
4387 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004388
Craig Topperc3ec1492014-05-26 06:22:03 +00004389 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004390}
Douglas Gregor9b146582009-07-08 20:55:45 +00004391
Douglas Gregor450f00842009-09-25 18:43:00 +00004392/// \brief Determine if the two templates are equivalent.
4393static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4394 if (T1 == T2)
4395 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396
Douglas Gregor450f00842009-09-25 18:43:00 +00004397 if (!T1 || !T2)
4398 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregor450f00842009-09-25 18:43:00 +00004400 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4401}
4402
4403/// \brief Retrieve the most specialized of the given function template
4404/// specializations.
4405///
John McCall58cc69d2010-01-27 01:50:18 +00004406/// \param SpecBegin the start iterator of the function template
4407/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004408///
John McCall58cc69d2010-01-27 01:50:18 +00004409/// \param SpecEnd the end iterator of the function template
4410/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004411///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004413/// diagnostic should occur.
4414///
4415/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4416/// no matching candidates.
4417///
4418/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4419/// occurs.
4420///
4421/// \param CandidateDiag partial diagnostic used for each function template
4422/// specialization that is a candidate in the ambiguous ordering. One parameter
4423/// in this diagnostic should be unbound, which will correspond to the string
4424/// describing the template arguments for the function template specialization.
4425///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004427/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004428UnresolvedSetIterator Sema::getMostSpecialized(
4429 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4430 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004431 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4432 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4433 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004434 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004435 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004436 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004437 FailedCandidates.NoteCandidates(*this, Loc);
4438 }
John McCall58cc69d2010-01-27 01:50:18 +00004439 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441
4442 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004443 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444
Douglas Gregor450f00842009-09-25 18:43:00 +00004445 // Find the function template that is better than all of the templates it
4446 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004447 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004449 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004450 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004451 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4452 FunctionTemplateDecl *Challenger
4453 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004454 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004455 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004456 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004457 Challenger)) {
4458 Best = I;
4459 BestTemplate = Challenger;
4460 }
4461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004462
Douglas Gregor450f00842009-09-25 18:43:00 +00004463 // Make sure that the "best" function template is more specialized than all
4464 // of the others.
4465 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004466 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4467 FunctionTemplateDecl *Challenger
4468 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004469 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004471 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004472 BestTemplate)) {
4473 Ambiguous = true;
4474 break;
4475 }
4476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004477
Douglas Gregor450f00842009-09-25 18:43:00 +00004478 if (!Ambiguous) {
4479 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004480 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
Douglas Gregor450f00842009-09-25 18:43:00 +00004483 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004484 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004485 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004486
Richard Smithb875c432013-05-04 01:51:08 +00004487 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004488 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4489 PartialDiagnostic PD = CandidateDiag;
4490 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004491 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004492 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004493 if (!TargetType.isNull())
4494 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4495 TargetType);
4496 Diag((*I)->getLocation(), PD);
4497 }
Richard Smithb875c432013-05-04 01:51:08 +00004498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499
John McCall58cc69d2010-01-27 01:50:18 +00004500 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004501}
4502
Douglas Gregorbe999392009-09-15 16:23:51 +00004503/// \brief Returns the more specialized class template partial specialization
4504/// according to the rules of partial ordering of class template partial
4505/// specializations (C++ [temp.class.order]).
4506///
4507/// \param PS1 the first class template partial specialization
4508///
4509/// \param PS2 the second class template partial specialization
4510///
4511/// \returns the more specialized class template partial specialization. If
4512/// neither partial specialization is more specialized, returns NULL.
4513ClassTemplatePartialSpecializationDecl *
4514Sema::getMoreSpecializedPartialSpecialization(
4515 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004516 ClassTemplatePartialSpecializationDecl *PS2,
4517 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004518 // C++ [temp.class.order]p1:
4519 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004520 // specialized as the second if, given the following rewrite to two
4521 // function templates, the first function template is at least as
4522 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004523 // templates (14.6.6.2):
4524 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525 // first partial specialization and has a single function parameter
4526 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004527 // arguments of the first partial specialization, and
4528 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004529 // second partial specialization and has a single function parameter
4530 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004531 // arguments of the second partial specialization.
4532 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004533 // Rather than synthesize function templates, we merely perform the
4534 // equivalent partial ordering by performing deduction directly on
4535 // the template arguments of the class template partial
4536 // specializations. This computation is slightly simpler than the
4537 // general problem of function template partial ordering, because
4538 // class template partial specializations are more constrained. We
4539 // know that every template parameter is deducible from the class
4540 // template partial specialization's template arguments, for
4541 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004542 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004543 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004544
4545 QualType PT1 = PS1->getInjectedSpecializationType();
4546 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004547
Douglas Gregorbe999392009-09-15 16:23:51 +00004548 // Determine whether PS1 is at least as specialized as PS2
4549 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004550 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4551 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004552 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004553 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004554 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004555 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004556 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004557 Better1 = !::FinishTemplateArgumentDeduction(
4558 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4559 }
4560
4561 // Determine whether PS2 is at least as specialized as PS1
4562 Deduced.clear();
4563 Deduced.resize(PS1->getTemplateParameters()->size());
4564 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4565 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004566 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004567 if (Better2) {
4568 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4569 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004570 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004571 Better2 = !::FinishTemplateArgumentDeduction(
4572 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4573 }
4574
4575 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004576 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004577
4578 return Better1 ? PS1 : PS2;
4579}
4580
Larisse Voufo30616382013-08-23 22:21:36 +00004581/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4582/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4583/// VarTemplate(Partial)SpecializationDecl with a new data
4584/// structure Template(Partial)SpecializationDecl, and
4585/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004586VarTemplatePartialSpecializationDecl *
4587Sema::getMoreSpecializedPartialSpecialization(
4588 VarTemplatePartialSpecializationDecl *PS1,
4589 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4590 SmallVector<DeducedTemplateArgument, 4> Deduced;
4591 TemplateDeductionInfo Info(Loc);
4592
Richard Smithf04fd0b2013-12-12 23:14:16 +00004593 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004594 "the partial specializations being compared should specialize"
4595 " the same template.");
4596 TemplateName Name(PS1->getSpecializedTemplate());
4597 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4598 QualType PT1 = Context.getTemplateSpecializationType(
4599 CanonTemplate, PS1->getTemplateArgs().data(),
4600 PS1->getTemplateArgs().size());
4601 QualType PT2 = Context.getTemplateSpecializationType(
4602 CanonTemplate, PS2->getTemplateArgs().data(),
4603 PS2->getTemplateArgs().size());
4604
4605 // Determine whether PS1 is at least as specialized as PS2
4606 Deduced.resize(PS2->getTemplateParameters()->size());
4607 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4608 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004609 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004610 if (Better1) {
4611 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4612 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004613 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4615 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004616 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004618
Douglas Gregorbe999392009-09-15 16:23:51 +00004619 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004620 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004621 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004622 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4623 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004624 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004625 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004626 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004627 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004628 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004629 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4630 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004631 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004633
Douglas Gregorbe999392009-09-15 16:23:51 +00004634 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004635 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004636
Douglas Gregorbe999392009-09-15 16:23:51 +00004637 return Better1? PS1 : PS2;
4638}
4639
Mike Stump11289f42009-09-09 15:08:12 +00004640static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004641MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004642 const TemplateArgument &TemplateArg,
4643 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004644 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004645 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004646
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004647/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004648/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004649static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004650MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004651 const Expr *E,
4652 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004653 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004654 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004655 // We can deduce from a pack expansion.
4656 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4657 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658
Richard Smith34349002012-07-09 03:07:20 +00004659 // Skip through any implicit casts we added while type-checking, and any
4660 // substitutions performed by template alias expansion.
4661 while (1) {
4662 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4663 E = ICE->getSubExpr();
4664 else if (const SubstNonTypeTemplateParmExpr *Subst =
4665 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4666 E = Subst->getReplacement();
4667 else
4668 break;
4669 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004670
4671 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004672 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004673 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004674 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004675 return;
4676
Mike Stump11289f42009-09-09 15:08:12 +00004677 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004678 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4679 if (!NTTP)
4680 return;
4681
Douglas Gregor21610382009-10-29 00:04:11 +00004682 if (NTTP->getDepth() == Depth)
4683 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004684}
4685
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004686/// \brief Mark the template parameters that are used by the given
4687/// nested name specifier.
4688static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004689MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004690 NestedNameSpecifier *NNS,
4691 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004692 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004693 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004694 if (!NNS)
4695 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004696
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004697 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004698 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004699 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004700 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004701}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004703/// \brief Mark the template parameters that are used by the given
4704/// template name.
4705static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004706MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004707 TemplateName Name,
4708 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004709 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004710 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004711 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4712 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004713 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4714 if (TTP->getDepth() == Depth)
4715 Used[TTP->getIndex()] = true;
4716 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004717 return;
4718 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004719
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004720 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004721 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004722 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004723 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004724 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004725 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004726}
4727
4728/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004729/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004730static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004731MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004732 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004733 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004734 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004735 if (T.isNull())
4736 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737
Douglas Gregor91772d12009-06-13 00:26:55 +00004738 // Non-dependent types have nothing deducible
4739 if (!T->isDependentType())
4740 return;
4741
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004742 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004743 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004744 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004745 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004746 cast<PointerType>(T)->getPointeeType(),
4747 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004748 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004749 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004750 break;
4751
4752 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004753 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004754 cast<BlockPointerType>(T)->getPointeeType(),
4755 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004756 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004757 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004758 break;
4759
4760 case Type::LValueReference:
4761 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004762 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004763 cast<ReferenceType>(T)->getPointeeType(),
4764 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004765 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004766 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004767 break;
4768
4769 case Type::MemberPointer: {
4770 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004771 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004772 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004773 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004774 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004775 break;
4776 }
4777
4778 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004779 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004780 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004781 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004782 // Fall through to check the element type
4783
4784 case Type::ConstantArray:
4785 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004786 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004787 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004788 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004789 break;
4790
4791 case Type::Vector:
4792 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004793 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004794 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004795 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004796 break;
4797
Douglas Gregor758a8692009-06-17 21:51:59 +00004798 case Type::DependentSizedExtVector: {
4799 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004800 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004801 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004802 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004803 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004804 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004805 break;
4806 }
4807
Douglas Gregor91772d12009-06-13 00:26:55 +00004808 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004809 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004810 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4811 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004812 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4813 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004814 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004815 break;
4816 }
4817
Douglas Gregor21610382009-10-29 00:04:11 +00004818 case Type::TemplateTypeParm: {
4819 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4820 if (TTP->getDepth() == Depth)
4821 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004822 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004823 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004824
Douglas Gregorfb322d82011-01-14 05:11:40 +00004825 case Type::SubstTemplateTypeParmPack: {
4826 const SubstTemplateTypeParmPackType *Subst
4827 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004828 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004829 QualType(Subst->getReplacedParameter(), 0),
4830 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004831 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004832 OnlyDeduced, Depth, Used);
4833 break;
4834 }
4835
John McCall2408e322010-04-27 00:57:59 +00004836 case Type::InjectedClassName:
4837 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4838 // fall through
4839
Douglas Gregor91772d12009-06-13 00:26:55 +00004840 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004841 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004842 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004843 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004844 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Douglas Gregord0ad2942010-12-23 01:24:45 +00004846 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004847 // If the template argument list of P contains a pack expansion that is
4848 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004849 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004850 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004851 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4852 break;
4853
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004854 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004855 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004856 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004857 break;
4858 }
4859
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004860 case Type::Complex:
4861 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004862 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004863 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004864 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004865 break;
4866
Eli Friedman0dfb8892011-10-06 23:00:33 +00004867 case Type::Atomic:
4868 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004869 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004870 cast<AtomicType>(T)->getValueType(),
4871 OnlyDeduced, Depth, Used);
4872 break;
4873
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004874 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004875 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004876 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004877 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004878 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004879 break;
4880
John McCallc392f372010-06-11 00:33:02 +00004881 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004882 // C++14 [temp.deduct.type]p5:
4883 // The non-deduced contexts are:
4884 // -- The nested-name-specifier of a type that was specified using a
4885 // qualified-id
4886 //
4887 // C++14 [temp.deduct.type]p6:
4888 // When a type name is specified in a way that includes a non-deduced
4889 // context, all of the types that comprise that type name are also
4890 // non-deduced.
4891 if (OnlyDeduced)
4892 break;
4893
John McCallc392f372010-06-11 00:33:02 +00004894 const DependentTemplateSpecializationType *Spec
4895 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896
Richard Smith50d5b972015-12-30 20:56:05 +00004897 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4898 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004899
John McCallc392f372010-06-11 00:33:02 +00004900 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004901 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004902 Used);
4903 break;
4904 }
4905
John McCallbd8d9bd2010-03-01 23:49:17 +00004906 case Type::TypeOf:
4907 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004908 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004909 cast<TypeOfType>(T)->getUnderlyingType(),
4910 OnlyDeduced, Depth, Used);
4911 break;
4912
4913 case Type::TypeOfExpr:
4914 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004915 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004916 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4917 OnlyDeduced, Depth, Used);
4918 break;
4919
4920 case Type::Decltype:
4921 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004922 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004923 cast<DecltypeType>(T)->getUnderlyingExpr(),
4924 OnlyDeduced, Depth, Used);
4925 break;
4926
Alexis Hunte852b102011-05-24 22:41:36 +00004927 case Type::UnaryTransform:
4928 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004929 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004930 cast<UnaryTransformType>(T)->getUnderlyingType(),
4931 OnlyDeduced, Depth, Used);
4932 break;
4933
Douglas Gregord2fa7662010-12-20 02:24:11 +00004934 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004935 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004936 cast<PackExpansionType>(T)->getPattern(),
4937 OnlyDeduced, Depth, Used);
4938 break;
4939
Richard Smith30482bc2011-02-20 03:19:35 +00004940 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004941 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004942 cast<AutoType>(T)->getDeducedType(),
4943 OnlyDeduced, Depth, Used);
4944
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004945 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004946 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004947 case Type::VariableArray:
4948 case Type::FunctionNoProto:
4949 case Type::Record:
4950 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004951 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004952 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004953 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004954 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00004955 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00004956#define TYPE(Class, Base)
4957#define ABSTRACT_TYPE(Class, Base)
4958#define DEPENDENT_TYPE(Class, Base)
4959#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4960#include "clang/AST/TypeNodes.def"
4961 break;
4962 }
4963}
4964
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004965/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004966/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004967static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004968MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004969 const TemplateArgument &TemplateArg,
4970 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004971 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004972 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004973 switch (TemplateArg.getKind()) {
4974 case TemplateArgument::Null:
4975 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004976 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004977 break;
Mike Stump11289f42009-09-09 15:08:12 +00004978
Eli Friedmanb826a002012-09-26 02:36:12 +00004979 case TemplateArgument::NullPtr:
4980 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4981 Depth, Used);
4982 break;
4983
Douglas Gregor91772d12009-06-13 00:26:55 +00004984 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004985 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004986 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004987 break;
4988
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004989 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004990 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004991 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004992 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004993 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004994 break;
4995
4996 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004997 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004998 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004999 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005000
Anders Carlssonbc343912009-06-15 17:04:53 +00005001 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005002 for (const auto &P : TemplateArg.pack_elements())
5003 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005004 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005005 }
5006}
5007
James Dennett41725122012-06-22 10:16:05 +00005008/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005009/// template argument list.
5010///
5011/// \param TemplateArgs the template argument list from which template
5012/// parameters will be deduced.
5013///
James Dennett41725122012-06-22 10:16:05 +00005014/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005015/// to indicate when the corresponding template parameter will be
5016/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005017void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005018Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005019 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005020 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005021 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022 // If the template argument list of P contains a pack expansion that is not
5023 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005024 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005026 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5027 return;
5028
Douglas Gregor91772d12009-06-13 00:26:55 +00005029 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005030 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005031 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005032}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005033
5034/// \brief Marks all of the template parameters that will be deduced by a
5035/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005036void Sema::MarkDeducedTemplateParameters(
5037 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5038 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005039 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005040 = FunctionTemplate->getTemplateParameters();
5041 Deduced.clear();
5042 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043
Douglas Gregorce23bae2009-09-18 23:21:38 +00005044 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5045 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005046 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005047 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005048}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005049
5050bool hasDeducibleTemplateParameters(Sema &S,
5051 FunctionTemplateDecl *FunctionTemplate,
5052 QualType T) {
5053 if (!T->isDependentType())
5054 return false;
5055
5056 TemplateParameterList *TemplateParams
5057 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005058 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005059 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005060 Deduced);
5061
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005062 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005063}