blob: 59dc1da49ac92d100bd96473a41e3a8f242b6a72 [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.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000289static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000290DeduceNonTypeTemplateArgument(Sema &S,
Mike Stump11289f42009-09-09 15:08:12 +0000291 NonTypeTemplateParmDecl *NTTP,
Douglas Gregor0a29a052010-03-26 05:50:28 +0000292 llvm::APSInt Value, QualType ValueType,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +0000293 bool DeducedFromArrayBound,
John McCall19c1bfd2010-08-25 05:32:35 +0000294 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000295 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000296 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000297 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000298
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000299 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
300 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000301 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000302 Deduced[NTTP->getIndex()],
303 NewDeduced);
304 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000305 Info.Param = NTTP;
306 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000310
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000311 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000312 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000313}
314
Mike Stump11289f42009-09-09 15:08:12 +0000315/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000316/// from the given type- or value-dependent expression.
317///
318/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000319static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000320DeduceNonTypeTemplateArgument(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000321 NonTypeTemplateParmDecl *NTTP,
322 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000323 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000325 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000326 "Cannot deduce non-type template argument with depth > 0");
327 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
328 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000329
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000330 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
332 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000333 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000334
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000335 if (Result.isNull()) {
336 Info.Param = NTTP;
337 Info.FirstArg = Deduced[NTTP->getIndex()];
338 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000339 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000340 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000341
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000342 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000343 return Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000344}
345
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000346/// \brief Deduce the value of the given non-type template parameter
347/// from the given declaration.
348///
349/// \returns true if deduction succeeded, false otherwise.
350static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000351DeduceNonTypeTemplateArgument(Sema &S,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000352 NonTypeTemplateParmDecl *NTTP,
353 ValueDecl *D,
354 TemplateDeductionInfo &Info,
355 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000356 assert(NTTP->getDepth() == 0 &&
357 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000358
Craig Topperc3ec1492014-05-26 06:22:03 +0000359 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
David Blaikie0f62c8d2014-10-16 04:21:25 +0000360 TemplateArgument New(D, NTTP->getType());
Eli Friedmanb826a002012-09-26 02:36:12 +0000361 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000362 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000363 Deduced[NTTP->getIndex()],
364 NewDeduced);
365 if (Result.isNull()) {
366 Info.Param = NTTP;
367 Info.FirstArg = Deduced[NTTP->getIndex()];
368 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000370 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000371
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000372 Deduced[NTTP->getIndex()] = Result;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000373 return Sema::TDK_Success;
374}
375
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000376static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000377DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000378 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000379 TemplateName Param,
380 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000381 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000382 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000383 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000384 if (!ParamDecl) {
385 // The parameter type is dependent and is not a template template parameter,
386 // so there is nothing that we can deduce.
387 return Sema::TDK_Success;
388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
Douglas Gregoradee3e32009-11-11 23:06:43 +0000390 if (TemplateTemplateParmDecl *TempParam
391 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000392 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000393 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000394 Deduced[TempParam->getIndex()],
395 NewDeduced);
396 if (Result.isNull()) {
397 Info.Param = TempParam;
398 Info.FirstArg = Deduced[TempParam->getIndex()];
399 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000400 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000403 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000404 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000406
Douglas Gregoradee3e32009-11-11 23:06:43 +0000407 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000408 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000409 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
Douglas Gregoradee3e32009-11-11 23:06:43 +0000411 // Mismatch of non-dependent template parameter to argument.
412 Info.FirstArg = TemplateArgument(Param);
413 Info.SecondArg = TemplateArgument(Arg);
414 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000415}
416
Mike Stump11289f42009-09-09 15:08:12 +0000417/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000418/// type (which is a template-id) with the template argument type.
419///
Chandler Carruthc1263112010-02-07 21:33:28 +0000420/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000421///
422/// \param TemplateParams the template parameters that we are deducing
423///
424/// \param Param the parameter type
425///
426/// \param Arg the argument type
427///
428/// \param Info information about the template argument deduction itself
429///
430/// \param Deduced the deduced template arguments
431///
432/// \returns the result of template argument deduction so far. Note that a
433/// "success" result means that template argument deduction has not yet failed,
434/// but it may still fail, later, for other reasons.
435static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000436DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000437 TemplateParameterList *TemplateParams,
438 const TemplateSpecializationType *Param,
439 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000440 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000441 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000442 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000443
Douglas Gregore81f3e72009-07-07 23:09:34 +0000444 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000445 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000446 = dyn_cast<TemplateSpecializationType>(Arg)) {
447 // Perform template argument deduction for the template name.
448 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000449 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000450 Param->getTemplateName(),
451 SpecArg->getTemplateName(),
452 Info, Deduced))
453 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000454
Mike Stump11289f42009-09-09 15:08:12 +0000455
Douglas Gregore81f3e72009-07-07 23:09:34 +0000456 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000457 // argument. Ignore any missing/extra arguments, since they could be
458 // filled in by default arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459 return DeduceTemplateArguments(S, TemplateParams,
460 Param->getArgs(), Param->getNumArgs(),
Douglas Gregord80ea202010-12-22 18:55:49 +0000461 SpecArg->getArgs(), SpecArg->getNumArgs(),
Richard Smith16b65392012-12-06 06:44:44 +0000462 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000463 }
Mike Stump11289f42009-09-09 15:08:12 +0000464
Douglas Gregore81f3e72009-07-07 23:09:34 +0000465 // If the argument type is a class template specialization, we
466 // perform template argument deduction using its template
467 // arguments.
468 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000469 if (!RecordArg) {
470 Info.FirstArg = TemplateArgument(QualType(Param, 0));
471 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000472 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
475 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000476 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000477 if (!SpecArg) {
478 Info.FirstArg = TemplateArgument(QualType(Param, 0));
479 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000480 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Douglas Gregore81f3e72009-07-07 23:09:34 +0000483 // Perform template argument deduction for the template name.
484 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000485 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000486 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000487 Param->getTemplateName(),
488 TemplateName(SpecArg->getSpecializedTemplate()),
489 Info, Deduced))
490 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregor7baabef2010-12-22 18:17:10 +0000492 // Perform template argument deduction for the template arguments.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000494 Param->getArgs(), Param->getNumArgs(),
495 SpecArg->getTemplateArgs().data(),
496 SpecArg->getTemplateArgs().size(),
497 Info, Deduced);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498}
499
John McCall08569062010-08-28 22:14:41 +0000500/// \brief Determines whether the given type is an opaque type that
501/// might be more qualified when instantiated.
502static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
503 switch (T->getTypeClass()) {
504 case Type::TypeOfExpr:
505 case Type::TypeOf:
506 case Type::DependentName:
507 case Type::Decltype:
508 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000509 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000510 return true;
511
512 case Type::ConstantArray:
513 case Type::IncompleteArray:
514 case Type::VariableArray:
515 case Type::DependentSizedArray:
516 return IsPossiblyOpaquelyQualifiedType(
517 cast<ArrayType>(T)->getElementType());
518
519 default:
520 return false;
521 }
522}
523
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000524/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000525static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000526getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000527 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
528 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000529
Douglas Gregor5499af42011-01-05 23:12:31 +0000530 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
531 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000532
Douglas Gregor5499af42011-01-05 23:12:31 +0000533 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
534 return std::make_pair(TTP->getDepth(), TTP->getIndex());
535}
536
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000537/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000538static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000539getDepthAndIndex(UnexpandedParameterPack UPP) {
540 if (const TemplateTypeParmType *TTP
541 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
542 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000543
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000544 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
545}
546
Douglas Gregor5499af42011-01-05 23:12:31 +0000547/// \brief Helper function to build a TemplateParameter when we don't
548/// know its type statically.
549static TemplateParameter makeTemplateParameter(Decl *D) {
550 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
551 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000552 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000553 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000554
Douglas Gregor5499af42011-01-05 23:12:31 +0000555 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
556}
557
Richard Smith0a80d572014-05-29 01:12:14 +0000558/// A pack that we're currently deducing.
559struct clang::DeducedPack {
560 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000561
Richard Smith0a80d572014-05-29 01:12:14 +0000562 // The index of the pack.
563 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564
Richard Smith0a80d572014-05-29 01:12:14 +0000565 // The old value of the pack before we started deducing it.
566 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000567
Richard Smith0a80d572014-05-29 01:12:14 +0000568 // A deferred value of this pack from an inner deduction, that couldn't be
569 // deduced because this deduction hadn't happened yet.
570 DeducedTemplateArgument DeferredDeduction;
571
572 // The new value of the pack.
573 SmallVector<DeducedTemplateArgument, 4> New;
574
575 // The outer deduction for this pack, if any.
576 DeducedPack *Outer;
577};
578
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000579namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000580/// A scope in which we're performing pack deduction.
581class PackDeductionScope {
582public:
583 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
584 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
585 TemplateDeductionInfo &Info, TemplateArgument Pattern)
586 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
587 // Compute the set of template parameter indices that correspond to
588 // parameter packs expanded by the pack expansion.
589 {
590 llvm::SmallBitVector SawIndices(TemplateParams->size());
591 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
592 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
593 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
594 unsigned Depth, Index;
595 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
596 if (Depth == 0 && !SawIndices[Index]) {
597 SawIndices[Index] = true;
598
599 // Save the deduced template argument for the parameter pack expanded
600 // by this pack expansion, then clear out the deduction.
601 DeducedPack Pack(Index);
602 Pack.Saved = Deduced[Index];
603 Deduced[Index] = TemplateArgument();
604
605 Packs.push_back(Pack);
606 }
607 }
608 }
609 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
610
611 for (auto &Pack : Packs) {
612 if (Info.PendingDeducedPacks.size() > Pack.Index)
613 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
614 else
615 Info.PendingDeducedPacks.resize(Pack.Index + 1);
616 Info.PendingDeducedPacks[Pack.Index] = &Pack;
617
618 if (S.CurrentInstantiationScope) {
619 // If the template argument pack was explicitly specified, add that to
620 // the set of deduced arguments.
621 const TemplateArgument *ExplicitArgs;
622 unsigned NumExplicitArgs;
623 NamedDecl *PartiallySubstitutedPack =
624 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
625 &ExplicitArgs, &NumExplicitArgs);
626 if (PartiallySubstitutedPack &&
627 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
628 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
629 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000630 }
631 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000632
Richard Smith0a80d572014-05-29 01:12:14 +0000633 ~PackDeductionScope() {
634 for (auto &Pack : Packs)
635 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000636 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000637
Richard Smith0a80d572014-05-29 01:12:14 +0000638 /// Move to deducing the next element in each pack that is being deduced.
639 void nextPackElement() {
640 // Capture the deduced template arguments for each parameter pack expanded
641 // by this pack expansion, add them to the list of arguments we've deduced
642 // for that pack, then clear out the deduced argument.
643 for (auto &Pack : Packs) {
644 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
645 if (!DeducedArg.isNull()) {
646 Pack.New.push_back(DeducedArg);
647 DeducedArg = DeducedTemplateArgument();
648 }
649 }
650 }
651
652 /// \brief Finish template argument deduction for a set of argument packs,
653 /// producing the argument packs and checking for consistency with prior
654 /// deductions.
655 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
656 // Build argument packs for each of the parameter packs expanded by this
657 // pack expansion.
658 for (auto &Pack : Packs) {
659 // Put back the old value for this pack.
660 Deduced[Pack.Index] = Pack.Saved;
661
662 // Build or find a new value for this pack.
663 DeducedTemplateArgument NewPack;
664 if (HasAnyArguments && Pack.New.empty()) {
665 if (Pack.DeferredDeduction.isNull()) {
666 // We were not able to deduce anything for this parameter pack
667 // (because it only appeared in non-deduced contexts), so just
668 // restore the saved argument pack.
669 continue;
670 }
671
672 NewPack = Pack.DeferredDeduction;
673 Pack.DeferredDeduction = TemplateArgument();
674 } else if (Pack.New.empty()) {
675 // If we deduced an empty argument pack, create it now.
676 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
677 } else {
678 TemplateArgument *ArgumentPack =
679 new (S.Context) TemplateArgument[Pack.New.size()];
680 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
681 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000682 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000683 Pack.New[0].wasDeducedFromArrayBound());
684 }
685
686 // Pick where we're going to put the merged pack.
687 DeducedTemplateArgument *Loc;
688 if (Pack.Outer) {
689 if (Pack.Outer->DeferredDeduction.isNull()) {
690 // Defer checking this pack until we have a complete pack to compare
691 // it against.
692 Pack.Outer->DeferredDeduction = NewPack;
693 continue;
694 }
695 Loc = &Pack.Outer->DeferredDeduction;
696 } else {
697 Loc = &Deduced[Pack.Index];
698 }
699
700 // Check the new pack matches any previous value.
701 DeducedTemplateArgument OldPack = *Loc;
702 DeducedTemplateArgument Result =
703 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
704
705 // If we deferred a deduction of this pack, check that one now too.
706 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
707 OldPack = Result;
708 NewPack = Pack.DeferredDeduction;
709 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
710 }
711
712 if (Result.isNull()) {
713 Info.Param =
714 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
715 Info.FirstArg = OldPack;
716 Info.SecondArg = NewPack;
717 return Sema::TDK_Inconsistent;
718 }
719
720 *Loc = Result;
721 }
722
723 return Sema::TDK_Success;
724 }
725
726private:
727 Sema &S;
728 TemplateParameterList *TemplateParams;
729 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
730 TemplateDeductionInfo &Info;
731
732 SmallVector<DeducedPack, 2> Packs;
733};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000734} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000735
Douglas Gregor5499af42011-01-05 23:12:31 +0000736/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000737/// types to the list of argument types, as in the parameter-type-lists of
738/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000739///
740/// \param S The semantic analysis object within which we are deducing
741///
742/// \param TemplateParams The template parameters that we are deducing
743///
744/// \param Params The list of parameter types
745///
746/// \param NumParams The number of types in \c Params
747///
748/// \param Args The list of argument types
749///
750/// \param NumArgs The number of types in \c Args
751///
752/// \param Info information about the template argument deduction itself
753///
754/// \param Deduced the deduced template arguments
755///
756/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
757/// how template argument deduction is performed.
758///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000759/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000760/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000761/// (C++0x [temp.deduct.partial]).
762///
Douglas Gregor5499af42011-01-05 23:12:31 +0000763/// \returns the result of template argument deduction so far. Note that a
764/// "success" result means that template argument deduction has not yet failed,
765/// but it may still fail, later, for other reasons.
766static Sema::TemplateDeductionResult
767DeduceTemplateArguments(Sema &S,
768 TemplateParameterList *TemplateParams,
769 const QualType *Params, unsigned NumParams,
770 const QualType *Args, unsigned NumArgs,
771 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000772 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000773 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000774 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000775 // Fast-path check to see if we have too many/too few arguments.
776 if (NumParams != NumArgs &&
777 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
778 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000779 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780
Douglas Gregor5499af42011-01-05 23:12:31 +0000781 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782 // Similarly, if P has a form that contains (T), then each parameter type
783 // Pi of the respective parameter-type- list of P is compared with the
784 // corresponding parameter type Ai of the corresponding parameter-type-list
785 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000786 unsigned ArgIdx = 0, ParamIdx = 0;
787 for (; ParamIdx != NumParams; ++ParamIdx) {
788 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000790 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
791 if (!Expansion) {
792 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000793
Douglas Gregor5499af42011-01-05 23:12:31 +0000794 // Make sure we have an argument.
795 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000796 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000797
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000798 if (isa<PackExpansionType>(Args[ArgIdx])) {
799 // C++0x [temp.deduct.type]p22:
800 // If the original function parameter associated with A is a function
801 // parameter pack and the function parameter associated with P is not
802 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000803 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805
Douglas Gregor5499af42011-01-05 23:12:31 +0000806 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000807 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
808 Params[ParamIdx], Args[ArgIdx],
809 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000810 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000811 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000812
Douglas Gregor5499af42011-01-05 23:12:31 +0000813 ++ArgIdx;
814 continue;
815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000817 // C++0x [temp.deduct.type]p5:
818 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000819 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000820 // parameter-declaration-clause.
821 if (ParamIdx + 1 < NumParams)
822 return Sema::TDK_Success;
823
Douglas Gregor5499af42011-01-05 23:12:31 +0000824 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000825 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000826 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000828 // comparison deduces template arguments for subsequent positions in the
829 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000830
Douglas Gregor5499af42011-01-05 23:12:31 +0000831 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000832 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000833
Douglas Gregor5499af42011-01-05 23:12:31 +0000834 bool HasAnyArguments = false;
835 for (; ArgIdx < NumArgs; ++ArgIdx) {
836 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000837
Douglas Gregor5499af42011-01-05 23:12:31 +0000838 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000840 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
841 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000842 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Richard Smith0a80d572014-05-29 01:12:14 +0000845 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000847
Douglas Gregor5499af42011-01-05 23:12:31 +0000848 // Build argument packs for each of the parameter packs expanded by this
849 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000850 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000853
Douglas Gregor5499af42011-01-05 23:12:31 +0000854 // Make sure we don't have any extra arguments.
855 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000856 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857
Douglas Gregor5499af42011-01-05 23:12:31 +0000858 return Sema::TDK_Success;
859}
860
Douglas Gregor1d684c22011-04-28 00:56:09 +0000861/// \brief Determine whether the parameter has qualifiers that are either
862/// inconsistent with or a superset of the argument's qualifiers.
863static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
864 QualType ArgType) {
865 Qualifiers ParamQs = ParamType.getQualifiers();
866 Qualifiers ArgQs = ArgType.getQualifiers();
867
868 if (ParamQs == ArgQs)
869 return false;
870
871 // Mismatched (but not missing) Objective-C GC attributes.
872 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
873 ParamQs.hasObjCGCAttr())
874 return true;
875
876 // Mismatched (but not missing) address spaces.
877 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
878 ParamQs.hasAddressSpace())
879 return true;
880
John McCall31168b02011-06-15 23:02:42 +0000881 // Mismatched (but not missing) Objective-C lifetime qualifiers.
882 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
883 ParamQs.hasObjCLifetime())
884 return true;
885
Douglas Gregor1d684c22011-04-28 00:56:09 +0000886 // CVR qualifier superset.
887 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
888 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
889 == ParamQs.getCVRQualifiers());
890}
891
Douglas Gregor19a41f12013-04-17 08:45:07 +0000892/// \brief Compare types for equality with respect to possibly compatible
893/// function types (noreturn adjustment, implicit calling conventions). If any
894/// of parameter and argument is not a function, just perform type comparison.
895///
896/// \param Param the template parameter type.
897///
898/// \param Arg the argument type.
899bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
900 CanQualType Arg) {
901 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
902 *ArgFunction = Arg->getAs<FunctionType>();
903
904 // Just compare if not functions.
905 if (!ParamFunction || !ArgFunction)
906 return Param == Arg;
907
908 // Noreturn adjustment.
909 QualType AdjustedParam;
910 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
911 return Arg == Context.getCanonicalType(AdjustedParam);
912
913 // FIXME: Compatible calling conventions.
914
915 return Param == Arg;
916}
917
Douglas Gregorcceb9752009-06-26 18:27:22 +0000918/// \brief Deduce the template arguments by comparing the parameter type and
919/// the argument type (C++ [temp.deduct.type]).
920///
Chandler Carruthc1263112010-02-07 21:33:28 +0000921/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000922///
923/// \param TemplateParams the template parameters that we are deducing
924///
925/// \param ParamIn the parameter type
926///
927/// \param ArgIn the argument type
928///
929/// \param Info information about the template argument deduction itself
930///
931/// \param Deduced the deduced template arguments
932///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000933/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000934/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000935///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000936/// \param PartialOrdering Whether we're performing template argument deduction
937/// in the context of partial ordering (C++0x [temp.deduct.partial]).
938///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000939/// \returns the result of template argument deduction so far. Note that a
940/// "success" result means that template argument deduction has not yet failed,
941/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000942static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000943DeduceTemplateArgumentsByTypeMatch(Sema &S,
944 TemplateParameterList *TemplateParams,
945 QualType ParamIn, QualType ArgIn,
946 TemplateDeductionInfo &Info,
947 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
948 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000949 bool PartialOrdering) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000950 // We only want to look at the canonical types, since typedefs and
951 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000952 QualType Param = S.Context.getCanonicalType(ParamIn);
953 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000954
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000955 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000956 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000957 if (const PackExpansionType *ArgExpansion
958 = dyn_cast<PackExpansionType>(Arg))
959 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000960
Douglas Gregorb837ea42011-01-11 17:34:58 +0000961 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000962 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000963 // Before the partial ordering is done, certain transformations are
964 // performed on the types used for partial ordering:
965 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +0000966 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
967 if (ParamRef)
968 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregorb837ea42011-01-11 17:34:58 +0000970 // - If A is a reference type, A is replaced by the type referred to.
971 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
972 if (ArgRef)
973 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000974
Richard Smithed563c22015-02-20 04:45:22 +0000975 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
976 // C++11 [temp.deduct.partial]p9:
977 // If, for a given type, deduction succeeds in both directions (i.e.,
978 // the types are identical after the transformations above) and both
979 // P and A were reference types [...]:
980 // - if [one type] was an lvalue reference and [the other type] was
981 // not, [the other type] is not considered to be at least as
982 // specialized as [the first type]
983 // - if [one type] is more cv-qualified than [the other type],
984 // [the other type] is not considered to be at least as specialized
985 // as [the first type]
986 // Objective-C ARC adds:
987 // - [one type] has non-trivial lifetime, [the other type] has
988 // __unsafe_unretained lifetime, and the types are otherwise
989 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +0000990 //
Richard Smithed563c22015-02-20 04:45:22 +0000991 // A is "considered to be at least as specialized" as P iff deduction
992 // succeeds, so we model this as a deduction failure. Note that
993 // [the first type] is P and [the other type] is A here; the standard
994 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +0000995 Qualifiers ParamQuals = Param.getQualifiers();
996 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +0000997 if ((ParamRef->isLValueReferenceType() &&
998 !ArgRef->isLValueReferenceType()) ||
999 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1000 (ParamQuals.hasNonTrivialObjCLifetime() &&
1001 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1002 ParamQuals.withoutObjCLifetime() ==
1003 ArgQuals.withoutObjCLifetime())) {
1004 Info.FirstArg = TemplateArgument(ParamIn);
1005 Info.SecondArg = TemplateArgument(ArgIn);
1006 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001007 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001009
Richard Smithed563c22015-02-20 04:45:22 +00001010 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001011 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001013 // version of P.
1014 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001016 // version of A.
1017 Arg = Arg.getUnqualifiedType();
1018 } else {
1019 // C++0x [temp.deduct.call]p4 bullet 1:
1020 // - If the original P is a reference type, the deduced A (i.e., the type
1021 // referred to by the reference) can be more cv-qualified than the
1022 // transformed A.
1023 if (TDF & TDF_ParamWithReferenceType) {
1024 Qualifiers Quals;
1025 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1026 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001027 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001028 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001030
Douglas Gregor85f240c2011-01-25 17:19:08 +00001031 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1032 // C++0x [temp.deduct.type]p10:
1033 // If P and A are function types that originated from deduction when
1034 // taking the address of a function template (14.8.2.2) or when deducing
1035 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036 // Ai are parameters of the top-level parameter-type-list of P and A,
1037 // respectively, Pi is adjusted if it is an rvalue reference to a
1038 // cv-unqualified template parameter and Ai is an lvalue reference, in
1039 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001040 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1041 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001042 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001043 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Douglas Gregor85f240c2011-01-25 17:19:08 +00001045 if (const RValueReferenceType *ParamRef
1046 = Param->getAs<RValueReferenceType>()) {
1047 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1048 !ParamRef->getPointeeType().getQualifiers())
1049 if (Arg->isLValueReferenceType())
1050 Param = ParamRef->getPointeeType();
1051 }
1052 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001054
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001055 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001056 // A template type argument T, a template template argument TT or a
1057 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001058 // the following forms:
1059 //
1060 // T
1061 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001062 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001063 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001064 // Just skip any attempts to deduce from a placeholder type.
1065 if (Arg->isPlaceholderType())
1066 return Sema::TDK_Success;
1067
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001068 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001069 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001070
Douglas Gregor60454822009-07-22 20:02:25 +00001071 // If the argument type is an array type, move the qualifiers up to the
1072 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001073 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001074 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001075 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001076 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001077 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001078 RecanonicalizeArg = true;
1079 }
1080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001082 // The argument type can not be less qualified than the parameter
1083 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001084 if (!(TDF & TDF_IgnoreQualifiers) &&
1085 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001086 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001087 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001088 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001089 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001090 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001091
1092 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001093 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001094 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001095
Douglas Gregor1d684c22011-04-28 00:56:09 +00001096 // Remove any qualifiers on the parameter from the deduced type.
1097 // We checked the qualifiers for consistency above.
1098 Qualifiers DeducedQs = DeducedType.getQualifiers();
1099 Qualifiers ParamQs = Param.getQualifiers();
1100 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1101 if (ParamQs.hasObjCGCAttr())
1102 DeducedQs.removeObjCGCAttr();
1103 if (ParamQs.hasAddressSpace())
1104 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001105 if (ParamQs.hasObjCLifetime())
1106 DeducedQs.removeObjCLifetime();
Douglas Gregore46db902011-06-17 22:11:49 +00001107
1108 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001109 // If template deduction would produce a lifetime qualifier on a type
1110 // that is not a lifetime type, template argument deduction fails.
1111 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1112 !DeducedType->isDependentType()) {
1113 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1114 Info.FirstArg = TemplateArgument(Param);
1115 Info.SecondArg = TemplateArgument(Arg);
1116 return Sema::TDK_Underqualified;
1117 }
1118
1119 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001120 // If template deduction would produce an argument type with lifetime type
1121 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001122 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001123 DeducedType->isObjCLifetimeType() &&
1124 !DeducedQs.hasObjCLifetime())
1125 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1126
Douglas Gregor1d684c22011-04-28 00:56:09 +00001127 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1128 DeducedQs);
1129
Douglas Gregord6605db2009-07-22 21:30:48 +00001130 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001131 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001132
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001133 DeducedTemplateArgument NewDeduced(DeducedType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001134 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001135 Deduced[Index],
1136 NewDeduced);
1137 if (Result.isNull()) {
1138 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1139 Info.FirstArg = Deduced[Index];
1140 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001142 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001143
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001144 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001145 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001146 }
1147
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001148 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001149 Info.FirstArg = TemplateArgument(ParamIn);
1150 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001151
Douglas Gregorfb322d82011-01-14 05:11:40 +00001152 // If the parameter is an already-substituted template parameter
1153 // pack, do nothing: we don't know which of its arguments to look
1154 // at, so we have to wait until all of the parameter packs in this
1155 // expansion have arguments.
1156 if (isa<SubstTemplateTypeParmPackType>(Param))
1157 return Sema::TDK_Success;
1158
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001159 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001160 CanQualType CanParam = S.Context.getCanonicalType(Param);
1161 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001162 if (!(TDF & TDF_IgnoreQualifiers)) {
1163 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001164 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001165 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001166 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001167 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001168 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001169 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001170
1171 // If the parameter type is not dependent, there is nothing to deduce.
1172 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001173 if (!(TDF & TDF_SkipNonDependent)) {
1174 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1175 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1176 Param != Arg;
1177 if (NonDeduced) {
1178 return Sema::TDK_NonDeducedMismatch;
1179 }
1180 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001181 return Sema::TDK_Success;
1182 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001183 } else if (!Param->isDependentType()) {
1184 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1185 ArgUnqualType = CanArg.getUnqualifiedType();
1186 bool Success = (TDF & TDF_InOverloadResolution)?
1187 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1188 ArgUnqualType) :
1189 ParamUnqualType == ArgUnqualType;
1190 if (Success)
1191 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001192 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001193
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001194 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001195 // Non-canonical types cannot appear here.
1196#define NON_CANONICAL_TYPE(Class, Base) \
1197 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1198#define TYPE(Class, Base)
1199#include "clang/AST/TypeNodes.def"
1200
1201 case Type::TemplateTypeParm:
1202 case Type::SubstTemplateTypeParmPack:
1203 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001204
1205 // These types cannot be dependent, so simply check whether the types are
1206 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001207 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001208 case Type::VariableArray:
1209 case Type::Vector:
1210 case Type::FunctionNoProto:
1211 case Type::Record:
1212 case Type::Enum:
1213 case Type::ObjCObject:
1214 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001215 case Type::ObjCObjectPointer: {
1216 if (TDF & TDF_SkipNonDependent)
1217 return Sema::TDK_Success;
1218
1219 if (TDF & TDF_IgnoreQualifiers) {
1220 Param = Param.getUnqualifiedType();
1221 Arg = Arg.getUnqualifiedType();
1222 }
1223
1224 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1225 }
1226
Douglas Gregor39c02722011-06-15 16:02:29 +00001227 // _Complex T [placeholder extension]
1228 case Type::Complex:
1229 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001230 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor39c02722011-06-15 16:02:29 +00001231 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001232 ComplexArg->getElementType(),
1233 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001234
1235 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001236
1237 // _Atomic T [extension]
1238 case Type::Atomic:
1239 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001240 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001241 cast<AtomicType>(Param)->getValueType(),
1242 AtomicArg->getValueType(),
1243 Info, Deduced, TDF);
1244
1245 return Sema::TDK_NonDeducedMismatch;
1246
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001247 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001248 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001249 QualType PointeeType;
1250 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1251 PointeeType = PointerArg->getPointeeType();
1252 } else if (const ObjCObjectPointerType *PointerArg
1253 = Arg->getAs<ObjCObjectPointerType>()) {
1254 PointeeType = PointerArg->getPointeeType();
1255 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001256 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001257 }
Mike Stump11289f42009-09-09 15:08:12 +00001258
Douglas Gregorfc516c92009-06-26 23:27:24 +00001259 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001260 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1261 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001262 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001263 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001264 }
Mike Stump11289f42009-09-09 15:08:12 +00001265
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001266 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001267 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001268 const LValueReferenceType *ReferenceArg =
1269 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001270 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001271 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001272
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001273 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001274 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001275 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001276 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001277
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001278 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001279 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001280 const RValueReferenceType *ReferenceArg =
1281 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001282 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001283 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001284
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001285 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1286 cast<RValueReferenceType>(Param)->getPointeeType(),
1287 ReferenceArg->getPointeeType(),
1288 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001291 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001292 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001293 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001294 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001295 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001296 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001297
John McCallf7332682010-08-19 00:20:19 +00001298 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001299 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1300 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1301 IncompleteArrayArg->getElementType(),
1302 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001303 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001304
1305 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001306 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001307 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001308 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001309 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001310 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001311
1312 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001313 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001314 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001315 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001316
John McCallf7332682010-08-19 00:20:19 +00001317 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001318 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1319 ConstantArrayParm->getElementType(),
1320 ConstantArrayArg->getElementType(),
1321 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001322 }
1323
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001324 // type [i]
1325 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001326 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001327 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001328 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001329
John McCallf7332682010-08-19 00:20:19 +00001330 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1331
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001332 // Check the element type of the arrays
1333 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001334 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001335 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001336 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1337 DependentArrayParm->getElementType(),
1338 ArrayArg->getElementType(),
1339 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001340 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001342 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001343 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001344 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1345 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001346 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001347
1348 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001349 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001350 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001351 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001352 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001353 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1354 llvm::APSInt Size(ConstantArrayArg->getSize());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355 return DeduceNonTypeTemplateArgument(S, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001356 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001357 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001358 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001359 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001360 if (const DependentSizedArrayType *DependentArrayArg
1361 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001362 if (DependentArrayArg->getSizeExpr())
1363 return DeduceNonTypeTemplateArgument(S, NTTP,
1364 DependentArrayArg->getSizeExpr(),
1365 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001366
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001367 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001368 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001369 }
Mike Stump11289f42009-09-09 15:08:12 +00001370
1371 // type(*)(T)
1372 // T(*)()
1373 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001374 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001375 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001376 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001377 dyn_cast<FunctionProtoType>(Arg);
1378 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001379 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001380
1381 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001382 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001383
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001385 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001386 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001387 != FunctionProtoArg->getRefQualifier() ||
1388 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001389 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001390
Anders Carlsson2128ec72009-06-08 15:19:08 +00001391 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001392 if (Sema::TemplateDeductionResult Result =
1393 DeduceTemplateArgumentsByTypeMatch(
1394 S, TemplateParams, FunctionProtoParam->getReturnType(),
1395 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001396 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001397
Alp Toker9cacbab2014-01-20 20:26:09 +00001398 return DeduceTemplateArguments(
1399 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1400 FunctionProtoParam->getNumParams(),
1401 FunctionProtoArg->param_type_begin(),
1402 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001403 }
Mike Stump11289f42009-09-09 15:08:12 +00001404
John McCalle78aac42010-03-10 03:28:59 +00001405 case Type::InjectedClassName: {
1406 // Treat a template's injected-class-name as if the template
1407 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001408 Param = cast<InjectedClassNameType>(Param)
1409 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001410 assert(isa<TemplateSpecializationType>(Param) &&
1411 "injected class name is not a template specialization type");
1412 // fall through
1413 }
1414
Douglas Gregor705c9002009-06-26 20:57:09 +00001415 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001416 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001417 // TT<T>
1418 // TT<i>
1419 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001420 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001421 const TemplateSpecializationType *SpecParam =
1422 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001423
Richard Smith9b296e32016-04-25 19:09:05 +00001424 // When Arg cannot be a derived class, we can just try to deduce template
1425 // arguments from the template-id.
1426 const RecordType *RecordT = Arg->getAs<RecordType>();
1427 if (!(TDF & TDF_DerivedClass) || !RecordT)
1428 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1429 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001430
Richard Smith9b296e32016-04-25 19:09:05 +00001431 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1432 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001433
Richard Smith9b296e32016-04-25 19:09:05 +00001434 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1435 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001436
Richard Smith9b296e32016-04-25 19:09:05 +00001437 if (Result == Sema::TDK_Success)
1438 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001439
Richard Smith9b296e32016-04-25 19:09:05 +00001440 // We cannot inspect base classes as part of deduction when the type
1441 // is incomplete, so either instantiate any templates necessary to
1442 // complete the type, or skip over it if it cannot be completed.
1443 if (!S.isCompleteType(Info.getLocation(), Arg))
1444 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001445
Richard Smith9b296e32016-04-25 19:09:05 +00001446 // C++14 [temp.deduct.call] p4b3:
1447 // If P is a class and P has the form simple-template-id, then the
1448 // transformed A can be a derived class of the deduced A. Likewise if
1449 // P is a pointer to a class of the form simple-template-id, the
1450 // transformed A can be a pointer to a derived class pointed to by the
1451 // deduced A.
1452 //
1453 // These alternatives are considered only if type deduction would
1454 // otherwise fail. If they yield more than one possible deduced A, the
1455 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001456
Faisal Vali683b0742016-05-19 02:28:21 +00001457 // Reset the incorrectly deduced argument from above.
1458 Deduced = DeducedOrig;
1459
1460 // Use data recursion to crawl through the list of base classes.
1461 // Visited contains the set of nodes we have already visited, while
1462 // ToVisit is our stack of records that we still need to visit.
1463 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1464 SmallVector<const RecordType *, 8> ToVisit;
1465 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001466 bool Successful = false;
Faisal Vali683b0742016-05-19 02:28:21 +00001467 while (!ToVisit.empty()) {
1468 // Retrieve the next class in the inheritance hierarchy.
1469 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001470
Faisal Vali683b0742016-05-19 02:28:21 +00001471 // If we have already seen this type, skip it.
1472 if (!Visited.insert(NextT).second)
1473 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001474
Faisal Vali683b0742016-05-19 02:28:21 +00001475 // If this is a base class, try to perform template argument
1476 // deduction from it.
1477 if (NextT != RecordT) {
1478 TemplateDeductionInfo BaseInfo(Info.getLocation());
1479 Sema::TemplateDeductionResult BaseResult =
1480 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1481 QualType(NextT, 0), BaseInfo, Deduced);
1482
1483 // If template argument deduction for this base was successful,
1484 // note that we had some success. Otherwise, ignore any deductions
1485 // from this base class.
1486 if (BaseResult == Sema::TDK_Success) {
1487 Successful = true;
1488 DeducedOrig.clear();
1489 DeducedOrig.append(Deduced.begin(), Deduced.end());
1490 Info.Param = BaseInfo.Param;
1491 Info.FirstArg = BaseInfo.FirstArg;
1492 Info.SecondArg = BaseInfo.SecondArg;
1493 } else
1494 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001495 }
Mike Stump11289f42009-09-09 15:08:12 +00001496
Faisal Vali683b0742016-05-19 02:28:21 +00001497 // Visit base classes
1498 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1499 for (const auto &Base : Next->bases()) {
1500 assert(Base.getType()->isRecordType() &&
1501 "Base class that isn't a record?");
1502 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1503 }
1504 }
Mike Stump11289f42009-09-09 15:08:12 +00001505
Richard Smith9b296e32016-04-25 19:09:05 +00001506 if (Successful)
1507 return Sema::TDK_Success;
1508
Douglas Gregore81f3e72009-07-07 23:09:34 +00001509 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001510 }
1511
Douglas Gregor637d9982009-06-10 23:47:09 +00001512 // T type::*
1513 // T T::*
1514 // T (type::*)()
1515 // type (T::*)()
1516 // type (type::*)(T)
1517 // type (T::*)(T)
1518 // T (type::*)(T)
1519 // T (T::*)()
1520 // T (T::*)(T)
1521 case Type::MemberPointer: {
1522 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1523 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1524 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001525 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001526
David Majnemera381cda2015-11-30 20:34:28 +00001527 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1528 if (ParamPointeeType->isFunctionType())
1529 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1530 /*IsCtorOrDtor=*/false, Info.getLocation());
1531 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1532 if (ArgPointeeType->isFunctionType())
1533 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1534 /*IsCtorOrDtor=*/false, Info.getLocation());
1535
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001536 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001537 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001538 ParamPointeeType,
1539 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001540 Info, Deduced,
1541 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001542 return Result;
1543
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001544 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1545 QualType(MemPtrParam->getClass(), 0),
1546 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001547 Info, Deduced,
1548 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001549 }
1550
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001551 // (clang extension)
1552 //
Mike Stump11289f42009-09-09 15:08:12 +00001553 // type(^)(T)
1554 // T(^)()
1555 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001556 case Type::BlockPointer: {
1557 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1558 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001559
Anders Carlssona767eee2009-06-12 16:23:10 +00001560 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001561 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001562
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001563 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1564 BlockPtrParam->getPointeeType(),
1565 BlockPtrArg->getPointeeType(),
1566 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001567 }
1568
Douglas Gregor39c02722011-06-15 16:02:29 +00001569 // (clang extension)
1570 //
1571 // T __attribute__(((ext_vector_type(<integral constant>))))
1572 case Type::ExtVector: {
1573 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1574 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1575 // Make sure that the vectors have the same number of elements.
1576 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1577 return Sema::TDK_NonDeducedMismatch;
1578
1579 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001580 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1581 VectorParam->getElementType(),
1582 VectorArg->getElementType(),
1583 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001584 }
1585
1586 if (const DependentSizedExtVectorType *VectorArg
1587 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1588 // We can't check the number of elements, since the argument has a
1589 // dependent number of elements. This can only occur during partial
1590 // ordering.
1591
1592 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001593 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1594 VectorParam->getElementType(),
1595 VectorArg->getElementType(),
1596 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001597 }
1598
1599 return Sema::TDK_NonDeducedMismatch;
1600 }
1601
1602 // (clang extension)
1603 //
1604 // T __attribute__(((ext_vector_type(N))))
1605 case Type::DependentSizedExtVector: {
1606 const DependentSizedExtVectorType *VectorParam
1607 = cast<DependentSizedExtVectorType>(Param);
1608
1609 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1610 // Perform deduction on the element types.
1611 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001612 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1613 VectorParam->getElementType(),
1614 VectorArg->getElementType(),
1615 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001616 return Result;
1617
1618 // Perform deduction on the vector size, if we can.
1619 NonTypeTemplateParmDecl *NTTP
1620 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1621 if (!NTTP)
1622 return Sema::TDK_Success;
1623
1624 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1625 ArgSize = VectorArg->getNumElements();
1626 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1627 false, Info, Deduced);
1628 }
1629
1630 if (const DependentSizedExtVectorType *VectorArg
1631 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1632 // Perform deduction on the element types.
1633 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001634 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1635 VectorParam->getElementType(),
1636 VectorArg->getElementType(),
1637 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001638 return Result;
1639
1640 // Perform deduction on the vector size, if we can.
1641 NonTypeTemplateParmDecl *NTTP
1642 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1643 if (!NTTP)
1644 return Sema::TDK_Success;
1645
1646 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1647 Info, Deduced);
1648 }
1649
1650 return Sema::TDK_NonDeducedMismatch;
1651 }
1652
Douglas Gregor637d9982009-06-10 23:47:09 +00001653 case Type::TypeOfExpr:
1654 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001655 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001656 case Type::UnresolvedUsing:
1657 case Type::Decltype:
1658 case Type::UnaryTransform:
1659 case Type::Auto:
1660 case Type::DependentTemplateSpecialization:
1661 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001662 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001663 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001664 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001665 }
1666
David Blaikiee4d798f2012-01-20 21:50:17 +00001667 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001668}
1669
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001670static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001671DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001672 TemplateParameterList *TemplateParams,
1673 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001674 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001675 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001676 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001677 // If the template argument is a pack expansion, perform template argument
1678 // deduction against the pattern of that expansion. This only occurs during
1679 // partial ordering.
1680 if (Arg.isPackExpansion())
1681 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001682
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001683 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001684 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001685 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001686
1687 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001688 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001689 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1690 Param.getAsType(),
1691 Arg.getAsType(),
1692 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001693 Info.FirstArg = Param;
1694 Info.SecondArg = Arg;
1695 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001696
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001697 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001698 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001700 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001701 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001702 Info.FirstArg = Param;
1703 Info.SecondArg = Arg;
1704 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001705
1706 case TemplateArgument::TemplateExpansion:
1707 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001708
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001709 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001710 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001711 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001712 return Sema::TDK_Success;
1713
1714 Info.FirstArg = Param;
1715 Info.SecondArg = Arg;
1716 return Sema::TDK_NonDeducedMismatch;
1717
1718 case TemplateArgument::NullPtr:
1719 if (Arg.getKind() == TemplateArgument::NullPtr &&
1720 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001721 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001722
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001723 Info.FirstArg = Param;
1724 Info.SecondArg = Arg;
1725 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001726
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001727 case TemplateArgument::Integral:
1728 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001729 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001730 return Sema::TDK_Success;
1731
1732 Info.FirstArg = Param;
1733 Info.SecondArg = Arg;
1734 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001735 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001736
1737 if (Arg.getKind() == TemplateArgument::Expression) {
1738 Info.FirstArg = Param;
1739 Info.SecondArg = Arg;
1740 return Sema::TDK_NonDeducedMismatch;
1741 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001742
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001743 Info.FirstArg = Param;
1744 Info.SecondArg = Arg;
1745 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001746
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001747 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001748 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001749 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1750 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001751 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001752 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001753 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001754 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001755 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001756 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001757 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001758 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001759 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001760 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001761 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001762
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001763 Info.FirstArg = Param;
1764 Info.SecondArg = Arg;
1765 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001766 }
Mike Stump11289f42009-09-09 15:08:12 +00001767
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001768 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001769 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001770 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001771 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001772 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001773 }
Mike Stump11289f42009-09-09 15:08:12 +00001774
David Blaikiee4d798f2012-01-20 21:50:17 +00001775 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001776}
1777
Douglas Gregor7baabef2010-12-22 18:17:10 +00001778/// \brief Determine whether there is a template argument to be used for
1779/// deduction.
1780///
1781/// This routine "expands" argument packs in-place, overriding its input
1782/// parameters so that \c Args[ArgIdx] will be the available template argument.
1783///
1784/// \returns true if there is another template argument (which will be at
1785/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001786static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001787 unsigned &ArgIdx,
1788 unsigned &NumArgs) {
1789 if (ArgIdx == NumArgs)
1790 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001791
Douglas Gregor7baabef2010-12-22 18:17:10 +00001792 const TemplateArgument &Arg = Args[ArgIdx];
1793 if (Arg.getKind() != TemplateArgument::Pack)
1794 return true;
1795
1796 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1797 Args = Arg.pack_begin();
1798 NumArgs = Arg.pack_size();
1799 ArgIdx = 0;
1800 return ArgIdx < NumArgs;
1801}
1802
Douglas Gregord0ad2942010-12-23 01:24:45 +00001803/// \brief Determine whether the given set of template arguments has a pack
1804/// expansion that is not the last template argument.
1805static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1806 unsigned NumArgs) {
1807 unsigned ArgIdx = 0;
1808 while (ArgIdx < NumArgs) {
1809 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810
Douglas Gregord0ad2942010-12-23 01:24:45 +00001811 // Unwrap argument packs.
1812 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1813 Args = Arg.pack_begin();
1814 NumArgs = Arg.pack_size();
1815 ArgIdx = 0;
1816 continue;
1817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818
Douglas Gregord0ad2942010-12-23 01:24:45 +00001819 ++ArgIdx;
1820 if (ArgIdx == NumArgs)
1821 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001822
Douglas Gregord0ad2942010-12-23 01:24:45 +00001823 if (Arg.isPackExpansion())
1824 return true;
1825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826
Douglas Gregord0ad2942010-12-23 01:24:45 +00001827 return false;
1828}
1829
Douglas Gregor7baabef2010-12-22 18:17:10 +00001830static Sema::TemplateDeductionResult
1831DeduceTemplateArguments(Sema &S,
1832 TemplateParameterList *TemplateParams,
1833 const TemplateArgument *Params, unsigned NumParams,
1834 const TemplateArgument *Args, unsigned NumArgs,
1835 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +00001836 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001837 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001838 // If the template argument list of P contains a pack expansion that is not
1839 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001840 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001841 if (hasPackExpansionBeforeEnd(Params, NumParams))
1842 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001843
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001844 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001845 // If P has a form that contains <T> or <i>, then each argument Pi of the
1846 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001847 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001848 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001850 ++ParamIdx) {
1851 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001852 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001853
Douglas Gregor7baabef2010-12-22 18:17:10 +00001854 // Check whether we have enough arguments.
1855 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Richard Smith16b65392012-12-06 06:44:44 +00001856 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001857
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001858 if (Args[ArgIdx].isPackExpansion()) {
1859 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1860 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001861 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001863
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001864 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001865 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001866 = DeduceTemplateArguments(S, TemplateParams,
1867 Params[ParamIdx], Args[ArgIdx],
1868 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001869 return Result;
1870
Douglas Gregor7baabef2010-12-22 18:17:10 +00001871 // Move to the next argument.
1872 ++ArgIdx;
1873 continue;
1874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001875
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001876 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001877
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001878 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001879 // If Pi is a pack expansion, then the pattern of Pi is compared with
1880 // each remaining argument in the template argument list of A. Each
1881 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001882 // template parameter packs expanded by Pi.
1883 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001884
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001885 // FIXME: If there are no remaining arguments, we can bail out early
1886 // and set any deduced parameter packs to an empty argument pack.
1887 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888
Richard Smith0a80d572014-05-29 01:12:14 +00001889 // Prepare to deduce the packs within the pattern.
1890 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001891
1892 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001893 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001894 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001895 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001896 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001897 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001898
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001899 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001900 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001901 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1902 Info, Deduced))
1903 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001904
Richard Smith0a80d572014-05-29 01:12:14 +00001905 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001906 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001908 // Build argument packs for each of the parameter packs expanded by this
1909 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001910 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001911 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001912 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913
Douglas Gregor7baabef2010-12-22 18:17:10 +00001914 return Sema::TDK_Success;
1915}
1916
Mike Stump11289f42009-09-09 15:08:12 +00001917static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001918DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001919 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001920 const TemplateArgumentList &ParamList,
1921 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001922 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001923 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001925 ParamList.data(), ParamList.size(),
1926 ArgList.data(), ArgList.size(),
1927 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001928}
1929
Douglas Gregor705c9002009-06-26 20:57:09 +00001930/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001931static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001932 const TemplateArgument &X,
1933 const TemplateArgument &Y) {
1934 if (X.getKind() != Y.getKind())
1935 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001936
Douglas Gregor705c9002009-06-26 20:57:09 +00001937 switch (X.getKind()) {
1938 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001939 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001940
Douglas Gregor705c9002009-06-26 20:57:09 +00001941 case TemplateArgument::Type:
1942 return Context.getCanonicalType(X.getAsType()) ==
1943 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001944
Douglas Gregor705c9002009-06-26 20:57:09 +00001945 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001946 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001947
1948 case TemplateArgument::NullPtr:
1949 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001950
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001951 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001952 case TemplateArgument::TemplateExpansion:
1953 return Context.getCanonicalTemplateName(
1954 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1955 Context.getCanonicalTemplateName(
1956 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957
Douglas Gregor705c9002009-06-26 20:57:09 +00001958 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001959 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001960
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001961 case TemplateArgument::Expression: {
1962 llvm::FoldingSetNodeID XID, YID;
1963 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001964 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001965 return XID == YID;
1966 }
Mike Stump11289f42009-09-09 15:08:12 +00001967
Douglas Gregor705c9002009-06-26 20:57:09 +00001968 case TemplateArgument::Pack:
1969 if (X.pack_size() != Y.pack_size())
1970 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001971
1972 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1973 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001974 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001975 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001976 if (!isSameTemplateArg(Context, *XP, *YP))
1977 return false;
1978
1979 return true;
1980 }
1981
David Blaikiee4d798f2012-01-20 21:50:17 +00001982 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00001983}
1984
Douglas Gregorca4686d2011-01-04 23:35:54 +00001985/// \brief Allocate a TemplateArgumentLoc where all locations have
1986/// been initialized to the given location.
1987///
1988/// \param S The semantic analysis object.
1989///
James Dennett634962f2012-06-14 21:40:34 +00001990/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00001991/// location information for.
1992///
1993/// \param NTTPType For a declaration template argument, the type of
1994/// the non-type template parameter that corresponds to this template
1995/// argument.
1996///
1997/// \param Loc The source location to use for the resulting template
1998/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00002000getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002001 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002002 QualType NTTPType,
2003 SourceLocation Loc) {
2004 switch (Arg.getKind()) {
2005 case TemplateArgument::Null:
2006 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002007
Douglas Gregorca4686d2011-01-04 23:35:54 +00002008 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002009 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002010 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002011
Douglas Gregorca4686d2011-01-04 23:35:54 +00002012 case TemplateArgument::Declaration: {
2013 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00002014 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002015 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002016 return TemplateArgumentLoc(TemplateArgument(E), E);
2017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002018
Eli Friedmanb826a002012-09-26 02:36:12 +00002019 case TemplateArgument::NullPtr: {
2020 Expr *E
2021 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002022 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002023 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2024 E);
2025 }
2026
Douglas Gregorca4686d2011-01-04 23:35:54 +00002027 case TemplateArgument::Integral: {
2028 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002029 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002030 return TemplateArgumentLoc(TemplateArgument(E), E);
2031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002032
Douglas Gregor9d802122011-03-02 17:09:35 +00002033 case TemplateArgument::Template:
2034 case TemplateArgument::TemplateExpansion: {
2035 NestedNameSpecifierLocBuilder Builder;
2036 TemplateName Template = Arg.getAsTemplate();
2037 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2038 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002039 else if (QualifiedTemplateName *QTN =
2040 Template.getAsQualifiedTemplateName())
Douglas Gregor9d802122011-03-02 17:09:35 +00002041 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2042
2043 if (Arg.getKind() == TemplateArgument::Template)
2044 return TemplateArgumentLoc(Arg,
2045 Builder.getWithLocInContext(S.Context),
2046 Loc);
2047
2048
2049 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2050 Loc, Loc);
2051 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002052
Douglas Gregorca4686d2011-01-04 23:35:54 +00002053 case TemplateArgument::Expression:
2054 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002055
Douglas Gregorca4686d2011-01-04 23:35:54 +00002056 case TemplateArgument::Pack:
2057 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059
David Blaikiee4d798f2012-01-20 21:50:17 +00002060 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002061}
2062
2063
2064/// \brief Convert the given deduced template argument and add it to the set of
2065/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002066static bool
2067ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2068 DeducedTemplateArgument Arg,
2069 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002070 TemplateDeductionInfo &Info,
2071 bool InFunctionTemplate,
2072 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002073 // First, for a non-type template parameter type that is
2074 // initialized by a declaration, we need the type of the
2075 // corresponding non-type template parameter.
2076 QualType NTTPType;
2077 if (NonTypeTemplateParmDecl *NTTP =
2078 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2079 NTTPType = NTTP->getType();
2080 if (NTTPType->isDependentType()) {
2081 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2082 Output.data(), Output.size());
2083 NTTPType = S.SubstType(NTTPType,
2084 MultiLevelTemplateArgumentList(TemplateArgs),
2085 NTTP->getLocation(),
2086 NTTP->getDeclName());
2087 if (NTTPType.isNull())
2088 return true;
2089 }
2090 }
2091
2092 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2093 unsigned ArgumentPackIndex) {
2094 // Convert the deduced template argument into a template
2095 // argument that we can check, almost as if the user had written
2096 // the template argument explicitly.
2097 TemplateArgumentLoc ArgLoc =
2098 getTrivialTemplateArgumentLoc(S, Arg, NTTPType, Info.getLocation());
2099
2100 // Check the template argument, converting it as necessary.
2101 return S.CheckTemplateArgument(
2102 Param, ArgLoc, Template, Template->getLocation(),
2103 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2104 InFunctionTemplate
2105 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2106 : Sema::CTAK_Deduced)
2107 : Sema::CTAK_Specified);
2108 };
2109
Douglas Gregorca4686d2011-01-04 23:35:54 +00002110 if (Arg.getKind() == TemplateArgument::Pack) {
2111 // This is a template argument pack, so check each of its arguments against
2112 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002113 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002114 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002115 // When converting the deduced template argument, append it to the
2116 // general output list. We need to do this so that the template argument
2117 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002118 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002119 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002120 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2121 "deduced nested pack");
2122 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002123 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
Douglas Gregor51bc5712011-01-05 20:52:18 +00002125 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002126 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002127 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128
Richard Smithdf18ee92016-02-03 20:40:30 +00002129 // If the pack is empty, we still need to substitute into the parameter
2130 // itself, in case that substitution fails. For non-type parameters, we did
2131 // this above. For type parameters, no substitution is ever required.
2132 auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param);
2133 if (TTP && PackedArgsBuilder.empty()) {
2134 // Set up a template instantiation context.
2135 LocalInstantiationScope Scope(S);
2136 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2137 TTP, Output,
2138 Template->getSourceRange());
2139 if (Inst.isInvalid())
2140 return true;
2141
2142 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2143 Output.data(), Output.size());
2144 if (!S.SubstDecl(TTP, S.CurContext,
2145 MultiLevelTemplateArgumentList(TemplateArgs)))
2146 return true;
2147 }
Richard Smith37acb792016-02-03 20:15:01 +00002148
Douglas Gregorca4686d2011-01-04 23:35:54 +00002149 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002150 Output.push_back(
2151 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002152 return false;
2153 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Richard Smith37acb792016-02-03 20:15:01 +00002155 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002156}
2157
Douglas Gregor684268d2010-04-29 06:21:43 +00002158/// Complete template argument deduction for a class template partial
2159/// specialization.
2160static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002161FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002162 ClassTemplatePartialSpecializationDecl *Partial,
2163 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002164 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002165 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002166 // Unevaluated SFINAE context.
2167 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002168 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002169
Douglas Gregor684268d2010-04-29 06:21:43 +00002170 Sema::ContextRAII SavedContext(S, Partial);
2171
2172 // C++ [temp.deduct.type]p2:
2173 // [...] or if any template argument remains neither deduced nor
2174 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002175 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002176 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2177 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002178 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002179 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002180 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002181 return Sema::TDK_Incomplete;
2182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002183
Douglas Gregorca4686d2011-01-04 23:35:54 +00002184 // We have deduced this argument, so it still needs to be
2185 // checked and converted.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002186 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002187 Partial, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002188 Builder)) {
2189 Info.Param = makeTemplateParameter(Param);
2190 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002191 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2192 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002193 return Sema::TDK_SubstitutionFailure;
2194 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196
Douglas Gregor684268d2010-04-29 06:21:43 +00002197 // Form the template argument list from the deduced template arguments.
2198 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002199 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002200 Builder.size());
2201
Douglas Gregor684268d2010-04-29 06:21:43 +00002202 Info.reset(DeducedArgumentList);
2203
2204 // Substitute the deduced template arguments into the template
2205 // arguments of the class template partial specialization, and
2206 // verify that the instantiated template arguments are both valid
2207 // and are equivalent to the template arguments originally provided
2208 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002209 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002210 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002211 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002212 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002213 const TemplateArgumentLoc *PartialTemplateArgs
2214 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002215
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002216 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2217 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002218
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002219 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002220 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2221 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2222 if (ParamIdx >= Partial->getTemplateParameters()->size())
2223 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2224
2225 Decl *Param
2226 = const_cast<NamedDecl *>(
2227 Partial->getTemplateParameters()->getParam(ParamIdx));
2228 Info.Param = makeTemplateParameter(Param);
2229 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2230 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002231 }
2232
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002233 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002234 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002235 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002236 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002237
Douglas Gregorca4686d2011-01-04 23:35:54 +00002238 TemplateParameterList *TemplateParams
2239 = ClassTemplate->getTemplateParameters();
2240 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002241 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002242 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002243 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002244 Info.FirstArg = TemplateArgs[I];
2245 Info.SecondArg = InstArg;
2246 return Sema::TDK_NonDeducedMismatch;
2247 }
2248 }
2249
2250 if (Trap.hasErrorOccurred())
2251 return Sema::TDK_SubstitutionFailure;
2252
2253 return Sema::TDK_Success;
2254}
2255
Douglas Gregor170bc422009-06-12 22:31:52 +00002256/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002257/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002258/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002259Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002260Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002261 const TemplateArgumentList &TemplateArgs,
2262 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002263 if (Partial->isInvalidDecl())
2264 return TDK_Invalid;
2265
Douglas Gregor170bc422009-06-12 22:31:52 +00002266 // C++ [temp.class.spec.match]p2:
2267 // A partial specialization matches a given actual template
2268 // argument list if the template arguments of the partial
2269 // specialization can be deduced from the actual template argument
2270 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002271
2272 // Unevaluated SFINAE context.
2273 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002274 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002275
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002276 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002277 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002278 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002279 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002280 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002281 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002282 TemplateArgs, Info, Deduced))
2283 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002284
Richard Smith80934652012-07-16 01:09:10 +00002285 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002286 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2287 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002288 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002289 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002290
Douglas Gregore1416332009-06-14 08:02:22 +00002291 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002292 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002293
2294 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002295 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002296}
Douglas Gregor91772d12009-06-13 00:26:55 +00002297
Larisse Voufo39a1e502013-08-06 01:03:05 +00002298/// Complete template argument deduction for a variable template partial
2299/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002300/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2301/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2302/// VarTemplate(Partial)SpecializationDecl with a new data
2303/// structure Template(Partial)SpecializationDecl, and
2304/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002305static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2306 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2307 const TemplateArgumentList &TemplateArgs,
2308 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2309 TemplateDeductionInfo &Info) {
2310 // Unevaluated SFINAE context.
2311 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2312 Sema::SFINAETrap Trap(S);
2313
2314 // C++ [temp.deduct.type]p2:
2315 // [...] or if any template argument remains neither deduced nor
2316 // explicitly specified, template argument deduction fails.
2317 SmallVector<TemplateArgument, 4> Builder;
2318 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2319 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2320 NamedDecl *Param = PartialParams->getParam(I);
2321 if (Deduced[I].isNull()) {
2322 Info.Param = makeTemplateParameter(Param);
2323 return Sema::TDK_Incomplete;
2324 }
2325
2326 // We have deduced this argument, so it still needs to be
2327 // checked and converted.
Richard Smith37acb792016-02-03 20:15:01 +00002328 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial,
2329 Info, false, Builder)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002330 Info.Param = makeTemplateParameter(Param);
2331 // FIXME: These template arguments are temporary. Free them!
2332 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2333 Builder.size()));
2334 return Sema::TDK_SubstitutionFailure;
2335 }
2336 }
2337
2338 // Form the template argument list from the deduced template arguments.
2339 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2340 S.Context, Builder.data(), Builder.size());
2341
2342 Info.reset(DeducedArgumentList);
2343
2344 // Substitute the deduced template arguments into the template
2345 // arguments of the class template partial specialization, and
2346 // verify that the instantiated template arguments are both valid
2347 // and are equivalent to the template arguments originally provided
2348 // to the class template.
2349 LocalInstantiationScope InstScope(S);
2350 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002351 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2352 = Partial->getTemplateArgsAsWritten();
2353 const TemplateArgumentLoc *PartialTemplateArgs
2354 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002355
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002356 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2357 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002358
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002359 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002360 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2361 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2362 if (ParamIdx >= Partial->getTemplateParameters()->size())
2363 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2364
2365 Decl *Param = const_cast<NamedDecl *>(
2366 Partial->getTemplateParameters()->getParam(ParamIdx));
2367 Info.Param = makeTemplateParameter(Param);
2368 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2369 return Sema::TDK_SubstitutionFailure;
2370 }
2371 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2372 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2373 false, ConvertedInstArgs))
2374 return Sema::TDK_SubstitutionFailure;
2375
2376 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2377 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2378 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2379 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2380 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2381 Info.FirstArg = TemplateArgs[I];
2382 Info.SecondArg = InstArg;
2383 return Sema::TDK_NonDeducedMismatch;
2384 }
2385 }
2386
2387 if (Trap.hasErrorOccurred())
2388 return Sema::TDK_SubstitutionFailure;
2389
2390 return Sema::TDK_Success;
2391}
2392
2393/// \brief Perform template argument deduction to determine whether
2394/// the given template arguments match the given variable template
2395/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002396/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2397/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2398/// VarTemplate(Partial)SpecializationDecl with a new data
2399/// structure Template(Partial)SpecializationDecl, and
2400/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002401Sema::TemplateDeductionResult
2402Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2403 const TemplateArgumentList &TemplateArgs,
2404 TemplateDeductionInfo &Info) {
2405 if (Partial->isInvalidDecl())
2406 return TDK_Invalid;
2407
2408 // C++ [temp.class.spec.match]p2:
2409 // A partial specialization matches a given actual template
2410 // argument list if the template arguments of the partial
2411 // specialization can be deduced from the actual template argument
2412 // list (14.8.2).
2413
2414 // Unevaluated SFINAE context.
2415 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2416 SFINAETrap Trap(*this);
2417
2418 SmallVector<DeducedTemplateArgument, 4> Deduced;
2419 Deduced.resize(Partial->getTemplateParameters()->size());
2420 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2421 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2422 TemplateArgs, Info, Deduced))
2423 return Result;
2424
2425 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002426 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2427 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002428 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002429 return TDK_InstantiationDepth;
2430
2431 if (Trap.hasErrorOccurred())
2432 return Sema::TDK_SubstitutionFailure;
2433
2434 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2435 Deduced, Info);
2436}
2437
Douglas Gregorfc516c92009-06-26 23:27:24 +00002438/// \brief Determine whether the given type T is a simple-template-id type.
2439static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002440 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002441 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002442 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002443
Douglas Gregorfc516c92009-06-26 23:27:24 +00002444 return false;
2445}
Douglas Gregor9b146582009-07-08 20:55:45 +00002446
2447/// \brief Substitute the explicitly-provided template arguments into the
2448/// given function template according to C++ [temp.arg.explicit].
2449///
2450/// \param FunctionTemplate the function template into which the explicit
2451/// template arguments will be substituted.
2452///
James Dennett634962f2012-06-14 21:40:34 +00002453/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002454/// arguments.
2455///
Mike Stump11289f42009-09-09 15:08:12 +00002456/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002457/// with the converted and checked explicit template arguments.
2458///
Mike Stump11289f42009-09-09 15:08:12 +00002459/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002460/// parameters.
2461///
2462/// \param FunctionType if non-NULL, the result type of the function template
2463/// will also be instantiated and the pointed-to value will be updated with
2464/// the instantiated function type.
2465///
2466/// \param Info if substitution fails for any reason, this object will be
2467/// populated with more information about the failure.
2468///
2469/// \returns TDK_Success if substitution was successful, or some failure
2470/// condition.
2471Sema::TemplateDeductionResult
2472Sema::SubstituteExplicitTemplateArguments(
2473 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002474 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002475 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2476 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002477 QualType *FunctionType,
2478 TemplateDeductionInfo &Info) {
2479 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2480 TemplateParameterList *TemplateParams
2481 = FunctionTemplate->getTemplateParameters();
2482
John McCall6b51f282009-11-23 01:53:49 +00002483 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002484 // No arguments to substitute; just copy over the parameter types and
2485 // fill in the function type.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002486 for (auto P : Function->params())
2487 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregor9b146582009-07-08 20:55:45 +00002489 if (FunctionType)
2490 *FunctionType = Function->getType();
2491 return TDK_Success;
2492 }
Mike Stump11289f42009-09-09 15:08:12 +00002493
Eli Friedman77dcc722012-02-08 03:07:05 +00002494 // Unevaluated SFINAE context.
2495 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002496 SFINAETrap Trap(*this);
2497
Douglas Gregor9b146582009-07-08 20:55:45 +00002498 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002499 // Template arguments that are present shall be specified in the
2500 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002501 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002502 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002503 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002504
2505 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002506 // explicitly-specified template arguments against this function template,
2507 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002508 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002509 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2510 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002511 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2512 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002513 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002514 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002515
Douglas Gregor9b146582009-07-08 20:55:45 +00002516 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002517 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002518 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002519 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002520 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002521 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002522 if (Index >= TemplateParams->size())
2523 Index = TemplateParams->size() - 1;
2524 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002525 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002526 }
Mike Stump11289f42009-09-09 15:08:12 +00002527
Douglas Gregor9b146582009-07-08 20:55:45 +00002528 // Form the template argument list from the explicitly-specified
2529 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002530 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002531 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002532 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533
John McCall036855a2010-10-12 19:40:14 +00002534 // Template argument deduction and the final substitution should be
2535 // done in the context of the templated declaration. Explicit
2536 // argument substitution, on the other hand, needs to happen in the
2537 // calling context.
2538 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2539
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002540 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002541 // note that the template argument pack is partially substituted and record
2542 // the explicit template arguments. They'll be used as part of deduction
2543 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002544 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2545 const TemplateArgument &Arg = Builder[I];
2546 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002547 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002548 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002549 Arg.pack_begin(),
2550 Arg.pack_size());
2551 break;
2552 }
2553 }
2554
Richard Smith5e580292012-02-10 09:58:53 +00002555 const FunctionProtoType *Proto
2556 = Function->getType()->getAs<FunctionProtoType>();
2557 assert(Proto && "Function template does not have a prototype?");
2558
Richard Smith70b13042015-01-09 01:19:56 +00002559 // Isolate our substituted parameters from our caller.
2560 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2561
John McCallc8e321d2016-03-01 02:09:25 +00002562 ExtParameterInfoBuilder ExtParamInfos;
2563
Douglas Gregor9b146582009-07-08 20:55:45 +00002564 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002565 // explicitly-specified template arguments. If the function has a trailing
2566 // return type, substitute it after the arguments to ensure we substitute
2567 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002568 if (Proto->hasTrailingReturn()) {
2569 if (SubstParmTypes(Function->getLocation(),
2570 Function->param_begin(), Function->getNumParams(),
John McCallc8e321d2016-03-01 02:09:25 +00002571 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002572 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002573 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002574 return TDK_SubstitutionFailure;
2575 }
2576
Richard Smith5e580292012-02-10 09:58:53 +00002577 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002578 QualType ResultType;
2579 {
2580 // C++11 [expr.prim.general]p3:
2581 // If a declaration declares a member function or member function
2582 // template of a class X, the expression this is a prvalue of type
2583 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2584 // and the end of the function-definition, member-declarator, or
2585 // declarator.
2586 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002587 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002588 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2589 ThisContext = Method->getParent();
2590 ThisTypeQuals = Method->getTypeQualifiers();
2591 }
2592
2593 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002594 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002595
2596 ResultType =
2597 SubstType(Proto->getReturnType(),
2598 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2599 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002600 if (ResultType.isNull() || Trap.hasErrorOccurred())
2601 return TDK_SubstitutionFailure;
2602 }
John McCallc8e321d2016-03-01 02:09:25 +00002603
Richard Smith5e580292012-02-10 09:58:53 +00002604 // Instantiate the types of each of the function parameters given the
2605 // explicitly-specified template arguments if we didn't do so earlier.
2606 if (!Proto->hasTrailingReturn() &&
2607 SubstParmTypes(Function->getLocation(),
2608 Function->param_begin(), Function->getNumParams(),
John McCallc8e321d2016-03-01 02:09:25 +00002609 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002610 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002611 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002612 return TDK_SubstitutionFailure;
2613
Douglas Gregor9b146582009-07-08 20:55:45 +00002614 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002615 auto EPI = Proto->getExtProtoInfo();
2616 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002617 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002618 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002619 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002620 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002621 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2622 return TDK_SubstitutionFailure;
2623 }
Mike Stump11289f42009-09-09 15:08:12 +00002624
Douglas Gregor9b146582009-07-08 20:55:45 +00002625 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002626 // Trailing template arguments that can be deduced (14.8.2) may be
2627 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002628 // template arguments can be deduced, they may all be omitted; in this
2629 // case, the empty template argument list <> itself may also be omitted.
2630 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002631 // Take all of the explicitly-specified arguments and put them into
2632 // the set of deduced template arguments. Explicitly-specified
2633 // parameter packs, however, will be set to NULL since the deduction
2634 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002635 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002636 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2637 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2638 if (Arg.getKind() == TemplateArgument::Pack)
2639 Deduced.push_back(DeducedTemplateArgument());
2640 else
2641 Deduced.push_back(Arg);
2642 }
Mike Stump11289f42009-09-09 15:08:12 +00002643
Douglas Gregor9b146582009-07-08 20:55:45 +00002644 return TDK_Success;
2645}
2646
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002647/// \brief Check whether the deduced argument type for a call to a function
2648/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2649static bool
2650CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2651 QualType DeducedA) {
2652 ASTContext &Context = S.Context;
2653
2654 QualType A = OriginalArg.OriginalArgType;
2655 QualType OriginalParamType = OriginalArg.OriginalParamType;
2656
2657 // Check for type equality (top-level cv-qualifiers are ignored).
2658 if (Context.hasSameUnqualifiedType(A, DeducedA))
2659 return false;
2660
2661 // Strip off references on the argument types; they aren't needed for
2662 // the following checks.
2663 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2664 DeducedA = DeducedARef->getPointeeType();
2665 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2666 A = ARef->getPointeeType();
2667
2668 // C++ [temp.deduct.call]p4:
2669 // [...] However, there are three cases that allow a difference:
2670 // - If the original P is a reference type, the deduced A (i.e., the
2671 // type referred to by the reference) can be more cv-qualified than
2672 // the transformed A.
2673 if (const ReferenceType *OriginalParamRef
2674 = OriginalParamType->getAs<ReferenceType>()) {
2675 // We don't want to keep the reference around any more.
2676 OriginalParamType = OriginalParamRef->getPointeeType();
2677
2678 Qualifiers AQuals = A.getQualifiers();
2679 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002680
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002681 // Under Objective-C++ ARC, the deduced type may have implicitly
2682 // been given strong or (when dealing with a const reference)
2683 // unsafe_unretained lifetime. If so, update the original
2684 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002685 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002686 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2687 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2688 (DeducedAQuals.hasConst() &&
2689 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2690 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002691 }
2692
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002693 if (AQuals == DeducedAQuals) {
2694 // Qualifiers match; there's nothing to do.
2695 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002696 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002697 } else {
2698 // Qualifiers are compatible, so have the argument type adopt the
2699 // deduced argument type's qualifiers as if we had performed the
2700 // qualification conversion.
2701 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2702 }
2703 }
2704
2705 // - The transformed A can be another pointer or pointer to member
2706 // type that can be converted to the deduced A via a qualification
2707 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002708 //
2709 // Also allow conversions which merely strip [[noreturn]] from function types
2710 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002711 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002712 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002713 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002714 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002715 (S.IsQualificationConversion(A, DeducedA, false,
2716 ObjCLifetimeConversion) ||
2717 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002718 return false;
2719
2720
2721 // - If P is a class and P has the form simple-template-id, then the
2722 // transformed A can be a derived class of the deduced A. [...]
2723 // [...] Likewise, if P is a pointer to a class of the form
2724 // simple-template-id, the transformed A can be a pointer to a
2725 // derived class pointed to by the deduced A.
2726 if (const PointerType *OriginalParamPtr
2727 = OriginalParamType->getAs<PointerType>()) {
2728 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2729 if (const PointerType *APtr = A->getAs<PointerType>()) {
2730 if (A->getPointeeType()->isRecordType()) {
2731 OriginalParamType = OriginalParamPtr->getPointeeType();
2732 DeducedA = DeducedAPtr->getPointeeType();
2733 A = APtr->getPointeeType();
2734 }
2735 }
2736 }
2737 }
2738
2739 if (Context.hasSameUnqualifiedType(A, DeducedA))
2740 return false;
2741
2742 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002743 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002744 return false;
2745
2746 return true;
2747}
2748
Mike Stump11289f42009-09-09 15:08:12 +00002749/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002750/// checking the deduced template arguments for completeness and forming
2751/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002752///
2753/// \param OriginalCallArgs If non-NULL, the original call arguments against
2754/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002755Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002756Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002757 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002758 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002759 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002760 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002761 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2762 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002763 TemplateParameterList *TemplateParams
2764 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002765
Eli Friedman77dcc722012-02-08 03:07:05 +00002766 // Unevaluated SFINAE context.
2767 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002768 SFINAETrap Trap(*this);
2769
Douglas Gregor9b146582009-07-08 20:55:45 +00002770 // Enter a new template instantiation context while we instantiate the
2771 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002772 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002773 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2774 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002775 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2776 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002777 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002778 return TDK_InstantiationDepth;
2779
John McCalle23b8712010-04-29 01:18:58 +00002780 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002781
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002782 // C++ [temp.deduct.type]p2:
2783 // [...] or if any template argument remains neither deduced nor
2784 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002785 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002786 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2787 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002788
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002789 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002790 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002791 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002792 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002793 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002794 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002795 // We may have had explicitly-specified template arguments for a
2796 // template parameter pack (that may or may not have been extended
2797 // via additional deduced arguments).
2798 if (Param->isParameterPack() && CurrentInstantiationScope) {
2799 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2800 Param) {
2801 // Forget the partially-substituted pack; its substitution is now
2802 // complete.
2803 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2804 }
2805 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002806 continue;
2807 }
Richard Smith37acb792016-02-03 20:15:01 +00002808
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002809 // We have deduced this argument, so it still needs to be
2810 // checked and converted.
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002811 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002812 FunctionTemplate, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002813 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002814 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002815 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2817 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002818 return TDK_SubstitutionFailure;
2819 }
2820
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002821 continue;
2822 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002823
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002824 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002825 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002826 // be deduced to an empty sequence of template arguments.
2827 // FIXME: Where did the word "trailing" come from?
2828 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002829 // We may have had explicitly-specified template arguments for this
2830 // template parameter pack. If so, our empty deduction extends the
2831 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2832 const TemplateArgument *ExplicitArgs;
2833 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002834 if (CurrentInstantiationScope &&
2835 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002836 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002837 == Param) {
Benjamin Kramercce63472015-08-05 09:40:22 +00002838 Builder.push_back(TemplateArgument(
2839 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002840
Richard Smithdf18ee92016-02-03 20:40:30 +00002841 // Forget the partially-substituted pack; its substitution is now
Douglas Gregorcaddba92013-01-18 22:27:09 +00002842 // complete.
2843 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2844 } else {
Richard Smithdf18ee92016-02-03 20:40:30 +00002845 // Go through the motions of checking the empty argument pack against
2846 // the parameter pack.
2847 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2848 if (ConvertDeducedTemplateArgument(*this, Param, DeducedPack,
2849 FunctionTemplate, Info, true,
2850 Builder)) {
2851 Info.Param = makeTemplateParameter(Param);
2852 // FIXME: These template arguments are temporary. Free them!
2853 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2854 Builder.size()));
2855 return TDK_SubstitutionFailure;
2856 }
Douglas Gregorcaddba92013-01-18 22:27:09 +00002857 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002858 continue;
2859 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002860
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002861 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002862 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002863 TemplateArgumentLoc DefArg
2864 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2865 FunctionTemplate->getLocation(),
2866 FunctionTemplate->getSourceRange().getEnd(),
2867 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002868 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002869
2870 // If there was no default argument, deduction is incomplete.
2871 if (DefArg.getArgument().isNull()) {
2872 Info.Param = makeTemplateParameter(
2873 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002874 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2875 Builder.size()));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002876 if (PartialOverloading) break;
2877
Richard Smithc87b9382013-07-04 01:01:24 +00002878 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002880
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002881 // Check whether we can actually use the default argument.
2882 if (CheckTemplateArgument(Param, DefArg,
2883 FunctionTemplate,
2884 FunctionTemplate->getLocation(),
2885 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002886 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002887 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002888 Info.Param = makeTemplateParameter(
2889 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002890 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002891 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002892 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002893 return TDK_SubstitutionFailure;
2894 }
2895
2896 // If we get here, we successfully used the default template argument.
2897 }
2898
2899 // Form the template argument list from the deduced template arguments.
2900 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002901 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002902 Info.reset(DeducedArgumentList);
2903
Mike Stump11289f42009-09-09 15:08:12 +00002904 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002905 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002906 DeclContext *Owner = FunctionTemplate->getDeclContext();
2907 if (FunctionTemplate->getFriendObjectKind())
2908 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002909 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002910 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002911 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002912 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002913 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002914
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002916 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002917
Mike Stump11289f42009-09-09 15:08:12 +00002918 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002919 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002920 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2921 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002922 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002923
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002924 // There may have been an error that did not prevent us from constructing a
2925 // declaration. Mark the declaration invalid and return with a substitution
2926 // failure.
2927 if (Trap.hasErrorOccurred()) {
2928 Specialization->setInvalidDecl(true);
2929 return TDK_SubstitutionFailure;
2930 }
2931
Douglas Gregore65aacb2011-06-16 16:50:48 +00002932 if (OriginalCallArgs) {
2933 // C++ [temp.deduct.call]p4:
2934 // In general, the deduction process attempts to find template argument
2935 // values that will make the deduced A identical to A (after the type A
2936 // is transformed as described above). [...]
2937 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2938 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002939 unsigned ParamIdx = OriginalArg.ArgIdx;
2940
2941 if (ParamIdx >= Specialization->getNumParams())
2942 continue;
2943
2944 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002945 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2946 Info.FirstArg = TemplateArgument(DeducedA);
2947 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2948 Info.CallArgIndex = OriginalArg.ArgIdx;
2949 return TDK_DeducedMismatch;
2950 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002951 }
2952 }
2953
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002954 // If we suppressed any diagnostics while performing template argument
2955 // deduction, and if we haven't already instantiated this declaration,
2956 // keep track of these diagnostics. They'll be emitted if this specialization
2957 // is actually used.
2958 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002959 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002960 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2961 if (Pos == SuppressedDiagnostics.end())
2962 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2963 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002964 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002965
Mike Stump11289f42009-09-09 15:08:12 +00002966 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002967}
2968
John McCall8d08b9b2010-08-27 09:08:28 +00002969/// Gets the type of a function for template-argument-deducton
2970/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002971static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002972 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002973 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002974 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002975 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002976 return QualType();
2977
John McCallc1f69982010-02-02 02:21:27 +00002978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002979 if (Method->isInstance()) {
2980 // An instance method that's referenced in a form that doesn't
2981 // look like a member pointer is just invalid.
2982 if (!R.HasFormOfMemberPointer) return QualType();
2983
Richard Smith2a7d4812013-05-04 07:00:32 +00002984 return S.Context.getMemberPointerType(Fn->getType(),
2985 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002986 }
2987
2988 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002989 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002990}
2991
2992/// Apply the deduction rules for overload sets.
2993///
2994/// \return the null type if this argument should be treated as an
2995/// undeduced context
2996static QualType
2997ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002998 Expr *Arg, QualType ParamType,
2999 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000
John McCall8d08b9b2010-08-27 09:08:28 +00003001 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003002
John McCall8d08b9b2010-08-27 09:08:28 +00003003 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003004
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003005 // C++0x [temp.deduct.call]p4
3006 unsigned TDF = 0;
3007 if (ParamWasReference)
3008 TDF |= TDF_ParamWithReferenceType;
3009 if (R.IsAddressOfOperand)
3010 TDF |= TDF_IgnoreQualifiers;
3011
John McCallc1f69982010-02-02 02:21:27 +00003012 // C++0x [temp.deduct.call]p6:
3013 // When P is a function type, pointer to function type, or pointer
3014 // to member function type:
3015
3016 if (!ParamType->isFunctionType() &&
3017 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003018 !ParamType->isMemberFunctionPointerType()) {
3019 if (Ovl->hasExplicitTemplateArgs()) {
3020 // But we can still look for an explicit specialization.
3021 if (FunctionDecl *ExplicitSpec
3022 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003023 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003024 }
John McCallc1f69982010-02-02 02:21:27 +00003025
George Burgess IVcc2f3552016-03-19 21:51:45 +00003026 DeclAccessPair DAP;
3027 if (FunctionDecl *Viable =
3028 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3029 return GetTypeOfFunction(S, R, Viable);
3030
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003031 return QualType();
3032 }
3033
3034 // Gather the explicit template arguments, if any.
3035 TemplateArgumentListInfo ExplicitTemplateArgs;
3036 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003037 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003038 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003039 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3040 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003041 NamedDecl *D = (*I)->getUnderlyingDecl();
3042
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003043 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3044 // - If the argument is an overload set containing one or more
3045 // function templates, the parameter is treated as a
3046 // non-deduced context.
3047 if (!Ovl->hasExplicitTemplateArgs())
3048 return QualType();
3049
3050 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003051 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003052 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003053 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3054 Specialization, Info))
3055 continue;
3056
3057 D = Specialization;
3058 }
John McCallc1f69982010-02-02 02:21:27 +00003059
3060 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003061 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003062 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003063
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003064 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003065 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003066 ArgType->isFunctionType())
3067 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003068
John McCallc1f69982010-02-02 02:21:27 +00003069 // - If the argument is an overload set (not containing function
3070 // templates), trial argument deduction is attempted using each
3071 // of the members of the set. If deduction succeeds for only one
3072 // of the overload set members, that member is used as the
3073 // argument value for the deduction. If deduction succeeds for
3074 // more than one member of the overload set the parameter is
3075 // treated as a non-deduced context.
3076
3077 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3078 // Type deduction is done independently for each P/A pair, and
3079 // the deduced template argument values are then combined.
3080 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003081 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003082 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003083 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003084 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003085 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3086 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003087 if (Result) continue;
3088 if (!Match.isNull()) return QualType();
3089 Match = ArgType;
3090 }
3091
3092 return Match;
3093}
3094
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003096/// described in C++ [temp.deduct.call].
3097///
3098/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003099/// argument deduction based on this P/A pair because the argument is an
3100/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003101static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3102 TemplateParameterList *TemplateParams,
3103 QualType &ParamType,
3104 QualType &ArgType,
3105 Expr *Arg,
3106 unsigned &TDF) {
3107 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003108 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003109 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003110 if (ParamType.hasQualifiers())
3111 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003112
3113 // [...] If P is a reference type, the type referred to by P is
3114 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003115 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003116 if (ParamRefType)
3117 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003118
Nathan Sidwell96090022015-01-16 15:20:14 +00003119 // Overload sets usually make this parameter an undeduced context,
3120 // but there are sometimes special circumstances. Typically
3121 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003122 if (ArgType == S.Context.OverloadTy) {
3123 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3124 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003125 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003126 if (ArgType.isNull())
3127 return true;
3128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003129
Douglas Gregor7825bf32011-01-06 22:09:01 +00003130 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003131 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003132 if (ArgType->isIncompleteArrayType()) {
3133 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003134 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003135 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003136
Douglas Gregor7825bf32011-01-06 22:09:01 +00003137 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003138 // If P is an rvalue reference to a cv-unqualified template
3139 // parameter and the argument is an lvalue, the type "lvalue
3140 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003141 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003142 !ParamType.getQualifiers() &&
3143 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003144 Arg->isLValue())
3145 ArgType = S.Context.getLValueReferenceType(ArgType);
3146 } else {
3147 // C++ [temp.deduct.call]p2:
3148 // If P is not a reference type:
3149 // - If A is an array type, the pointer type produced by the
3150 // array-to-pointer standard conversion (4.2) is used in place of
3151 // A for type deduction; otherwise,
3152 if (ArgType->isArrayType())
3153 ArgType = S.Context.getArrayDecayedType(ArgType);
3154 // - If A is a function type, the pointer type produced by the
3155 // function-to-pointer standard conversion (4.3) is used in place
3156 // of A for type deduction; otherwise,
3157 else if (ArgType->isFunctionType())
3158 ArgType = S.Context.getPointerType(ArgType);
3159 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003160 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003161 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003162 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003163 }
3164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165
Douglas Gregor7825bf32011-01-06 22:09:01 +00003166 // C++0x [temp.deduct.call]p4:
3167 // In general, the deduction process attempts to find template argument
3168 // values that will make the deduced A identical to A (after the type A
3169 // is transformed as described above). [...]
3170 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor7825bf32011-01-06 22:09:01 +00003172 // - If the original P is a reference type, the deduced A (i.e., the
3173 // type referred to by the reference) can be more cv-qualified than
3174 // the transformed A.
3175 if (ParamRefType)
3176 TDF |= TDF_ParamWithReferenceType;
3177 // - The transformed A can be another pointer or pointer to member
3178 // type that can be converted to the deduced A via a qualification
3179 // conversion (4.4).
3180 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3181 ArgType->isObjCObjectPointerType())
3182 TDF |= TDF_IgnoreQualifiers;
3183 // - If P is a class and P has the form simple-template-id, then the
3184 // transformed A can be a derived class of the deduced A. Likewise,
3185 // if P is a pointer to a class of the form simple-template-id, the
3186 // transformed A can be a pointer to a derived class pointed to by
3187 // the deduced A.
3188 if (isSimpleTemplateIdType(ParamType) ||
3189 (isa<PointerType>(ParamType) &&
3190 isSimpleTemplateIdType(
3191 ParamType->getAs<PointerType>()->getPointeeType())))
3192 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003193
Douglas Gregor7825bf32011-01-06 22:09:01 +00003194 return false;
3195}
3196
Nico Weberc153d242014-07-28 00:02:09 +00003197static bool
3198hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3199 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003200
Hubert Tong3280b332015-06-25 00:25:49 +00003201static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3202 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3203 Expr *Arg, TemplateDeductionInfo &Info,
3204 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3205
3206/// \brief Attempt template argument deduction from an initializer list
3207/// deemed to be an argument in a function call.
3208static bool
3209DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3210 QualType AdjustedParamType, InitListExpr *ILE,
3211 TemplateDeductionInfo &Info,
3212 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3213 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003214
3215 // [temp.deduct.call] p1 (post CWG-1591)
3216 // If removing references and cv-qualifiers from P gives
3217 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3218 // non-empty initializer list (8.5.4), then deduction is performed instead for
3219 // each element of the initializer list, taking P0 as a function template
3220 // parameter type and the initializer element as its argument, and in the
3221 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3222 // length of the initializer list. Otherwise, an initializer list argument
3223 // causes the parameter to be considered a non-deduced context
3224
3225 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3226
3227 const bool IsDependentSizedArray =
3228 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3229
Faisal Validd76cc12015-12-10 12:29:11 +00003230 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003231
3232 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3233 S.isStdInitializerList(AdjustedParamType, &ElTy);
3234
3235 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003236 return false;
3237
3238 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003239 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3240 // deduce against the 'T' in T[N].
3241 if (ElTy.isNull()) {
3242 assert(!IsSTDList);
3243 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003244 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003245 // Deduction only needs to be done for dependent types.
3246 if (ElTy->isDependentType()) {
3247 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003248 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3249 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003250 return true;
3251 }
3252 }
3253 if (IsDependentSizedArray) {
3254 const DependentSizedArrayType *ArrTy =
3255 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3256 // Determine the array bound is something we can deduce.
3257 if (NonTypeTemplateParmDecl *NTTP =
3258 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3259 // We can perform template argument deduction for the given non-type
3260 // template parameter.
3261 assert(NTTP->getDepth() == 0 &&
3262 "Cannot deduce non-type template argument at depth > 0");
3263 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3264 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003265
Faisal Valif6dfdb32015-12-10 05:36:39 +00003266 Result = DeduceNonTypeTemplateArgument(
3267 S, NTTP, llvm::APSInt(Size), NTTP->getType(),
3268 /*ArrayBound=*/true, Info, Deduced);
3269 }
3270 }
Hubert Tong3280b332015-06-25 00:25:49 +00003271 return true;
3272}
3273
Sebastian Redl19181662012-03-15 21:40:51 +00003274/// \brief Perform template argument deduction by matching a parameter type
3275/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003276/// an initializer list that was originally matched against a parameter
3277/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003278static Sema::TemplateDeductionResult
3279DeduceTemplateArgumentByListElement(Sema &S,
3280 TemplateParameterList *TemplateParams,
3281 QualType ParamType, Expr *Arg,
3282 TemplateDeductionInfo &Info,
3283 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3284 unsigned TDF) {
3285 // Handle the case where an init list contains another init list as the
3286 // element.
3287 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003288 Sema::TemplateDeductionResult Result;
3289 if (!DeduceFromInitializerList(S, TemplateParams,
3290 ParamType.getNonReferenceType(), ILE, Info,
3291 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003292 return Sema::TDK_Success; // Just ignore this expression.
3293
Hubert Tong3280b332015-06-25 00:25:49 +00003294 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003295 }
3296
3297 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003298 QualType ArgType = Arg->getType();
3299 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003300 ArgType, Arg, TDF)) {
3301 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003302 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003303 }
Sebastian Redl19181662012-03-15 21:40:51 +00003304 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003305 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003306}
3307
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003308/// \brief Perform template argument deduction from a function call
3309/// (C++ [temp.deduct.call]).
3310///
3311/// \param FunctionTemplate the function template for which we are performing
3312/// template argument deduction.
3313///
James Dennett18348b62012-06-22 08:52:37 +00003314/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003315/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003316///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003317/// \param Args the function call arguments
3318///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003319/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003320/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003321/// template argument deduction.
3322///
3323/// \param Info the argument will be updated to provide additional information
3324/// about template argument deduction.
3325///
3326/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003327Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3328 FunctionTemplateDecl *FunctionTemplate,
3329 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003330 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3331 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003332 if (FunctionTemplate->isInvalidDecl())
3333 return TDK_Invalid;
3334
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003335 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003336 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003337
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003338 // C++ [temp.deduct.call]p1:
3339 // Template argument deduction is done by comparing each function template
3340 // parameter type (call it P) with the type of the corresponding argument
3341 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003342 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003343 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003344 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003345 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003346 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003347 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003348 if (Proto->isTemplateVariadic())
3349 /* Do nothing */;
3350 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003351 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003353 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003354 }
Mike Stump11289f42009-09-09 15:08:12 +00003355
Douglas Gregor89026b52009-06-30 23:57:56 +00003356 // The types of the parameters from which we will perform template argument
3357 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003358 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003359 TemplateParameterList *TemplateParams
3360 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003361 SmallVector<DeducedTemplateArgument, 4> Deduced;
3362 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003363 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003364 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003365 TemplateDeductionResult Result =
3366 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003367 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003368 Deduced,
3369 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003370 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003371 Info);
3372 if (Result)
3373 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003374
3375 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003376 } else {
3377 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003378 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003379 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3380 }
Mike Stump11289f42009-09-09 15:08:12 +00003381
Douglas Gregor89026b52009-06-30 23:57:56 +00003382 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003383 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003384 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003385 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003386 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3387 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003388 QualType OrigParamType = ParamTypes[ParamIdx];
3389 QualType ParamType = OrigParamType;
3390
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003391 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003392 = dyn_cast<PackExpansionType>(ParamType);
3393 if (!ParamExpansion) {
3394 // Simple case: matching a function parameter to a function argument.
3395 if (ArgIdx >= CheckArgs)
3396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003397
Douglas Gregor7825bf32011-01-06 22:09:01 +00003398 Expr *Arg = Args[ArgIdx++];
3399 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003400
Douglas Gregor7825bf32011-01-06 22:09:01 +00003401 unsigned TDF = 0;
3402 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3403 ParamType, ArgType, Arg,
3404 TDF))
3405 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406
Douglas Gregor0c83c812011-10-09 22:06:46 +00003407 // If we have nothing to deduce, we're done.
3408 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3409 continue;
3410
Sebastian Redl43144e72012-01-17 22:49:58 +00003411 // If the argument is an initializer list ...
3412 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003413 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003414 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003415 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3416 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003417 continue;
3418
Hubert Tong3280b332015-06-25 00:25:49 +00003419 if (Result)
3420 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003421 // Don't track the argument type, since an initializer list has none.
3422 continue;
3423 }
3424
Douglas Gregore65aacb2011-06-16 16:50:48 +00003425 // Keep track of the argument type and corresponding parameter index,
3426 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003427 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3428 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003429
Douglas Gregor7825bf32011-01-06 22:09:01 +00003430 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003431 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3432 ParamType, ArgType,
3433 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003434 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003435
Douglas Gregor7825bf32011-01-06 22:09:01 +00003436 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
Douglas Gregor7825bf32011-01-06 22:09:01 +00003439 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440 // For a function parameter pack that occurs at the end of the
3441 // parameter-declaration-list, the type A of each remaining argument of
3442 // the call is compared with the type P of the declarator-id of the
3443 // function parameter pack. Each comparison deduces template arguments
3444 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003445 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003446 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003447 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003448 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003449 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450
Douglas Gregor7825bf32011-01-06 22:09:01 +00003451 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003452 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3453 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003454
Douglas Gregor7825bf32011-01-06 22:09:01 +00003455 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003456 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003457 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458
Douglas Gregore65aacb2011-06-16 16:50:48 +00003459 QualType OrigParamType = ParamPattern;
3460 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003461 Expr *Arg = Args[ArgIdx];
3462 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003463
Douglas Gregor7825bf32011-01-06 22:09:01 +00003464 unsigned TDF = 0;
3465 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3466 ParamType, ArgType, Arg,
3467 TDF)) {
3468 // We can't actually perform any deduction for this argument, so stop
3469 // deduction at this point.
3470 ++ArgIdx;
3471 break;
3472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473
Sebastian Redl43144e72012-01-17 22:49:58 +00003474 // As above, initializer lists need special handling.
3475 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003476 TemplateDeductionResult Result;
3477 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3478 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003479 ++ArgIdx;
3480 break;
3481 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003482
Hubert Tong3280b332015-06-25 00:25:49 +00003483 if (Result)
3484 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003485 } else {
3486
3487 // Keep track of the argument type and corresponding argument index,
3488 // so we can check for compatibility between the deduced A and A.
3489 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3490 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3491 ArgType));
3492
3493 if (TemplateDeductionResult Result
3494 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3495 ParamType, ArgType, Info,
3496 Deduced, TDF))
3497 return Result;
3498 }
Mike Stump11289f42009-09-09 15:08:12 +00003499
Richard Smith0a80d572014-05-29 01:12:14 +00003500 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Douglas Gregor7825bf32011-01-06 22:09:01 +00003503 // Build argument packs for each of the parameter packs expanded by this
3504 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003505 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003507
Douglas Gregor7825bf32011-01-06 22:09:01 +00003508 // After we've matching against a parameter pack, we're done.
3509 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003510 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003511
Mike Stump11289f42009-09-09 15:08:12 +00003512 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003513 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003514 Info, &OriginalCallArgs,
3515 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003516}
3517
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003518QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3519 QualType FunctionType) {
3520 if (ArgFunctionType.isNull())
3521 return ArgFunctionType;
3522
3523 const FunctionProtoType *FunctionTypeP =
3524 FunctionType->castAs<FunctionProtoType>();
3525 CallingConv CC = FunctionTypeP->getCallConv();
3526 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3527 const FunctionProtoType *ArgFunctionTypeP =
3528 ArgFunctionType->getAs<FunctionProtoType>();
3529 if (ArgFunctionTypeP->getCallConv() == CC &&
3530 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3531 return ArgFunctionType;
3532
3533 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3534 EI = EI.withNoReturn(NoReturn);
3535 ArgFunctionTypeP =
3536 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3537 return QualType(ArgFunctionTypeP, 0);
3538}
3539
Douglas Gregor9b146582009-07-08 20:55:45 +00003540/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003541/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3542/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003543///
3544/// \param FunctionTemplate the function template for which we are performing
3545/// template argument deduction.
3546///
James Dennett18348b62012-06-22 08:52:37 +00003547/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003548/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003549///
3550/// \param ArgFunctionType the function type that will be used as the
3551/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003552/// function template's function type. This type may be NULL, if there is no
3553/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003554///
3555/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003556/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003557/// template argument deduction.
3558///
3559/// \param Info the argument will be updated to provide additional information
3560/// about template argument deduction.
3561///
3562/// \returns the result of template argument deduction.
3563Sema::TemplateDeductionResult
3564Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003565 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003566 QualType ArgFunctionType,
3567 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003568 TemplateDeductionInfo &Info,
3569 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003570 if (FunctionTemplate->isInvalidDecl())
3571 return TDK_Invalid;
3572
Douglas Gregor9b146582009-07-08 20:55:45 +00003573 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3574 TemplateParameterList *TemplateParams
3575 = FunctionTemplate->getTemplateParameters();
3576 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003577 if (!InOverloadResolution)
3578 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003579
Douglas Gregor9b146582009-07-08 20:55:45 +00003580 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003581 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003582 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003583 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003584 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003585 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003586 if (TemplateDeductionResult Result
3587 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003588 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003589 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003590 &FunctionType, Info))
3591 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003592
3593 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003594 }
3595
Eli Friedman77dcc722012-02-08 03:07:05 +00003596 // Unevaluated SFINAE context.
3597 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003598 SFINAETrap Trap(*this);
3599
John McCallc1f69982010-02-02 02:21:27 +00003600 Deduced.resize(TemplateParams->size());
3601
Richard Smith2a7d4812013-05-04 07:00:32 +00003602 // If the function has a deduced return type, substitute it for a dependent
3603 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003604 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003605 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003606 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003607 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003608 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003609 }
3610
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003611 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003612 unsigned TDF = TDF_TopLevelParameterTypeList;
3613 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003614 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003615 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003616 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003617 FunctionType, ArgFunctionType,
3618 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003619 return Result;
3620 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003621
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003623 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3624 NumExplicitlySpecified,
3625 Specialization, Info))
3626 return Result;
3627
Richard Smith2a7d4812013-05-04 07:00:32 +00003628 // If the function has a deduced return type, deduce it now, so we can check
3629 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003630 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003631 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003632 DeduceReturnType(Specialization, Info.getLocation(), false))
3633 return TDK_MiscellaneousDeductionFailure;
3634
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003635 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003636 // specialization with respect to arguments of compatible pointer to function
3637 // types, template argument deduction fails.
3638 if (!ArgFunctionType.isNull()) {
3639 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3640 Context.getCanonicalType(Specialization->getType()),
3641 Context.getCanonicalType(ArgFunctionType)))
3642 return TDK_MiscellaneousDeductionFailure;
3643 else if(!InOverloadResolution &&
3644 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3645 return TDK_MiscellaneousDeductionFailure;
3646 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003647
3648 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003649}
3650
Faisal Vali850da1a2013-09-29 17:08:32 +00003651/// \brief Given a function declaration (e.g. a generic lambda conversion
3652/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003653/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3654/// to replace 'auto' with and not the actual result type you want
3655/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003656static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003657SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003658 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003659 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003660 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003661 assert(AutoResultType->getContainedAutoType());
3662 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003663 TypeToReplaceAutoWith);
3664 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3665}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003666
3667/// \brief Given a specialized conversion operator of a generic lambda
3668/// create the corresponding specializations of the call operator and
3669/// the static-invoker. If the return type of the call operator is auto,
3670/// deduce its return type and check if that matches the
3671/// return type of the destination function ptr.
3672
3673static inline Sema::TemplateDeductionResult
3674SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3675 CXXConversionDecl *ConversionSpecialized,
3676 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3677 QualType ReturnTypeOfDestFunctionPtr,
3678 TemplateDeductionInfo &TDInfo,
3679 Sema &S) {
3680
3681 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3682 assert(LambdaClass && LambdaClass->isGenericLambda());
3683
3684 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003685 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003686 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3687 CallOpResultType->getContainedAutoType();
3688
3689 FunctionTemplateDecl *CallOpTemplate =
3690 CallOpGeneric->getDescribedFunctionTemplate();
3691
Craig Topperc3ec1492014-05-26 06:22:03 +00003692 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003693 // Use the deduced arguments of the conversion function, to specialize our
3694 // generic lambda's call operator.
3695 if (Sema::TemplateDeductionResult Result
3696 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3697 DeducedArguments,
3698 0, CallOpSpecialized, TDInfo))
3699 return Result;
3700
3701 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003702 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3703 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003704 S.DeduceReturnType(CallOpSpecialized,
3705 CallOpSpecialized->getPointOfInstantiation(),
3706 /*Diagnose*/ true);
3707
3708 // Check to see if the return type of the destination ptr-to-function
3709 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003710 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003711 ReturnTypeOfDestFunctionPtr))
3712 return Sema::TDK_NonDeducedMismatch;
3713 // Since we have succeeded in matching the source and destination
3714 // ptr-to-functions (now including return type), and have successfully
3715 // specialized our corresponding call operator, we are ready to
3716 // specialize the static invoker with the deduced arguments of our
3717 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003718 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003719 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3720 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3721
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003722#ifndef NDEBUG
3723 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3724#endif
3725 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003726 InvokerSpecialized, TDInfo);
3727 assert(Result == Sema::TDK_Success &&
3728 "If the call operator succeeded so should the invoker!");
3729 // Set the result type to match the corresponding call operator
3730 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003731 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3732 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003733 // Be sure to get the type to replace 'auto' with and not
3734 // the full result type of the call op specialization
3735 // to substitute into the 'auto' of the invoker and conversion
3736 // function.
3737 // For e.g.
3738 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3739 // We don't want to subst 'int*' into 'auto' to get int**.
3740
Alp Toker314cc812014-01-25 16:55:45 +00003741 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3742 ->getContainedAutoType()
3743 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003744 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3745 TypeToReplaceAutoWith, S);
3746 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3747 TypeToReplaceAutoWith, S);
3748 }
3749
3750 // Ensure that static invoker doesn't have a const qualifier.
3751 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3752 // do not use the CallOperator's TypeSourceInfo which allows
3753 // the const qualifier to leak through.
3754 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3755 getType().getTypePtr()->castAs<FunctionProtoType>();
3756 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3757 EPI.TypeQuals = 0;
3758 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003759 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003760 return Sema::TDK_Success;
3761}
Douglas Gregor05155d82009-08-21 23:19:43 +00003762/// \brief Deduce template arguments for a templated conversion
3763/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3764/// conversion function template specialization.
3765Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003766Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003767 QualType ToType,
3768 CXXConversionDecl *&Specialization,
3769 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003770 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003771 return TDK_Invalid;
3772
Faisal Vali2b3a3012013-10-24 23:40:02 +00003773 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003774 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3775
Faisal Vali2b3a3012013-10-24 23:40:02 +00003776 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003777
3778 // Canonicalize the types for deduction.
3779 QualType P = Context.getCanonicalType(FromType);
3780 QualType A = Context.getCanonicalType(ToType);
3781
Douglas Gregord99609a2011-03-06 09:03:20 +00003782 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003783 // If P is a reference type, the type referred to by P is used for
3784 // type deduction.
3785 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3786 P = PRef->getPointeeType();
3787
Douglas Gregord99609a2011-03-06 09:03:20 +00003788 // C++0x [temp.deduct.conv]p4:
3789 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003790 // for type deduction.
3791 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003792 A = ARef->getPointeeType().getUnqualifiedType();
3793 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003794 //
Mike Stump11289f42009-09-09 15:08:12 +00003795 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003796 else {
3797 assert(!A->isReferenceType() && "Reference types were handled above");
3798
3799 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003800 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003801 // of P for type deduction; otherwise,
3802 if (P->isArrayType())
3803 P = Context.getArrayDecayedType(P);
3804 // - If P is a function type, the pointer type produced by the
3805 // function-to-pointer standard conversion (4.3) is used in
3806 // place of P for type deduction; otherwise,
3807 else if (P->isFunctionType())
3808 P = Context.getPointerType(P);
3809 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003810 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003811 else
3812 P = P.getUnqualifiedType();
3813
Douglas Gregord99609a2011-03-06 09:03:20 +00003814 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003815 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003816 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003817 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003818 A = A.getUnqualifiedType();
3819 }
3820
Eli Friedman77dcc722012-02-08 03:07:05 +00003821 // Unevaluated SFINAE context.
3822 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003823 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003824
3825 // C++ [temp.deduct.conv]p1:
3826 // Template argument deduction is done by comparing the return
3827 // type of the template conversion function (call it P) with the
3828 // type that is required as the result of the conversion (call it
3829 // A) as described in 14.8.2.4.
3830 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003831 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003832 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003833 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003834
3835 // C++0x [temp.deduct.conv]p4:
3836 // In general, the deduction process attempts to find template
3837 // argument values that will make the deduced A identical to
3838 // A. However, there are two cases that allow a difference:
3839 unsigned TDF = 0;
3840 // - If the original A is a reference type, A can be more
3841 // cv-qualified than the deduced A (i.e., the type referred to
3842 // by the reference)
3843 if (ToType->isReferenceType())
3844 TDF |= TDF_ParamWithReferenceType;
3845 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003846 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003847 // conversion.
3848 //
3849 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3850 // both P and A are pointers or member pointers. In this case, we
3851 // just ignore cv-qualifiers completely).
3852 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003853 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003854 TDF |= TDF_IgnoreQualifiers;
3855 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003856 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3857 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003858 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003859
3860 // Create an Instantiation Scope for finalizing the operator.
3861 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003862 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003863 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003864 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003865 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3866 ConversionSpecialized, Info);
3867 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3868
3869 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003870 // to a ptr-to-function, use the deduced arguments from the conversion
3871 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003872 // e.g., int (*fp)(int) = [](auto a) { return a; };
3873 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3874
3875 // Get the return type of the destination ptr-to-function we are converting
3876 // to. This is necessary for matching the lambda call operator's return
3877 // type to that of the destination ptr-to-function's return type.
3878 assert(A->isPointerType() &&
3879 "Can only convert from lambda to ptr-to-function");
3880 const FunctionType *ToFunType =
3881 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003882 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3883
Faisal Vali2b3a3012013-10-24 23:40:02 +00003884 // Create the corresponding specializations of the call operator and
3885 // the static-invoker; and if the return type is auto,
3886 // deduce the return type and check if it matches the
3887 // DestFunctionPtrReturnType.
3888 // For instance:
3889 // auto L = [](auto a) { return f(a); };
3890 // int (*fp)(int) = L;
3891 // char (*fp2)(int) = L; <-- Not OK.
3892
3893 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3894 Specialization, Deduced, DestFunctionPtrReturnType,
3895 Info, *this);
3896 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003897 return Result;
3898}
3899
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003900/// \brief Deduce template arguments for a function template when there is
3901/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3902///
3903/// \param FunctionTemplate the function template for which we are performing
3904/// template argument deduction.
3905///
James Dennett18348b62012-06-22 08:52:37 +00003906/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003907/// arguments.
3908///
3909/// \param Specialization if template argument deduction was successful,
3910/// this will be set to the function template specialization produced by
3911/// template argument deduction.
3912///
3913/// \param Info the argument will be updated to provide additional information
3914/// about template argument deduction.
3915///
3916/// \returns the result of template argument deduction.
3917Sema::TemplateDeductionResult
3918Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003919 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003920 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003921 TemplateDeductionInfo &Info,
3922 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003923 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003924 QualType(), Specialization, Info,
3925 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003926}
3927
Richard Smith30482bc2011-02-20 03:19:35 +00003928namespace {
3929 /// Substitute the 'auto' type specifier within a type for a given replacement
3930 /// type.
3931 class SubstituteAutoTransform :
3932 public TreeTransform<SubstituteAutoTransform> {
3933 QualType Replacement;
3934 public:
Nico Weberc153d242014-07-28 00:02:09 +00003935 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3936 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3937 Replacement(Replacement) {}
3938
Richard Smith30482bc2011-02-20 03:19:35 +00003939 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3940 // If we're building the type pattern to deduce against, don't wrap the
3941 // substituted type in an AutoType. Certain template deduction rules
3942 // apply only when a template type parameter appears directly (and not if
3943 // the parameter is found through desugaring). For instance:
3944 // auto &&lref = lvalue;
3945 // must transform into "rvalue reference to T" not "rvalue reference to
3946 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003947 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003948 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003949 TemplateTypeParmTypeLoc NewTL =
3950 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003951 NewTL.setNameLoc(TL.getNameLoc());
3952 return Result;
3953 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003954 bool Dependent =
3955 !Replacement.isNull() && Replacement->isDependentType();
3956 QualType Result =
3957 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00003958 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003959 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003960 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3961 NewTL.setNameLoc(TL.getNameLoc());
3962 return Result;
3963 }
3964 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003965
3966 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3967 // Lambdas never need to be transformed.
3968 return E;
3969 }
Richard Smith061f1e22013-04-30 21:23:01 +00003970
Richard Smith2a7d4812013-05-04 07:00:32 +00003971 QualType Apply(TypeLoc TL) {
3972 // Create some scratch storage for the transformed type locations.
3973 // FIXME: We're just going to throw this information away. Don't build it.
3974 TypeLocBuilder TLB;
3975 TLB.reserve(TL.getFullDataSize());
3976 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003977 }
Richard Smith30482bc2011-02-20 03:19:35 +00003978 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003979}
Richard Smith30482bc2011-02-20 03:19:35 +00003980
Richard Smith2a7d4812013-05-04 07:00:32 +00003981Sema::DeduceAutoResult
3982Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3983 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3984}
3985
Richard Smith061f1e22013-04-30 21:23:01 +00003986/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003987///
3988/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003989/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003990/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003991/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003992Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003993Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003994 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003995 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3996 if (NonPlaceholder.isInvalid())
3997 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003998 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003999 }
4000
Richard Smith2a7d4812013-05-04 07:00:32 +00004001 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004002 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004003 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004004 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004005 }
4006
Richard Smith74aeef52013-04-26 16:15:35 +00004007 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4008 // Since 'decltype(auto)' can only occur at the top of the type, we
4009 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004010 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004011 if (AT->isDecltypeAuto()) {
4012 if (isa<InitListExpr>(Init)) {
4013 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4014 return DAR_FailedAlreadyDiagnosed;
4015 }
4016
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004017 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004018 if (Deduced.isNull())
4019 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004020 // FIXME: Support a non-canonical deduced type for 'auto'.
4021 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004022 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004023 if (Result.isNull())
4024 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004025 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004026 } else if (!getLangOpts().CPlusPlus) {
4027 if (isa<InitListExpr>(Init)) {
4028 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4029 return DAR_FailedAlreadyDiagnosed;
4030 }
Richard Smith74aeef52013-04-26 16:15:35 +00004031 }
4032 }
4033
Richard Smith30482bc2011-02-20 03:19:35 +00004034 SourceLocation Loc = Init->getExprLoc();
4035
4036 LocalInstantiationScope InstScope(*this);
4037
4038 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004039 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004040 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4041 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004042 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4043 NamedDecl *TemplParamPtr = TemplParam;
James Y Knight7a22b242015-08-06 20:26:32 +00004044 FixedSizeTemplateParameterListStorage<1> TemplateParamsSt(
David Majnemer902f8c62015-12-27 07:16:27 +00004045 Loc, Loc, TemplParamPtr, Loc);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004046
Richard Smith061f1e22013-04-30 21:23:01 +00004047 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4048 assert(!FuncParam.isNull() &&
4049 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004050
4051 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004052 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004053 Deduced.resize(1);
4054 QualType InitType = Init->getType();
4055 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004056
Craig Toppere6706e42012-09-19 02:26:47 +00004057 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004058
Richard Smith74801c82012-07-08 04:13:07 +00004059 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004060 if (InitList) {
4061 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004062 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4063 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004064 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004065 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004066 }
4067 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004068 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4069 Diag(Loc, diag::err_auto_bitfield);
4070 return DAR_FailedAlreadyDiagnosed;
4071 }
4072
James Y Knight7a22b242015-08-06 20:26:32 +00004073 if (AdjustFunctionParmAndArgTypesForDeduction(
4074 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004075 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004076
James Y Knight7a22b242015-08-06 20:26:32 +00004077 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4078 FuncParam, InitType, Info, Deduced,
4079 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004080 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004081 }
Richard Smith30482bc2011-02-20 03:19:35 +00004082
Eli Friedmane4310952012-11-06 23:56:42 +00004083 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004084 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004085
Eli Friedmane4310952012-11-06 23:56:42 +00004086 QualType DeducedType = Deduced[0].getAsType();
4087
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004088 if (InitList) {
4089 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4090 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004091 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004092 }
4093
Richard Smith061f1e22013-04-30 21:23:01 +00004094 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004095 if (Result.isNull())
4096 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004097
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004098 // Check that the deduced argument type is compatible with the original
4099 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004100 if (!InitList && !Result.isNull() &&
4101 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004102 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004103 Result)) {
4104 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004105 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004106 }
4107
Sebastian Redl09edce02012-01-23 22:09:39 +00004108 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004109}
4110
Faisal Vali2b391ab2013-09-26 19:54:12 +00004111QualType Sema::SubstAutoType(QualType TypeWithAuto,
4112 QualType TypeToReplaceAuto) {
4113 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4114 TransformType(TypeWithAuto);
4115}
4116
4117TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4118 QualType TypeToReplaceAuto) {
4119 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4120 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004121}
4122
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004123void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4124 if (isa<InitListExpr>(Init))
4125 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004126 VDecl->isInitCapture()
4127 ? diag::err_init_capture_deduction_failure_from_init_list
4128 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004129 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4130 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004131 Diag(VDecl->getLocation(),
4132 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4133 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004134 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4135 << Init->getSourceRange();
4136}
4137
Richard Smith2a7d4812013-05-04 07:00:32 +00004138bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4139 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004140 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004141
4142 if (FD->getTemplateInstantiationPattern())
4143 InstantiateFunctionDefinition(Loc, FD);
4144
Alp Toker314cc812014-01-25 16:55:45 +00004145 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004146 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4147 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4148 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4149 }
4150
4151 return StillUndeduced;
4152}
4153
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004154static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004155MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004156 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004157 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004158 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004159
4160/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004161static void
4162AddImplicitObjectParameterType(ASTContext &Context,
4163 CXXMethodDecl *Method,
4164 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004165 // C++11 [temp.func.order]p3:
4166 // [...] The new parameter is of type "reference to cv A," where cv are
4167 // the cv-qualifiers of the function template (if any) and A is
4168 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004169 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004170 // The standard doesn't say explicitly, but we pick the appropriate kind of
4171 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004172 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4173 ArgTy = Context.getQualifiedType(ArgTy,
4174 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004175 if (Method->getRefQualifier() == RQ_RValue)
4176 ArgTy = Context.getRValueReferenceType(ArgTy);
4177 else
4178 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004179 ArgTypes.push_back(ArgTy);
4180}
4181
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004182/// \brief Determine whether the function template \p FT1 is at least as
4183/// specialized as \p FT2.
4184static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004185 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004186 FunctionTemplateDecl *FT1,
4187 FunctionTemplateDecl *FT2,
4188 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004189 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004190 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004191 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004192 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4193 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004194
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004195 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4196 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004197 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004198 Deduced.resize(TemplateParams->size());
4199
4200 // C++0x [temp.deduct.partial]p3:
4201 // The types used to determine the ordering depend on the context in which
4202 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004203 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004204 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004205 switch (TPOC) {
4206 case TPOC_Call: {
4207 // - In the context of a function call, the function parameter types are
4208 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004209 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4210 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004211
Eli Friedman3b5774a2012-09-19 23:27:04 +00004212 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004213 // [...] If only one of the function templates is a non-static
4214 // member, that function template is considered to have a new
4215 // first parameter inserted in its function parameter list. The
4216 // new parameter is of type "reference to cv A," where cv are
4217 // the cv-qualifiers of the function template (if any) and A is
4218 // the class of which the function template is a member.
4219 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004220 // Note that we interpret this to mean "if one of the function
4221 // templates is a non-static member and the other is a non-member";
4222 // otherwise, the ordering rules for static functions against non-static
4223 // functions don't make any sense.
4224 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004225 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4226 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004227 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004228
Richard Smithe5b52202013-09-11 00:52:39 +00004229 unsigned NumComparedArguments = NumCallArguments1;
4230
4231 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004232 // Compare 'this' from Method1 against first parameter from Method2.
4233 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4234 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004235 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004236 // Compare 'this' from Method2 against first parameter from Method1.
4237 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004238 }
4239
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004240 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004241 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004242 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004243 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004244
Douglas Gregorb837ea42011-01-11 17:34:58 +00004245 // C++ [temp.func.order]p5:
4246 // The presence of unused ellipsis and default arguments has no effect on
4247 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004248 if (Args1.size() > NumComparedArguments)
4249 Args1.resize(NumComparedArguments);
4250 if (Args2.size() > NumComparedArguments)
4251 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004252 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4253 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004254 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004255 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004256
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004257 break;
4258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004260 case TPOC_Conversion:
4261 // - In the context of a call to a conversion operator, the return types
4262 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004263 if (DeduceTemplateArgumentsByTypeMatch(
4264 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4265 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004266 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004267 return false;
4268 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004269
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004270 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004271 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004272 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004273 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4274 FD2->getType(), FD1->getType(),
4275 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004276 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004277 return false;
4278 break;
4279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004281 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282 // In most cases, all template parameters must have values in order for
4283 // deduction to succeed, but for partial ordering purposes a template
4284 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004285 // types being used for partial ordering. [ Note: a template parameter used
4286 // in a non-deduced context is considered used. -end note]
4287 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4288 for (; ArgIdx != NumArgs; ++ArgIdx)
4289 if (Deduced[ArgIdx].isNull())
4290 break;
4291
4292 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004294 // as FT2.
4295 return true;
4296 }
4297
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004298 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004299 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004300 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004301 case TPOC_Call:
4302 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4303 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004304 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004305 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_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004309 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4310 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004311 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004313 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004314 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004315 TemplateParams->getDepth(),
4316 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004317 break;
4318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004320 for (; ArgIdx != NumArgs; ++ArgIdx)
4321 // If this argument had no value deduced but was used in one of the types
4322 // used for partial ordering, then deduction fails.
4323 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4324 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004325
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004326 return true;
4327}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328
Douglas Gregorcef1a032011-01-16 16:03:23 +00004329/// \brief Determine whether this a function template whose parameter-type-list
4330/// ends with a function parameter pack.
4331static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4332 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4333 unsigned NumParams = Function->getNumParams();
4334 if (NumParams == 0)
4335 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004336
Douglas Gregorcef1a032011-01-16 16:03:23 +00004337 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4338 if (!Last->isParameterPack())
4339 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340
Douglas Gregorcef1a032011-01-16 16:03:23 +00004341 // Make sure that no previous parameter is a parameter pack.
4342 while (--NumParams > 0) {
4343 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4344 return false;
4345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregorcef1a032011-01-16 16:03:23 +00004347 return true;
4348}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004349
Douglas Gregorbe999392009-09-15 16:23:51 +00004350/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004351/// to the rules of function template partial ordering (C++ [temp.func.order]).
4352///
4353/// \param FT1 the first function template
4354///
4355/// \param FT2 the second function template
4356///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004357/// \param TPOC the context in which we are performing partial ordering of
4358/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004359///
Richard Smithe5b52202013-09-11 00:52:39 +00004360/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4361/// only when \c TPOC is \c TPOC_Call.
4362///
4363/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4364/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004365///
Douglas Gregorbe999392009-09-15 16:23:51 +00004366/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004367/// template is more specialized, returns NULL.
4368FunctionTemplateDecl *
4369Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4370 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004371 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004372 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004373 unsigned NumCallArguments1,
4374 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004376 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004377 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004378 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004380 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004381 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004382
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004383 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004384 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004385
Douglas Gregorcef1a032011-01-16 16:03:23 +00004386 // FIXME: This mimics what GCC implements, but doesn't match up with the
4387 // proposed resolution for core issue 692. This area needs to be sorted out,
4388 // but for now we attempt to maintain compatibility.
4389 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4390 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4391 if (Variadic1 != Variadic2)
4392 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004393
Craig Topperc3ec1492014-05-26 06:22:03 +00004394 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004395}
Douglas Gregor9b146582009-07-08 20:55:45 +00004396
Douglas Gregor450f00842009-09-25 18:43:00 +00004397/// \brief Determine if the two templates are equivalent.
4398static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4399 if (T1 == T2)
4400 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
Douglas Gregor450f00842009-09-25 18:43:00 +00004402 if (!T1 || !T2)
4403 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004404
Douglas Gregor450f00842009-09-25 18:43:00 +00004405 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4406}
4407
4408/// \brief Retrieve the most specialized of the given function template
4409/// specializations.
4410///
John McCall58cc69d2010-01-27 01:50:18 +00004411/// \param SpecBegin the start iterator of the function template
4412/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004413///
John McCall58cc69d2010-01-27 01:50:18 +00004414/// \param SpecEnd the end iterator of the function template
4415/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004416///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004417/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004418/// diagnostic should occur.
4419///
4420/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4421/// no matching candidates.
4422///
4423/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4424/// occurs.
4425///
4426/// \param CandidateDiag partial diagnostic used for each function template
4427/// specialization that is a candidate in the ambiguous ordering. One parameter
4428/// in this diagnostic should be unbound, which will correspond to the string
4429/// describing the template arguments for the function template specialization.
4430///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004432/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004433UnresolvedSetIterator Sema::getMostSpecialized(
4434 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4435 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004436 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4437 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4438 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004439 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004440 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004441 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004442 FailedCandidates.NoteCandidates(*this, Loc);
4443 }
John McCall58cc69d2010-01-27 01:50:18 +00004444 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446
4447 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004448 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449
Douglas Gregor450f00842009-09-25 18:43:00 +00004450 // Find the function template that is better than all of the templates it
4451 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004452 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004453 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004454 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004455 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004456 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4457 FunctionTemplateDecl *Challenger
4458 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004459 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004460 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004461 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004462 Challenger)) {
4463 Best = I;
4464 BestTemplate = Challenger;
4465 }
4466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467
Douglas Gregor450f00842009-09-25 18:43:00 +00004468 // Make sure that the "best" function template is more specialized than all
4469 // of the others.
4470 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004471 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4472 FunctionTemplateDecl *Challenger
4473 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004474 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004476 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004477 BestTemplate)) {
4478 Ambiguous = true;
4479 break;
4480 }
4481 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
Douglas Gregor450f00842009-09-25 18:43:00 +00004483 if (!Ambiguous) {
4484 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004485 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004486 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004487
Douglas Gregor450f00842009-09-25 18:43:00 +00004488 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004489 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004490 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491
Richard Smithb875c432013-05-04 01:51:08 +00004492 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004493 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4494 PartialDiagnostic PD = CandidateDiag;
4495 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004496 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004497 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004498 if (!TargetType.isNull())
4499 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4500 TargetType);
4501 Diag((*I)->getLocation(), PD);
4502 }
Richard Smithb875c432013-05-04 01:51:08 +00004503 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004504
John McCall58cc69d2010-01-27 01:50:18 +00004505 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004506}
4507
Douglas Gregorbe999392009-09-15 16:23:51 +00004508/// \brief Returns the more specialized class template partial specialization
4509/// according to the rules of partial ordering of class template partial
4510/// specializations (C++ [temp.class.order]).
4511///
4512/// \param PS1 the first class template partial specialization
4513///
4514/// \param PS2 the second class template partial specialization
4515///
4516/// \returns the more specialized class template partial specialization. If
4517/// neither partial specialization is more specialized, returns NULL.
4518ClassTemplatePartialSpecializationDecl *
4519Sema::getMoreSpecializedPartialSpecialization(
4520 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004521 ClassTemplatePartialSpecializationDecl *PS2,
4522 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004523 // C++ [temp.class.order]p1:
4524 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525 // specialized as the second if, given the following rewrite to two
4526 // function templates, the first function template is at least as
4527 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004528 // templates (14.6.6.2):
4529 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530 // first partial specialization and has a single function parameter
4531 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004532 // arguments of the first partial specialization, and
4533 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534 // second partial specialization and has a single function parameter
4535 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004536 // arguments of the second partial specialization.
4537 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004538 // Rather than synthesize function templates, we merely perform the
4539 // equivalent partial ordering by performing deduction directly on
4540 // the template arguments of the class template partial
4541 // specializations. This computation is slightly simpler than the
4542 // general problem of function template partial ordering, because
4543 // class template partial specializations are more constrained. We
4544 // know that every template parameter is deducible from the class
4545 // template partial specialization's template arguments, for
4546 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004547 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004548 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004549
4550 QualType PT1 = PS1->getInjectedSpecializationType();
4551 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552
Douglas Gregorbe999392009-09-15 16:23:51 +00004553 // Determine whether PS1 is at least as specialized as PS2
4554 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004555 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4556 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004557 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004558 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004559 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004560 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004561 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004562 Better1 = !::FinishTemplateArgumentDeduction(
4563 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4564 }
4565
4566 // Determine whether PS2 is at least as specialized as PS1
4567 Deduced.clear();
4568 Deduced.resize(PS1->getTemplateParameters()->size());
4569 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4570 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004571 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004572 if (Better2) {
4573 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4574 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004575 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004576 Better2 = !::FinishTemplateArgumentDeduction(
4577 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4578 }
4579
4580 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004581 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004582
4583 return Better1 ? PS1 : PS2;
4584}
4585
Larisse Voufo30616382013-08-23 22:21:36 +00004586/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4587/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4588/// VarTemplate(Partial)SpecializationDecl with a new data
4589/// structure Template(Partial)SpecializationDecl, and
4590/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004591VarTemplatePartialSpecializationDecl *
4592Sema::getMoreSpecializedPartialSpecialization(
4593 VarTemplatePartialSpecializationDecl *PS1,
4594 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4595 SmallVector<DeducedTemplateArgument, 4> Deduced;
4596 TemplateDeductionInfo Info(Loc);
4597
Richard Smithf04fd0b2013-12-12 23:14:16 +00004598 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004599 "the partial specializations being compared should specialize"
4600 " the same template.");
4601 TemplateName Name(PS1->getSpecializedTemplate());
4602 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4603 QualType PT1 = Context.getTemplateSpecializationType(
4604 CanonTemplate, PS1->getTemplateArgs().data(),
4605 PS1->getTemplateArgs().size());
4606 QualType PT2 = Context.getTemplateSpecializationType(
4607 CanonTemplate, PS2->getTemplateArgs().data(),
4608 PS2->getTemplateArgs().size());
4609
4610 // Determine whether PS1 is at least as specialized as PS2
4611 Deduced.resize(PS2->getTemplateParameters()->size());
4612 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4613 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004614 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004615 if (Better1) {
4616 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4617 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004618 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004619 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4620 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004621 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623
Douglas Gregorbe999392009-09-15 16:23:51 +00004624 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004625 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004626 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004627 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4628 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004629 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004630 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004631 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004632 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004633 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004634 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4635 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004636 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004637 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004638
Douglas Gregorbe999392009-09-15 16:23:51 +00004639 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004640 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004641
Douglas Gregorbe999392009-09-15 16:23:51 +00004642 return Better1? PS1 : PS2;
4643}
4644
Mike Stump11289f42009-09-09 15:08:12 +00004645static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004646MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004647 const TemplateArgument &TemplateArg,
4648 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004649 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004650 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004651
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004652/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004653/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004654static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004655MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004656 const Expr *E,
4657 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004658 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004659 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004660 // We can deduce from a pack expansion.
4661 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4662 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663
Richard Smith34349002012-07-09 03:07:20 +00004664 // Skip through any implicit casts we added while type-checking, and any
4665 // substitutions performed by template alias expansion.
4666 while (1) {
4667 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4668 E = ICE->getSubExpr();
4669 else if (const SubstNonTypeTemplateParmExpr *Subst =
4670 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4671 E = Subst->getReplacement();
4672 else
4673 break;
4674 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004675
4676 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004677 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004678 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004679 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004680 return;
4681
Mike Stump11289f42009-09-09 15:08:12 +00004682 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004683 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4684 if (!NTTP)
4685 return;
4686
Douglas Gregor21610382009-10-29 00:04:11 +00004687 if (NTTP->getDepth() == Depth)
4688 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004689}
4690
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004691/// \brief Mark the template parameters that are used by the given
4692/// nested name specifier.
4693static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004694MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004695 NestedNameSpecifier *NNS,
4696 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004697 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004698 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004699 if (!NNS)
4700 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004701
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004702 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004703 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004704 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004705 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004706}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004708/// \brief Mark the template parameters that are used by the given
4709/// template name.
4710static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004711MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004712 TemplateName Name,
4713 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004714 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004715 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004716 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4717 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004718 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4719 if (TTP->getDepth() == Depth)
4720 Used[TTP->getIndex()] = true;
4721 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004722 return;
4723 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004725 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004726 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004727 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004728 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004729 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004730 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004731}
4732
4733/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004734/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004735static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004736MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004737 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004738 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004739 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004740 if (T.isNull())
4741 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004742
Douglas Gregor91772d12009-06-13 00:26:55 +00004743 // Non-dependent types have nothing deducible
4744 if (!T->isDependentType())
4745 return;
4746
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004747 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004748 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004749 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004750 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004751 cast<PointerType>(T)->getPointeeType(),
4752 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004753 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004754 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004755 break;
4756
4757 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004758 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004759 cast<BlockPointerType>(T)->getPointeeType(),
4760 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004761 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004762 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004763 break;
4764
4765 case Type::LValueReference:
4766 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004767 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004768 cast<ReferenceType>(T)->getPointeeType(),
4769 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004770 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004771 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004772 break;
4773
4774 case Type::MemberPointer: {
4775 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004776 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004777 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004778 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004779 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004780 break;
4781 }
4782
4783 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004784 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004785 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004786 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004787 // Fall through to check the element type
4788
4789 case Type::ConstantArray:
4790 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004791 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004792 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004793 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004794 break;
4795
4796 case Type::Vector:
4797 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004798 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004799 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004800 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004801 break;
4802
Douglas Gregor758a8692009-06-17 21:51:59 +00004803 case Type::DependentSizedExtVector: {
4804 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004805 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004806 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004807 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004808 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004809 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004810 break;
4811 }
4812
Douglas Gregor91772d12009-06-13 00:26:55 +00004813 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004814 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004815 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4816 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004817 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4818 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004819 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004820 break;
4821 }
4822
Douglas Gregor21610382009-10-29 00:04:11 +00004823 case Type::TemplateTypeParm: {
4824 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4825 if (TTP->getDepth() == Depth)
4826 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004827 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004828 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004829
Douglas Gregorfb322d82011-01-14 05:11:40 +00004830 case Type::SubstTemplateTypeParmPack: {
4831 const SubstTemplateTypeParmPackType *Subst
4832 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004833 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004834 QualType(Subst->getReplacedParameter(), 0),
4835 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004836 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004837 OnlyDeduced, Depth, Used);
4838 break;
4839 }
4840
John McCall2408e322010-04-27 00:57:59 +00004841 case Type::InjectedClassName:
4842 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4843 // fall through
4844
Douglas Gregor91772d12009-06-13 00:26:55 +00004845 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004846 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004847 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004848 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004849 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004850
Douglas Gregord0ad2942010-12-23 01:24:45 +00004851 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004852 // If the template argument list of P contains a pack expansion that is
4853 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004854 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004855 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004856 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4857 break;
4858
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004859 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004860 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004861 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004862 break;
4863 }
4864
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004865 case Type::Complex:
4866 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004867 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004868 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004869 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004870 break;
4871
Eli Friedman0dfb8892011-10-06 23:00:33 +00004872 case Type::Atomic:
4873 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004874 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004875 cast<AtomicType>(T)->getValueType(),
4876 OnlyDeduced, Depth, Used);
4877 break;
4878
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004879 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004880 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004881 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004882 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004883 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004884 break;
4885
John McCallc392f372010-06-11 00:33:02 +00004886 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004887 // C++14 [temp.deduct.type]p5:
4888 // The non-deduced contexts are:
4889 // -- The nested-name-specifier of a type that was specified using a
4890 // qualified-id
4891 //
4892 // C++14 [temp.deduct.type]p6:
4893 // When a type name is specified in a way that includes a non-deduced
4894 // context, all of the types that comprise that type name are also
4895 // non-deduced.
4896 if (OnlyDeduced)
4897 break;
4898
John McCallc392f372010-06-11 00:33:02 +00004899 const DependentTemplateSpecializationType *Spec
4900 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901
Richard Smith50d5b972015-12-30 20:56:05 +00004902 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4903 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004904
John McCallc392f372010-06-11 00:33:02 +00004905 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004906 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004907 Used);
4908 break;
4909 }
4910
John McCallbd8d9bd2010-03-01 23:49:17 +00004911 case Type::TypeOf:
4912 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004913 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004914 cast<TypeOfType>(T)->getUnderlyingType(),
4915 OnlyDeduced, Depth, Used);
4916 break;
4917
4918 case Type::TypeOfExpr:
4919 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004920 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004921 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4922 OnlyDeduced, Depth, Used);
4923 break;
4924
4925 case Type::Decltype:
4926 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004927 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004928 cast<DecltypeType>(T)->getUnderlyingExpr(),
4929 OnlyDeduced, Depth, Used);
4930 break;
4931
Alexis Hunte852b102011-05-24 22:41:36 +00004932 case Type::UnaryTransform:
4933 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004934 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004935 cast<UnaryTransformType>(T)->getUnderlyingType(),
4936 OnlyDeduced, Depth, Used);
4937 break;
4938
Douglas Gregord2fa7662010-12-20 02:24:11 +00004939 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004940 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004941 cast<PackExpansionType>(T)->getPattern(),
4942 OnlyDeduced, Depth, Used);
4943 break;
4944
Richard Smith30482bc2011-02-20 03:19:35 +00004945 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004946 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004947 cast<AutoType>(T)->getDeducedType(),
4948 OnlyDeduced, Depth, Used);
4949
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004950 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004951 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004952 case Type::VariableArray:
4953 case Type::FunctionNoProto:
4954 case Type::Record:
4955 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004956 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004957 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004958 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004959 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00004960 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00004961#define TYPE(Class, Base)
4962#define ABSTRACT_TYPE(Class, Base)
4963#define DEPENDENT_TYPE(Class, Base)
4964#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4965#include "clang/AST/TypeNodes.def"
4966 break;
4967 }
4968}
4969
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004970/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004971/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004972static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004973MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004974 const TemplateArgument &TemplateArg,
4975 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004976 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004977 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004978 switch (TemplateArg.getKind()) {
4979 case TemplateArgument::Null:
4980 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004981 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004982 break;
Mike Stump11289f42009-09-09 15:08:12 +00004983
Eli Friedmanb826a002012-09-26 02:36:12 +00004984 case TemplateArgument::NullPtr:
4985 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4986 Depth, Used);
4987 break;
4988
Douglas Gregor91772d12009-06-13 00:26:55 +00004989 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004990 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004991 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004992 break;
4993
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004994 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004995 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004996 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004997 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004998 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004999 break;
5000
5001 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005002 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005003 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005004 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005
Anders Carlssonbc343912009-06-15 17:04:53 +00005006 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005007 for (const auto &P : TemplateArg.pack_elements())
5008 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005009 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005010 }
5011}
5012
James Dennett41725122012-06-22 10:16:05 +00005013/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005014/// template argument list.
5015///
5016/// \param TemplateArgs the template argument list from which template
5017/// parameters will be deduced.
5018///
James Dennett41725122012-06-22 10:16:05 +00005019/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005020/// to indicate when the corresponding template parameter will be
5021/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005022void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005023Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005024 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005025 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005026 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027 // If the template argument list of P contains a pack expansion that is not
5028 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005029 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005031 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5032 return;
5033
Douglas Gregor91772d12009-06-13 00:26:55 +00005034 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005035 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005036 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005037}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005038
5039/// \brief Marks all of the template parameters that will be deduced by a
5040/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005041void Sema::MarkDeducedTemplateParameters(
5042 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5043 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005045 = FunctionTemplate->getTemplateParameters();
5046 Deduced.clear();
5047 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048
Douglas Gregorce23bae2009-09-18 23:21:38 +00005049 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5050 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005051 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005052 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005053}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005054
5055bool hasDeducibleTemplateParameters(Sema &S,
5056 FunctionTemplateDecl *FunctionTemplate,
5057 QualType T) {
5058 if (!T->isDependentType())
5059 return false;
5060
5061 TemplateParameterList *TemplateParams
5062 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005063 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005064 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005065 Deduced);
5066
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005067 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005068}