blob: 0b090c8ff7eedf832f9036e499759873feb7ebf8 [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: {
1421 const TemplateSpecializationType *SpecParam
1422 = cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001423
Douglas Gregore81f3e72009-07-07 23:09:34 +00001424 // Try to deduce template arguments from the template-id.
1425 Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00001426 = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
Douglas Gregore81f3e72009-07-07 23:09:34 +00001427 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001428
Douglas Gregor42909752009-09-30 22:13:51 +00001429 if (Result && (TDF & TDF_DerivedClass)) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001430 // C++ [temp.deduct.call]p3b3:
1431 // If P is a class, and P has the form template-id, then A can be a
1432 // derived class of the deduced A. Likewise, if P is a pointer to a
Mike Stump11289f42009-09-09 15:08:12 +00001433 // class of the form template-id, A can be a pointer to a derived
Douglas Gregore81f3e72009-07-07 23:09:34 +00001434 // class pointed to by the deduced A.
1435 //
1436 // More importantly:
Mike Stump11289f42009-09-09 15:08:12 +00001437 // These alternatives are considered only if type deduction would
Douglas Gregore81f3e72009-07-07 23:09:34 +00001438 // otherwise fail.
Chandler Carruthc1263112010-02-07 21:33:28 +00001439 if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1440 // 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.
Richard Smithdb0ac552015-12-18 22:40:25 +00001443 if (!S.isCompleteType(Info.getLocation(), Arg))
Chandler Carruthc1263112010-02-07 21:33:28 +00001444 return Result;
1445
Douglas Gregore81f3e72009-07-07 23:09:34 +00001446 // Use data recursion to crawl through the list of base classes.
Mike Stump11289f42009-09-09 15:08:12 +00001447 // Visited contains the set of nodes we have already visited, while
Douglas Gregore81f3e72009-07-07 23:09:34 +00001448 // ToVisit is our stack of records that we still need to visit.
1449 llvm::SmallPtrSet<const RecordType *, 8> Visited;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001450 SmallVector<const RecordType *, 8> ToVisit;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001451 ToVisit.push_back(RecordT);
1452 bool Successful = false;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001453 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1454 Deduced.end());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001455 while (!ToVisit.empty()) {
1456 // Retrieve the next class in the inheritance hierarchy.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001457 const RecordType *NextT = ToVisit.pop_back_val();
Mike Stump11289f42009-09-09 15:08:12 +00001458
Douglas Gregore81f3e72009-07-07 23:09:34 +00001459 // If we have already seen this type, skip it.
David Blaikie82e95a32014-11-19 07:49:47 +00001460 if (!Visited.insert(NextT).second)
Douglas Gregore81f3e72009-07-07 23:09:34 +00001461 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001462
Douglas Gregore81f3e72009-07-07 23:09:34 +00001463 // If this is a base class, try to perform template argument
1464 // deduction from it.
1465 if (NextT != RecordT) {
Richard Trieu23bafad2012-11-07 21:17:13 +00001466 TemplateDeductionInfo BaseInfo(Info.getLocation());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001467 Sema::TemplateDeductionResult BaseResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001468 = DeduceTemplateArguments(S, TemplateParams, SpecParam,
Richard Trieu23bafad2012-11-07 21:17:13 +00001469 QualType(NextT, 0), BaseInfo,
1470 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001471
Douglas Gregore81f3e72009-07-07 23:09:34 +00001472 // If template argument deduction for this base was successful,
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001473 // note that we had some success. Otherwise, ignore any deductions
1474 // from this base class.
1475 if (BaseResult == Sema::TDK_Success) {
Douglas Gregore81f3e72009-07-07 23:09:34 +00001476 Successful = true;
Benjamin Kramer4d08ccb2012-01-20 16:39:18 +00001477 DeducedOrig.clear();
1478 DeducedOrig.append(Deduced.begin(), Deduced.end());
Richard Trieu23bafad2012-11-07 21:17:13 +00001479 Info.Param = BaseInfo.Param;
1480 Info.FirstArg = BaseInfo.FirstArg;
1481 Info.SecondArg = BaseInfo.SecondArg;
Douglas Gregore0f7a8a2010-11-02 00:02:34 +00001482 }
1483 else
1484 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
Douglas Gregore81f3e72009-07-07 23:09:34 +00001487 // Visit base classes
1488 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
Aaron Ballman574705e2014-03-13 15:41:46 +00001489 for (const auto &Base : Next->bases()) {
1490 assert(Base.getType()->isRecordType() &&
Douglas Gregore81f3e72009-07-07 23:09:34 +00001491 "Base class that isn't a record?");
Aaron Ballman574705e2014-03-13 15:41:46 +00001492 ToVisit.push_back(Base.getType()->getAs<RecordType>());
Douglas Gregore81f3e72009-07-07 23:09:34 +00001493 }
1494 }
Mike Stump11289f42009-09-09 15:08:12 +00001495
Douglas Gregore81f3e72009-07-07 23:09:34 +00001496 if (Successful)
1497 return Sema::TDK_Success;
1498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Douglas Gregore81f3e72009-07-07 23:09:34 +00001500 }
Mike Stump11289f42009-09-09 15:08:12 +00001501
Douglas Gregore81f3e72009-07-07 23:09:34 +00001502 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001503 }
1504
Douglas Gregor637d9982009-06-10 23:47:09 +00001505 // T type::*
1506 // T T::*
1507 // T (type::*)()
1508 // type (T::*)()
1509 // type (type::*)(T)
1510 // type (T::*)(T)
1511 // T (type::*)(T)
1512 // T (T::*)()
1513 // T (T::*)(T)
1514 case Type::MemberPointer: {
1515 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1516 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1517 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001518 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001519
David Majnemera381cda2015-11-30 20:34:28 +00001520 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1521 if (ParamPointeeType->isFunctionType())
1522 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1523 /*IsCtorOrDtor=*/false, Info.getLocation());
1524 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1525 if (ArgPointeeType->isFunctionType())
1526 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1527 /*IsCtorOrDtor=*/false, Info.getLocation());
1528
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001529 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001530 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001531 ParamPointeeType,
1532 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001533 Info, Deduced,
1534 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001535 return Result;
1536
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001537 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1538 QualType(MemPtrParam->getClass(), 0),
1539 QualType(MemPtrArg->getClass(), 0),
Douglas Gregor194ea692012-03-11 03:29:50 +00001540 Info, Deduced,
1541 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001542 }
1543
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001544 // (clang extension)
1545 //
Mike Stump11289f42009-09-09 15:08:12 +00001546 // type(^)(T)
1547 // T(^)()
1548 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001549 case Type::BlockPointer: {
1550 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1551 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001552
Anders Carlssona767eee2009-06-12 16:23:10 +00001553 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001554 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001555
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001556 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1557 BlockPtrParam->getPointeeType(),
1558 BlockPtrArg->getPointeeType(),
1559 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001560 }
1561
Douglas Gregor39c02722011-06-15 16:02:29 +00001562 // (clang extension)
1563 //
1564 // T __attribute__(((ext_vector_type(<integral constant>))))
1565 case Type::ExtVector: {
1566 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1567 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1568 // Make sure that the vectors have the same number of elements.
1569 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1570 return Sema::TDK_NonDeducedMismatch;
1571
1572 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001573 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1574 VectorParam->getElementType(),
1575 VectorArg->getElementType(),
1576 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001577 }
1578
1579 if (const DependentSizedExtVectorType *VectorArg
1580 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1581 // We can't check the number of elements, since the argument has a
1582 // dependent number of elements. This can only occur during partial
1583 // ordering.
1584
1585 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001586 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1587 VectorParam->getElementType(),
1588 VectorArg->getElementType(),
1589 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001590 }
1591
1592 return Sema::TDK_NonDeducedMismatch;
1593 }
1594
1595 // (clang extension)
1596 //
1597 // T __attribute__(((ext_vector_type(N))))
1598 case Type::DependentSizedExtVector: {
1599 const DependentSizedExtVectorType *VectorParam
1600 = cast<DependentSizedExtVectorType>(Param);
1601
1602 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1603 // Perform deduction on the element types.
1604 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001605 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1606 VectorParam->getElementType(),
1607 VectorArg->getElementType(),
1608 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001609 return Result;
1610
1611 // Perform deduction on the vector size, if we can.
1612 NonTypeTemplateParmDecl *NTTP
1613 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1614 if (!NTTP)
1615 return Sema::TDK_Success;
1616
1617 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1618 ArgSize = VectorArg->getNumElements();
1619 return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1620 false, Info, Deduced);
1621 }
1622
1623 if (const DependentSizedExtVectorType *VectorArg
1624 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1625 // Perform deduction on the element types.
1626 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001627 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1628 VectorParam->getElementType(),
1629 VectorArg->getElementType(),
1630 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001631 return Result;
1632
1633 // Perform deduction on the vector size, if we can.
1634 NonTypeTemplateParmDecl *NTTP
1635 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1636 if (!NTTP)
1637 return Sema::TDK_Success;
1638
1639 return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1640 Info, Deduced);
1641 }
1642
1643 return Sema::TDK_NonDeducedMismatch;
1644 }
1645
Douglas Gregor637d9982009-06-10 23:47:09 +00001646 case Type::TypeOfExpr:
1647 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001648 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001649 case Type::UnresolvedUsing:
1650 case Type::Decltype:
1651 case Type::UnaryTransform:
1652 case Type::Auto:
1653 case Type::DependentTemplateSpecialization:
1654 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001655 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001656 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001657 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001658 }
1659
David Blaikiee4d798f2012-01-20 21:50:17 +00001660 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001661}
1662
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001663static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001664DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001665 TemplateParameterList *TemplateParams,
1666 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001667 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001668 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001669 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001670 // If the template argument is a pack expansion, perform template argument
1671 // deduction against the pattern of that expansion. This only occurs during
1672 // partial ordering.
1673 if (Arg.isPackExpansion())
1674 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001676 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001677 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001678 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001679
1680 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001681 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001682 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1683 Param.getAsType(),
1684 Arg.getAsType(),
1685 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001686 Info.FirstArg = Param;
1687 Info.SecondArg = Arg;
1688 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001689
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001690 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001691 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001692 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001693 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001694 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001695 Info.FirstArg = Param;
1696 Info.SecondArg = Arg;
1697 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001698
1699 case TemplateArgument::TemplateExpansion:
1700 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001701
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001702 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001703 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001704 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001705 return Sema::TDK_Success;
1706
1707 Info.FirstArg = Param;
1708 Info.SecondArg = Arg;
1709 return Sema::TDK_NonDeducedMismatch;
1710
1711 case TemplateArgument::NullPtr:
1712 if (Arg.getKind() == TemplateArgument::NullPtr &&
1713 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001714 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001715
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001716 Info.FirstArg = Param;
1717 Info.SecondArg = Arg;
1718 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001719
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001720 case TemplateArgument::Integral:
1721 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001722 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001723 return Sema::TDK_Success;
1724
1725 Info.FirstArg = Param;
1726 Info.SecondArg = Arg;
1727 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001728 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001729
1730 if (Arg.getKind() == TemplateArgument::Expression) {
1731 Info.FirstArg = Param;
1732 Info.SecondArg = Arg;
1733 return Sema::TDK_NonDeducedMismatch;
1734 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001735
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001736 Info.FirstArg = Param;
1737 Info.SecondArg = Arg;
1738 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001739
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001740 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001741 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001742 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1743 if (Arg.getKind() == TemplateArgument::Integral)
Chandler Carruthc1263112010-02-07 21:33:28 +00001744 return DeduceNonTypeTemplateArgument(S, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001745 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001746 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001747 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001748 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001749 if (Arg.getKind() == TemplateArgument::Expression)
Chandler Carruthc1263112010-02-07 21:33:28 +00001750 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001751 Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001752 if (Arg.getKind() == TemplateArgument::Declaration)
Chandler Carruthc1263112010-02-07 21:33:28 +00001753 return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001754 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001755
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001756 Info.FirstArg = Param;
1757 Info.SecondArg = Arg;
1758 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001759 }
Mike Stump11289f42009-09-09 15:08:12 +00001760
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001761 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001762 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001763 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001764 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001765 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001766 }
Mike Stump11289f42009-09-09 15:08:12 +00001767
David Blaikiee4d798f2012-01-20 21:50:17 +00001768 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001769}
1770
Douglas Gregor7baabef2010-12-22 18:17:10 +00001771/// \brief Determine whether there is a template argument to be used for
1772/// deduction.
1773///
1774/// This routine "expands" argument packs in-place, overriding its input
1775/// parameters so that \c Args[ArgIdx] will be the available template argument.
1776///
1777/// \returns true if there is another template argument (which will be at
1778/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001779static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001780 unsigned &ArgIdx,
1781 unsigned &NumArgs) {
1782 if (ArgIdx == NumArgs)
1783 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
Douglas Gregor7baabef2010-12-22 18:17:10 +00001785 const TemplateArgument &Arg = Args[ArgIdx];
1786 if (Arg.getKind() != TemplateArgument::Pack)
1787 return true;
1788
1789 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1790 Args = Arg.pack_begin();
1791 NumArgs = Arg.pack_size();
1792 ArgIdx = 0;
1793 return ArgIdx < NumArgs;
1794}
1795
Douglas Gregord0ad2942010-12-23 01:24:45 +00001796/// \brief Determine whether the given set of template arguments has a pack
1797/// expansion that is not the last template argument.
1798static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1799 unsigned NumArgs) {
1800 unsigned ArgIdx = 0;
1801 while (ArgIdx < NumArgs) {
1802 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001803
Douglas Gregord0ad2942010-12-23 01:24:45 +00001804 // Unwrap argument packs.
1805 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1806 Args = Arg.pack_begin();
1807 NumArgs = Arg.pack_size();
1808 ArgIdx = 0;
1809 continue;
1810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001811
Douglas Gregord0ad2942010-12-23 01:24:45 +00001812 ++ArgIdx;
1813 if (ArgIdx == NumArgs)
1814 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001815
Douglas Gregord0ad2942010-12-23 01:24:45 +00001816 if (Arg.isPackExpansion())
1817 return true;
1818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001819
Douglas Gregord0ad2942010-12-23 01:24:45 +00001820 return false;
1821}
1822
Douglas Gregor7baabef2010-12-22 18:17:10 +00001823static Sema::TemplateDeductionResult
1824DeduceTemplateArguments(Sema &S,
1825 TemplateParameterList *TemplateParams,
1826 const TemplateArgument *Params, unsigned NumParams,
1827 const TemplateArgument *Args, unsigned NumArgs,
1828 TemplateDeductionInfo &Info,
Richard Smith16b65392012-12-06 06:44:44 +00001829 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001830 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001831 // If the template argument list of P contains a pack expansion that is not
1832 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001833 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001834 if (hasPackExpansionBeforeEnd(Params, NumParams))
1835 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001836
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001837 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001838 // If P has a form that contains <T> or <i>, then each argument Pi of the
1839 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001840 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001841 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001842 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001843 ++ParamIdx) {
1844 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001845 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846
Douglas Gregor7baabef2010-12-22 18:17:10 +00001847 // Check whether we have enough arguments.
1848 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
Richard Smith16b65392012-12-06 06:44:44 +00001849 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001850
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001851 if (Args[ArgIdx].isPackExpansion()) {
1852 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1853 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001854 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001857 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001858 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001859 = DeduceTemplateArguments(S, TemplateParams,
1860 Params[ParamIdx], Args[ArgIdx],
1861 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862 return Result;
1863
Douglas Gregor7baabef2010-12-22 18:17:10 +00001864 // Move to the next argument.
1865 ++ArgIdx;
1866 continue;
1867 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001869 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001870
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001871 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001872 // If Pi is a pack expansion, then the pattern of Pi is compared with
1873 // each remaining argument in the template argument list of A. Each
1874 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001875 // template parameter packs expanded by Pi.
1876 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001877
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001878 // FIXME: If there are no remaining arguments, we can bail out early
1879 // and set any deduced parameter packs to an empty argument pack.
1880 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001881
Richard Smith0a80d572014-05-29 01:12:14 +00001882 // Prepare to deduce the packs within the pattern.
1883 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001884
1885 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001886 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001887 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001888 bool HasAnyArguments = false;
Richard Smith0a80d572014-05-29 01:12:14 +00001889 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001890 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001892 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001893 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001894 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1895 Info, Deduced))
1896 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897
Richard Smith0a80d572014-05-29 01:12:14 +00001898 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001900
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001901 // Build argument packs for each of the parameter packs expanded by this
1902 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001903 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001904 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001906
Douglas Gregor7baabef2010-12-22 18:17:10 +00001907 return Sema::TDK_Success;
1908}
1909
Mike Stump11289f42009-09-09 15:08:12 +00001910static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001911DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001912 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001913 const TemplateArgumentList &ParamList,
1914 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001915 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001916 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001918 ParamList.data(), ParamList.size(),
1919 ArgList.data(), ArgList.size(),
1920 Info, Deduced);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001921}
1922
Douglas Gregor705c9002009-06-26 20:57:09 +00001923/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001924static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001925 const TemplateArgument &X,
1926 const TemplateArgument &Y) {
1927 if (X.getKind() != Y.getKind())
1928 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001929
Douglas Gregor705c9002009-06-26 20:57:09 +00001930 switch (X.getKind()) {
1931 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001932 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001933
Douglas Gregor705c9002009-06-26 20:57:09 +00001934 case TemplateArgument::Type:
1935 return Context.getCanonicalType(X.getAsType()) ==
1936 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001937
Douglas Gregor705c9002009-06-26 20:57:09 +00001938 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001939 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001940
1941 case TemplateArgument::NullPtr:
1942 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001943
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001944 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001945 case TemplateArgument::TemplateExpansion:
1946 return Context.getCanonicalTemplateName(
1947 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1948 Context.getCanonicalTemplateName(
1949 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001950
Douglas Gregor705c9002009-06-26 20:57:09 +00001951 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001952 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00001953
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001954 case TemplateArgument::Expression: {
1955 llvm::FoldingSetNodeID XID, YID;
1956 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001958 return XID == YID;
1959 }
Mike Stump11289f42009-09-09 15:08:12 +00001960
Douglas Gregor705c9002009-06-26 20:57:09 +00001961 case TemplateArgument::Pack:
1962 if (X.pack_size() != Y.pack_size())
1963 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001964
1965 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
1966 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00001967 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00001968 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00001969 if (!isSameTemplateArg(Context, *XP, *YP))
1970 return false;
1971
1972 return true;
1973 }
1974
David Blaikiee4d798f2012-01-20 21:50:17 +00001975 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00001976}
1977
Douglas Gregorca4686d2011-01-04 23:35:54 +00001978/// \brief Allocate a TemplateArgumentLoc where all locations have
1979/// been initialized to the given location.
1980///
1981/// \param S The semantic analysis object.
1982///
James Dennett634962f2012-06-14 21:40:34 +00001983/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00001984/// location information for.
1985///
1986/// \param NTTPType For a declaration template argument, the type of
1987/// the non-type template parameter that corresponds to this template
1988/// argument.
1989///
1990/// \param Loc The source location to use for the resulting template
1991/// argument.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001992static TemplateArgumentLoc
Douglas Gregorca4686d2011-01-04 23:35:54 +00001993getTrivialTemplateArgumentLoc(Sema &S,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994 const TemplateArgument &Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00001995 QualType NTTPType,
1996 SourceLocation Loc) {
1997 switch (Arg.getKind()) {
1998 case TemplateArgument::Null:
1999 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Douglas Gregorca4686d2011-01-04 23:35:54 +00002001 case TemplateArgument::Type:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002 return TemplateArgumentLoc(Arg,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002003 S.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004
Douglas Gregorca4686d2011-01-04 23:35:54 +00002005 case TemplateArgument::Declaration: {
2006 Expr *E
Douglas Gregoreb29d182011-01-05 17:40:24 +00002007 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002008 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002009 return TemplateArgumentLoc(TemplateArgument(E), E);
2010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002011
Eli Friedmanb826a002012-09-26 02:36:12 +00002012 case TemplateArgument::NullPtr: {
2013 Expr *E
2014 = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002015 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002016 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2017 E);
2018 }
2019
Douglas Gregorca4686d2011-01-04 23:35:54 +00002020 case TemplateArgument::Integral: {
2021 Expr *E
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002022 = S.BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002023 return TemplateArgumentLoc(TemplateArgument(E), E);
2024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002025
Douglas Gregor9d802122011-03-02 17:09:35 +00002026 case TemplateArgument::Template:
2027 case TemplateArgument::TemplateExpansion: {
2028 NestedNameSpecifierLocBuilder Builder;
2029 TemplateName Template = Arg.getAsTemplate();
2030 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2031 Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002032 else if (QualifiedTemplateName *QTN =
2033 Template.getAsQualifiedTemplateName())
Douglas Gregor9d802122011-03-02 17:09:35 +00002034 Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2035
2036 if (Arg.getKind() == TemplateArgument::Template)
2037 return TemplateArgumentLoc(Arg,
2038 Builder.getWithLocInContext(S.Context),
2039 Loc);
2040
2041
2042 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2043 Loc, Loc);
2044 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002045
Douglas Gregorca4686d2011-01-04 23:35:54 +00002046 case TemplateArgument::Expression:
2047 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002048
Douglas Gregorca4686d2011-01-04 23:35:54 +00002049 case TemplateArgument::Pack:
2050 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2051 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002052
David Blaikiee4d798f2012-01-20 21:50:17 +00002053 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002054}
2055
2056
2057/// \brief Convert the given deduced template argument and add it to the set of
2058/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002059static bool
2060ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2061 DeducedTemplateArgument Arg,
2062 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002063 TemplateDeductionInfo &Info,
2064 bool InFunctionTemplate,
2065 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002066 // First, for a non-type template parameter type that is
2067 // initialized by a declaration, we need the type of the
2068 // corresponding non-type template parameter.
2069 QualType NTTPType;
2070 if (NonTypeTemplateParmDecl *NTTP =
2071 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2072 NTTPType = NTTP->getType();
2073 if (NTTPType->isDependentType()) {
2074 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2075 Output.data(), Output.size());
2076 NTTPType = S.SubstType(NTTPType,
2077 MultiLevelTemplateArgumentList(TemplateArgs),
2078 NTTP->getLocation(),
2079 NTTP->getDeclName());
2080 if (NTTPType.isNull())
2081 return true;
2082 }
2083 }
2084
2085 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2086 unsigned ArgumentPackIndex) {
2087 // Convert the deduced template argument into a template
2088 // argument that we can check, almost as if the user had written
2089 // the template argument explicitly.
2090 TemplateArgumentLoc ArgLoc =
2091 getTrivialTemplateArgumentLoc(S, Arg, NTTPType, Info.getLocation());
2092
2093 // Check the template argument, converting it as necessary.
2094 return S.CheckTemplateArgument(
2095 Param, ArgLoc, Template, Template->getLocation(),
2096 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2097 InFunctionTemplate
2098 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2099 : Sema::CTAK_Deduced)
2100 : Sema::CTAK_Specified);
2101 };
2102
Douglas Gregorca4686d2011-01-04 23:35:54 +00002103 if (Arg.getKind() == TemplateArgument::Pack) {
2104 // This is a template argument pack, so check each of its arguments against
2105 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002106 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002107 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002108 // When converting the deduced template argument, append it to the
2109 // general output list. We need to do this so that the template argument
2110 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002111 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002112 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002113 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2114 "deduced nested pack");
2115 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002116 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002117
Douglas Gregor51bc5712011-01-05 20:52:18 +00002118 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002119 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121
Richard Smithdf18ee92016-02-03 20:40:30 +00002122 // If the pack is empty, we still need to substitute into the parameter
2123 // itself, in case that substitution fails. For non-type parameters, we did
2124 // this above. For type parameters, no substitution is ever required.
2125 auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param);
2126 if (TTP && PackedArgsBuilder.empty()) {
2127 // Set up a template instantiation context.
2128 LocalInstantiationScope Scope(S);
2129 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2130 TTP, Output,
2131 Template->getSourceRange());
2132 if (Inst.isInvalid())
2133 return true;
2134
2135 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2136 Output.data(), Output.size());
2137 if (!S.SubstDecl(TTP, S.CurContext,
2138 MultiLevelTemplateArgumentList(TemplateArgs)))
2139 return true;
2140 }
Richard Smith37acb792016-02-03 20:15:01 +00002141
Douglas Gregorca4686d2011-01-04 23:35:54 +00002142 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002143 Output.push_back(
2144 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002145 return false;
2146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002147
Richard Smith37acb792016-02-03 20:15:01 +00002148 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002149}
2150
Douglas Gregor684268d2010-04-29 06:21:43 +00002151/// Complete template argument deduction for a class template partial
2152/// specialization.
2153static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002155 ClassTemplatePartialSpecializationDecl *Partial,
2156 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002157 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002158 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002159 // Unevaluated SFINAE context.
2160 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002161 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162
Douglas Gregor684268d2010-04-29 06:21:43 +00002163 Sema::ContextRAII SavedContext(S, Partial);
2164
2165 // C++ [temp.deduct.type]p2:
2166 // [...] or if any template argument remains neither deduced nor
2167 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002168 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002169 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2170 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002171 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002172 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002173 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002174 return Sema::TDK_Incomplete;
2175 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176
Douglas Gregorca4686d2011-01-04 23:35:54 +00002177 // We have deduced this argument, so it still needs to be
2178 // checked and converted.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002179 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002180 Partial, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002181 Builder)) {
2182 Info.Param = makeTemplateParameter(Param);
2183 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2185 Builder.size()));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002186 return Sema::TDK_SubstitutionFailure;
2187 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002189
Douglas Gregor684268d2010-04-29 06:21:43 +00002190 // Form the template argument list from the deduced template arguments.
2191 TemplateArgumentList *DeducedArgumentList
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002192 = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002193 Builder.size());
2194
Douglas Gregor684268d2010-04-29 06:21:43 +00002195 Info.reset(DeducedArgumentList);
2196
2197 // Substitute the deduced template arguments into the template
2198 // arguments of the class template partial specialization, and
2199 // verify that the instantiated template arguments are both valid
2200 // and are equivalent to the template arguments originally provided
2201 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002202 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002203 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002204 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002205 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002206 const TemplateArgumentLoc *PartialTemplateArgs
2207 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002208
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002209 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2210 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002211
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002212 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002213 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2214 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2215 if (ParamIdx >= Partial->getTemplateParameters()->size())
2216 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2217
2218 Decl *Param
2219 = const_cast<NamedDecl *>(
2220 Partial->getTemplateParameters()->getParam(ParamIdx));
2221 Info.Param = makeTemplateParameter(Param);
2222 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2223 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002224 }
2225
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002226 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002227 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002228 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002229 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002230
Douglas Gregorca4686d2011-01-04 23:35:54 +00002231 TemplateParameterList *TemplateParams
2232 = ClassTemplate->getTemplateParameters();
2233 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002234 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002235 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002236 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002237 Info.FirstArg = TemplateArgs[I];
2238 Info.SecondArg = InstArg;
2239 return Sema::TDK_NonDeducedMismatch;
2240 }
2241 }
2242
2243 if (Trap.hasErrorOccurred())
2244 return Sema::TDK_SubstitutionFailure;
2245
2246 return Sema::TDK_Success;
2247}
2248
Douglas Gregor170bc422009-06-12 22:31:52 +00002249/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002250/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002251/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002252Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002253Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002254 const TemplateArgumentList &TemplateArgs,
2255 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002256 if (Partial->isInvalidDecl())
2257 return TDK_Invalid;
2258
Douglas Gregor170bc422009-06-12 22:31:52 +00002259 // C++ [temp.class.spec.match]p2:
2260 // A partial specialization matches a given actual template
2261 // argument list if the template arguments of the partial
2262 // specialization can be deduced from the actual template argument
2263 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002264
2265 // Unevaluated SFINAE context.
2266 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002267 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002268
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002269 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002270 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002271 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002272 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002273 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002274 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002275 TemplateArgs, Info, Deduced))
2276 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002277
Richard Smith80934652012-07-16 01:09:10 +00002278 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002279 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2280 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002281 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002282 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002283
Douglas Gregore1416332009-06-14 08:02:22 +00002284 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002285 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002286
2287 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002288 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002289}
Douglas Gregor91772d12009-06-13 00:26:55 +00002290
Larisse Voufo39a1e502013-08-06 01:03:05 +00002291/// Complete template argument deduction for a variable template partial
2292/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002293/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2294/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2295/// VarTemplate(Partial)SpecializationDecl with a new data
2296/// structure Template(Partial)SpecializationDecl, and
2297/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002298static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2299 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2300 const TemplateArgumentList &TemplateArgs,
2301 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2302 TemplateDeductionInfo &Info) {
2303 // Unevaluated SFINAE context.
2304 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2305 Sema::SFINAETrap Trap(S);
2306
2307 // C++ [temp.deduct.type]p2:
2308 // [...] or if any template argument remains neither deduced nor
2309 // explicitly specified, template argument deduction fails.
2310 SmallVector<TemplateArgument, 4> Builder;
2311 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2312 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2313 NamedDecl *Param = PartialParams->getParam(I);
2314 if (Deduced[I].isNull()) {
2315 Info.Param = makeTemplateParameter(Param);
2316 return Sema::TDK_Incomplete;
2317 }
2318
2319 // We have deduced this argument, so it still needs to be
2320 // checked and converted.
Richard Smith37acb792016-02-03 20:15:01 +00002321 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial,
2322 Info, false, Builder)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002323 Info.Param = makeTemplateParameter(Param);
2324 // FIXME: These template arguments are temporary. Free them!
2325 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2326 Builder.size()));
2327 return Sema::TDK_SubstitutionFailure;
2328 }
2329 }
2330
2331 // Form the template argument list from the deduced template arguments.
2332 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
2333 S.Context, Builder.data(), Builder.size());
2334
2335 Info.reset(DeducedArgumentList);
2336
2337 // Substitute the deduced template arguments into the template
2338 // arguments of the class template partial specialization, and
2339 // verify that the instantiated template arguments are both valid
2340 // and are equivalent to the template arguments originally provided
2341 // to the class template.
2342 LocalInstantiationScope InstScope(S);
2343 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002344 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2345 = Partial->getTemplateArgsAsWritten();
2346 const TemplateArgumentLoc *PartialTemplateArgs
2347 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002348
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002349 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2350 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002351
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002352 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002353 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2354 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2355 if (ParamIdx >= Partial->getTemplateParameters()->size())
2356 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2357
2358 Decl *Param = const_cast<NamedDecl *>(
2359 Partial->getTemplateParameters()->getParam(ParamIdx));
2360 Info.Param = makeTemplateParameter(Param);
2361 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2362 return Sema::TDK_SubstitutionFailure;
2363 }
2364 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2365 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2366 false, ConvertedInstArgs))
2367 return Sema::TDK_SubstitutionFailure;
2368
2369 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2370 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2371 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2372 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2373 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2374 Info.FirstArg = TemplateArgs[I];
2375 Info.SecondArg = InstArg;
2376 return Sema::TDK_NonDeducedMismatch;
2377 }
2378 }
2379
2380 if (Trap.hasErrorOccurred())
2381 return Sema::TDK_SubstitutionFailure;
2382
2383 return Sema::TDK_Success;
2384}
2385
2386/// \brief Perform template argument deduction to determine whether
2387/// the given template arguments match the given variable template
2388/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002389/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2390/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2391/// VarTemplate(Partial)SpecializationDecl with a new data
2392/// structure Template(Partial)SpecializationDecl, and
2393/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002394Sema::TemplateDeductionResult
2395Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2396 const TemplateArgumentList &TemplateArgs,
2397 TemplateDeductionInfo &Info) {
2398 if (Partial->isInvalidDecl())
2399 return TDK_Invalid;
2400
2401 // C++ [temp.class.spec.match]p2:
2402 // A partial specialization matches a given actual template
2403 // argument list if the template arguments of the partial
2404 // specialization can be deduced from the actual template argument
2405 // list (14.8.2).
2406
2407 // Unevaluated SFINAE context.
2408 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2409 SFINAETrap Trap(*this);
2410
2411 SmallVector<DeducedTemplateArgument, 4> Deduced;
2412 Deduced.resize(Partial->getTemplateParameters()->size());
2413 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2414 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2415 TemplateArgs, Info, Deduced))
2416 return Result;
2417
2418 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002419 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2420 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002421 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002422 return TDK_InstantiationDepth;
2423
2424 if (Trap.hasErrorOccurred())
2425 return Sema::TDK_SubstitutionFailure;
2426
2427 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2428 Deduced, Info);
2429}
2430
Douglas Gregorfc516c92009-06-26 23:27:24 +00002431/// \brief Determine whether the given type T is a simple-template-id type.
2432static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002433 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002434 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002435 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002436
Douglas Gregorfc516c92009-06-26 23:27:24 +00002437 return false;
2438}
Douglas Gregor9b146582009-07-08 20:55:45 +00002439
2440/// \brief Substitute the explicitly-provided template arguments into the
2441/// given function template according to C++ [temp.arg.explicit].
2442///
2443/// \param FunctionTemplate the function template into which the explicit
2444/// template arguments will be substituted.
2445///
James Dennett634962f2012-06-14 21:40:34 +00002446/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002447/// arguments.
2448///
Mike Stump11289f42009-09-09 15:08:12 +00002449/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002450/// with the converted and checked explicit template arguments.
2451///
Mike Stump11289f42009-09-09 15:08:12 +00002452/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002453/// parameters.
2454///
2455/// \param FunctionType if non-NULL, the result type of the function template
2456/// will also be instantiated and the pointed-to value will be updated with
2457/// the instantiated function type.
2458///
2459/// \param Info if substitution fails for any reason, this object will be
2460/// populated with more information about the failure.
2461///
2462/// \returns TDK_Success if substitution was successful, or some failure
2463/// condition.
2464Sema::TemplateDeductionResult
2465Sema::SubstituteExplicitTemplateArguments(
2466 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002467 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002468 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2469 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002470 QualType *FunctionType,
2471 TemplateDeductionInfo &Info) {
2472 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2473 TemplateParameterList *TemplateParams
2474 = FunctionTemplate->getTemplateParameters();
2475
John McCall6b51f282009-11-23 01:53:49 +00002476 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002477 // No arguments to substitute; just copy over the parameter types and
2478 // fill in the function type.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002479 for (auto P : Function->params())
2480 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002481
Douglas Gregor9b146582009-07-08 20:55:45 +00002482 if (FunctionType)
2483 *FunctionType = Function->getType();
2484 return TDK_Success;
2485 }
Mike Stump11289f42009-09-09 15:08:12 +00002486
Eli Friedman77dcc722012-02-08 03:07:05 +00002487 // Unevaluated SFINAE context.
2488 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002489 SFINAETrap Trap(*this);
2490
Douglas Gregor9b146582009-07-08 20:55:45 +00002491 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002492 // Template arguments that are present shall be specified in the
2493 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002494 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002495 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002496 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002497
2498 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002499 // explicitly-specified template arguments against this function template,
2500 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002501 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002502 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2503 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002504 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2505 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002506 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002507 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002508
Douglas Gregor9b146582009-07-08 20:55:45 +00002509 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002510 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002511 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002512 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002513 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002514 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002515 if (Index >= TemplateParams->size())
2516 Index = TemplateParams->size() - 1;
2517 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002518 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002519 }
Mike Stump11289f42009-09-09 15:08:12 +00002520
Douglas Gregor9b146582009-07-08 20:55:45 +00002521 // Form the template argument list from the explicitly-specified
2522 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002523 TemplateArgumentList *ExplicitArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002524 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor9b146582009-07-08 20:55:45 +00002525 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002526
John McCall036855a2010-10-12 19:40:14 +00002527 // Template argument deduction and the final substitution should be
2528 // done in the context of the templated declaration. Explicit
2529 // argument substitution, on the other hand, needs to happen in the
2530 // calling context.
2531 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2532
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002533 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002534 // note that the template argument pack is partially substituted and record
2535 // the explicit template arguments. They'll be used as part of deduction
2536 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002537 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2538 const TemplateArgument &Arg = Builder[I];
2539 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002540 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002541 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002542 Arg.pack_begin(),
2543 Arg.pack_size());
2544 break;
2545 }
2546 }
2547
Richard Smith5e580292012-02-10 09:58:53 +00002548 const FunctionProtoType *Proto
2549 = Function->getType()->getAs<FunctionProtoType>();
2550 assert(Proto && "Function template does not have a prototype?");
2551
Richard Smith70b13042015-01-09 01:19:56 +00002552 // Isolate our substituted parameters from our caller.
2553 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2554
Douglas Gregor9b146582009-07-08 20:55:45 +00002555 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002556 // explicitly-specified template arguments. If the function has a trailing
2557 // return type, substitute it after the arguments to ensure we substitute
2558 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002559 if (Proto->hasTrailingReturn()) {
2560 if (SubstParmTypes(Function->getLocation(),
2561 Function->param_begin(), Function->getNumParams(),
2562 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2563 ParamTypes))
2564 return TDK_SubstitutionFailure;
2565 }
2566
Richard Smith5e580292012-02-10 09:58:53 +00002567 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002568 QualType ResultType;
2569 {
2570 // C++11 [expr.prim.general]p3:
2571 // If a declaration declares a member function or member function
2572 // template of a class X, the expression this is a prvalue of type
2573 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2574 // and the end of the function-definition, member-declarator, or
2575 // declarator.
2576 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002577 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002578 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2579 ThisContext = Method->getParent();
2580 ThisTypeQuals = Method->getTypeQualifiers();
2581 }
2582
2583 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002584 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002585
2586 ResultType =
2587 SubstType(Proto->getReturnType(),
2588 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2589 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002590 if (ResultType.isNull() || Trap.hasErrorOccurred())
2591 return TDK_SubstitutionFailure;
2592 }
2593
Richard Smith5e580292012-02-10 09:58:53 +00002594 // Instantiate the types of each of the function parameters given the
2595 // explicitly-specified template arguments if we didn't do so earlier.
2596 if (!Proto->hasTrailingReturn() &&
2597 SubstParmTypes(Function->getLocation(),
2598 Function->param_begin(), Function->getNumParams(),
2599 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2600 ParamTypes))
2601 return TDK_SubstitutionFailure;
2602
Douglas Gregor9b146582009-07-08 20:55:45 +00002603 if (FunctionType) {
Jordan Rose5c382722013-03-08 21:51:21 +00002604 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002605 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002606 Function->getDeclName(),
Jordan Rosea0a86be2013-03-08 22:25:36 +00002607 Proto->getExtProtoInfo());
Douglas Gregor9b146582009-07-08 20:55:45 +00002608 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2609 return TDK_SubstitutionFailure;
2610 }
Mike Stump11289f42009-09-09 15:08:12 +00002611
Douglas Gregor9b146582009-07-08 20:55:45 +00002612 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002613 // Trailing template arguments that can be deduced (14.8.2) may be
2614 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002615 // template arguments can be deduced, they may all be omitted; in this
2616 // case, the empty template argument list <> itself may also be omitted.
2617 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002618 // Take all of the explicitly-specified arguments and put them into
2619 // the set of deduced template arguments. Explicitly-specified
2620 // parameter packs, however, will be set to NULL since the deduction
2621 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002622 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002623 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2624 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2625 if (Arg.getKind() == TemplateArgument::Pack)
2626 Deduced.push_back(DeducedTemplateArgument());
2627 else
2628 Deduced.push_back(Arg);
2629 }
Mike Stump11289f42009-09-09 15:08:12 +00002630
Douglas Gregor9b146582009-07-08 20:55:45 +00002631 return TDK_Success;
2632}
2633
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002634/// \brief Check whether the deduced argument type for a call to a function
2635/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2636static bool
2637CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2638 QualType DeducedA) {
2639 ASTContext &Context = S.Context;
2640
2641 QualType A = OriginalArg.OriginalArgType;
2642 QualType OriginalParamType = OriginalArg.OriginalParamType;
2643
2644 // Check for type equality (top-level cv-qualifiers are ignored).
2645 if (Context.hasSameUnqualifiedType(A, DeducedA))
2646 return false;
2647
2648 // Strip off references on the argument types; they aren't needed for
2649 // the following checks.
2650 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2651 DeducedA = DeducedARef->getPointeeType();
2652 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2653 A = ARef->getPointeeType();
2654
2655 // C++ [temp.deduct.call]p4:
2656 // [...] However, there are three cases that allow a difference:
2657 // - If the original P is a reference type, the deduced A (i.e., the
2658 // type referred to by the reference) can be more cv-qualified than
2659 // the transformed A.
2660 if (const ReferenceType *OriginalParamRef
2661 = OriginalParamType->getAs<ReferenceType>()) {
2662 // We don't want to keep the reference around any more.
2663 OriginalParamType = OriginalParamRef->getPointeeType();
2664
2665 Qualifiers AQuals = A.getQualifiers();
2666 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002667
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002668 // Under Objective-C++ ARC, the deduced type may have implicitly
2669 // been given strong or (when dealing with a const reference)
2670 // unsafe_unretained lifetime. If so, update the original
2671 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002672 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002673 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2674 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2675 (DeducedAQuals.hasConst() &&
2676 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2677 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002678 }
2679
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002680 if (AQuals == DeducedAQuals) {
2681 // Qualifiers match; there's nothing to do.
2682 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002683 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002684 } else {
2685 // Qualifiers are compatible, so have the argument type adopt the
2686 // deduced argument type's qualifiers as if we had performed the
2687 // qualification conversion.
2688 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2689 }
2690 }
2691
2692 // - The transformed A can be another pointer or pointer to member
2693 // type that can be converted to the deduced A via a qualification
2694 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002695 //
2696 // Also allow conversions which merely strip [[noreturn]] from function types
2697 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002698 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002699 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002700 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002701 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002702 (S.IsQualificationConversion(A, DeducedA, false,
2703 ObjCLifetimeConversion) ||
2704 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002705 return false;
2706
2707
2708 // - If P is a class and P has the form simple-template-id, then the
2709 // transformed A can be a derived class of the deduced A. [...]
2710 // [...] Likewise, if P is a pointer to a class of the form
2711 // simple-template-id, the transformed A can be a pointer to a
2712 // derived class pointed to by the deduced A.
2713 if (const PointerType *OriginalParamPtr
2714 = OriginalParamType->getAs<PointerType>()) {
2715 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2716 if (const PointerType *APtr = A->getAs<PointerType>()) {
2717 if (A->getPointeeType()->isRecordType()) {
2718 OriginalParamType = OriginalParamPtr->getPointeeType();
2719 DeducedA = DeducedAPtr->getPointeeType();
2720 A = APtr->getPointeeType();
2721 }
2722 }
2723 }
2724 }
2725
2726 if (Context.hasSameUnqualifiedType(A, DeducedA))
2727 return false;
2728
2729 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002730 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002731 return false;
2732
2733 return true;
2734}
2735
Mike Stump11289f42009-09-09 15:08:12 +00002736/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002737/// checking the deduced template arguments for completeness and forming
2738/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002739///
2740/// \param OriginalCallArgs If non-NULL, the original call arguments against
2741/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002742Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002743Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002744 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002745 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002746 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002747 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002748 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2749 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002750 TemplateParameterList *TemplateParams
2751 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002752
Eli Friedman77dcc722012-02-08 03:07:05 +00002753 // Unevaluated SFINAE context.
2754 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002755 SFINAETrap Trap(*this);
2756
Douglas Gregor9b146582009-07-08 20:55:45 +00002757 // Enter a new template instantiation context while we instantiate the
2758 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002759 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002760 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2761 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002762 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2763 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002764 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002765 return TDK_InstantiationDepth;
2766
John McCalle23b8712010-04-29 01:18:58 +00002767 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002768
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002769 // C++ [temp.deduct.type]p2:
2770 // [...] or if any template argument remains neither deduced nor
2771 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002772 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002773 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2774 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002775
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002776 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002777 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002778 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002779 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002780 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002781 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002782 // We may have had explicitly-specified template arguments for a
2783 // template parameter pack (that may or may not have been extended
2784 // via additional deduced arguments).
2785 if (Param->isParameterPack() && CurrentInstantiationScope) {
2786 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2787 Param) {
2788 // Forget the partially-substituted pack; its substitution is now
2789 // complete.
2790 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2791 }
2792 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002793 continue;
2794 }
Richard Smith37acb792016-02-03 20:15:01 +00002795
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002796 // We have deduced this argument, so it still needs to be
2797 // checked and converted.
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002798 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002799 FunctionTemplate, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002800 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002801 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002802 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2804 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002805 return TDK_SubstitutionFailure;
2806 }
2807
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002808 continue;
2809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002810
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002811 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002812 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002813 // be deduced to an empty sequence of template arguments.
2814 // FIXME: Where did the word "trailing" come from?
2815 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002816 // We may have had explicitly-specified template arguments for this
2817 // template parameter pack. If so, our empty deduction extends the
2818 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2819 const TemplateArgument *ExplicitArgs;
2820 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002821 if (CurrentInstantiationScope &&
2822 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002823 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002824 == Param) {
Benjamin Kramercce63472015-08-05 09:40:22 +00002825 Builder.push_back(TemplateArgument(
2826 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002827
Richard Smithdf18ee92016-02-03 20:40:30 +00002828 // Forget the partially-substituted pack; its substitution is now
Douglas Gregorcaddba92013-01-18 22:27:09 +00002829 // complete.
2830 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2831 } else {
Richard Smithdf18ee92016-02-03 20:40:30 +00002832 // Go through the motions of checking the empty argument pack against
2833 // the parameter pack.
2834 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2835 if (ConvertDeducedTemplateArgument(*this, Param, DeducedPack,
2836 FunctionTemplate, Info, true,
2837 Builder)) {
2838 Info.Param = makeTemplateParameter(Param);
2839 // FIXME: These template arguments are temporary. Free them!
2840 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2841 Builder.size()));
2842 return TDK_SubstitutionFailure;
2843 }
Douglas Gregorcaddba92013-01-18 22:27:09 +00002844 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002845 continue;
2846 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002847
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002849 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002850 TemplateArgumentLoc DefArg
2851 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2852 FunctionTemplate->getLocation(),
2853 FunctionTemplate->getSourceRange().getEnd(),
2854 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002855 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002856
2857 // If there was no default argument, deduction is incomplete.
2858 if (DefArg.getArgument().isNull()) {
2859 Info.Param = makeTemplateParameter(
2860 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002861 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2862 Builder.size()));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002863 if (PartialOverloading) break;
2864
Richard Smithc87b9382013-07-04 01:01:24 +00002865 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002867
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002868 // Check whether we can actually use the default argument.
2869 if (CheckTemplateArgument(Param, DefArg,
2870 FunctionTemplate,
2871 FunctionTemplate->getLocation(),
2872 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002873 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002874 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002875 Info.Param = makeTemplateParameter(
2876 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002877 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002878 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002879 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002880 return TDK_SubstitutionFailure;
2881 }
2882
2883 // If we get here, we successfully used the default template argument.
2884 }
2885
2886 // Form the template argument list from the deduced template arguments.
2887 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002888 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002889 Info.reset(DeducedArgumentList);
2890
Mike Stump11289f42009-09-09 15:08:12 +00002891 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002892 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002893 DeclContext *Owner = FunctionTemplate->getDeclContext();
2894 if (FunctionTemplate->getFriendObjectKind())
2895 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002896 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002897 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002898 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002899 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002900 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002901
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002902 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002903 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002904
Mike Stump11289f42009-09-09 15:08:12 +00002905 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002906 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002907 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2908 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002909 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002910
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002911 // There may have been an error that did not prevent us from constructing a
2912 // declaration. Mark the declaration invalid and return with a substitution
2913 // failure.
2914 if (Trap.hasErrorOccurred()) {
2915 Specialization->setInvalidDecl(true);
2916 return TDK_SubstitutionFailure;
2917 }
2918
Douglas Gregore65aacb2011-06-16 16:50:48 +00002919 if (OriginalCallArgs) {
2920 // C++ [temp.deduct.call]p4:
2921 // In general, the deduction process attempts to find template argument
2922 // values that will make the deduced A identical to A (after the type A
2923 // is transformed as described above). [...]
2924 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2925 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002926 unsigned ParamIdx = OriginalArg.ArgIdx;
2927
2928 if (ParamIdx >= Specialization->getNumParams())
2929 continue;
2930
2931 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002932 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2933 Info.FirstArg = TemplateArgument(DeducedA);
2934 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2935 Info.CallArgIndex = OriginalArg.ArgIdx;
2936 return TDK_DeducedMismatch;
2937 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002938 }
2939 }
2940
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002941 // If we suppressed any diagnostics while performing template argument
2942 // deduction, and if we haven't already instantiated this declaration,
2943 // keep track of these diagnostics. They'll be emitted if this specialization
2944 // is actually used.
2945 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002946 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002947 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2948 if (Pos == SuppressedDiagnostics.end())
2949 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2950 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002951 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002952
Mike Stump11289f42009-09-09 15:08:12 +00002953 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002954}
2955
John McCall8d08b9b2010-08-27 09:08:28 +00002956/// Gets the type of a function for template-argument-deducton
2957/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002958static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002959 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002960 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002961 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002962 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002963 return QualType();
2964
John McCallc1f69982010-02-02 02:21:27 +00002965 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002966 if (Method->isInstance()) {
2967 // An instance method that's referenced in a form that doesn't
2968 // look like a member pointer is just invalid.
2969 if (!R.HasFormOfMemberPointer) return QualType();
2970
Richard Smith2a7d4812013-05-04 07:00:32 +00002971 return S.Context.getMemberPointerType(Fn->getType(),
2972 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002973 }
2974
2975 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002976 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002977}
2978
2979/// Apply the deduction rules for overload sets.
2980///
2981/// \return the null type if this argument should be treated as an
2982/// undeduced context
2983static QualType
2984ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002985 Expr *Arg, QualType ParamType,
2986 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002987
John McCall8d08b9b2010-08-27 09:08:28 +00002988 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00002989
John McCall8d08b9b2010-08-27 09:08:28 +00002990 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00002991
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002992 // C++0x [temp.deduct.call]p4
2993 unsigned TDF = 0;
2994 if (ParamWasReference)
2995 TDF |= TDF_ParamWithReferenceType;
2996 if (R.IsAddressOfOperand)
2997 TDF |= TDF_IgnoreQualifiers;
2998
John McCallc1f69982010-02-02 02:21:27 +00002999 // C++0x [temp.deduct.call]p6:
3000 // When P is a function type, pointer to function type, or pointer
3001 // to member function type:
3002
3003 if (!ParamType->isFunctionType() &&
3004 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003005 !ParamType->isMemberFunctionPointerType()) {
3006 if (Ovl->hasExplicitTemplateArgs()) {
3007 // But we can still look for an explicit specialization.
3008 if (FunctionDecl *ExplicitSpec
3009 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003010 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003011 }
John McCallc1f69982010-02-02 02:21:27 +00003012
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003013 return QualType();
3014 }
3015
3016 // Gather the explicit template arguments, if any.
3017 TemplateArgumentListInfo ExplicitTemplateArgs;
3018 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003019 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003020 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003021 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3022 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003023 NamedDecl *D = (*I)->getUnderlyingDecl();
3024
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003025 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3026 // - If the argument is an overload set containing one or more
3027 // function templates, the parameter is treated as a
3028 // non-deduced context.
3029 if (!Ovl->hasExplicitTemplateArgs())
3030 return QualType();
3031
3032 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003033 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003034 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003035 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3036 Specialization, Info))
3037 continue;
3038
3039 D = Specialization;
3040 }
John McCallc1f69982010-02-02 02:21:27 +00003041
3042 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003043 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003044 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003045
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003046 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003047 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003048 ArgType->isFunctionType())
3049 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050
John McCallc1f69982010-02-02 02:21:27 +00003051 // - If the argument is an overload set (not containing function
3052 // templates), trial argument deduction is attempted using each
3053 // of the members of the set. If deduction succeeds for only one
3054 // of the overload set members, that member is used as the
3055 // argument value for the deduction. If deduction succeeds for
3056 // more than one member of the overload set the parameter is
3057 // treated as a non-deduced context.
3058
3059 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3060 // Type deduction is done independently for each P/A pair, and
3061 // the deduced template argument values are then combined.
3062 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003063 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003064 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003065 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003066 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003067 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3068 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003069 if (Result) continue;
3070 if (!Match.isNull()) return QualType();
3071 Match = ArgType;
3072 }
3073
3074 return Match;
3075}
3076
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003077/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003078/// described in C++ [temp.deduct.call].
3079///
3080/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003081/// argument deduction based on this P/A pair because the argument is an
3082/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003083static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3084 TemplateParameterList *TemplateParams,
3085 QualType &ParamType,
3086 QualType &ArgType,
3087 Expr *Arg,
3088 unsigned &TDF) {
3089 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003090 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003091 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003092 if (ParamType.hasQualifiers())
3093 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003094
3095 // [...] If P is a reference type, the type referred to by P is
3096 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003097 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003098 if (ParamRefType)
3099 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003100
Nathan Sidwell96090022015-01-16 15:20:14 +00003101 // Overload sets usually make this parameter an undeduced context,
3102 // but there are sometimes special circumstances. Typically
3103 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003104 if (ArgType == S.Context.OverloadTy) {
3105 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3106 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003107 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003108 if (ArgType.isNull())
3109 return true;
3110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003111
Douglas Gregor7825bf32011-01-06 22:09:01 +00003112 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003113 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003114 if (ArgType->isIncompleteArrayType()) {
3115 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003116 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003117 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003118
Douglas Gregor7825bf32011-01-06 22:09:01 +00003119 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003120 // If P is an rvalue reference to a cv-unqualified template
3121 // parameter and the argument is an lvalue, the type "lvalue
3122 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003123 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003124 !ParamType.getQualifiers() &&
3125 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003126 Arg->isLValue())
3127 ArgType = S.Context.getLValueReferenceType(ArgType);
3128 } else {
3129 // C++ [temp.deduct.call]p2:
3130 // If P is not a reference type:
3131 // - If A is an array type, the pointer type produced by the
3132 // array-to-pointer standard conversion (4.2) is used in place of
3133 // A for type deduction; otherwise,
3134 if (ArgType->isArrayType())
3135 ArgType = S.Context.getArrayDecayedType(ArgType);
3136 // - If A is a function type, the pointer type produced by the
3137 // function-to-pointer standard conversion (4.3) is used in place
3138 // of A for type deduction; otherwise,
3139 else if (ArgType->isFunctionType())
3140 ArgType = S.Context.getPointerType(ArgType);
3141 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003142 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003143 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003144 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003145 }
3146 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003147
Douglas Gregor7825bf32011-01-06 22:09:01 +00003148 // C++0x [temp.deduct.call]p4:
3149 // In general, the deduction process attempts to find template argument
3150 // values that will make the deduced A identical to A (after the type A
3151 // is transformed as described above). [...]
3152 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153
Douglas Gregor7825bf32011-01-06 22:09:01 +00003154 // - If the original P is a reference type, the deduced A (i.e., the
3155 // type referred to by the reference) can be more cv-qualified than
3156 // the transformed A.
3157 if (ParamRefType)
3158 TDF |= TDF_ParamWithReferenceType;
3159 // - The transformed A can be another pointer or pointer to member
3160 // type that can be converted to the deduced A via a qualification
3161 // conversion (4.4).
3162 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3163 ArgType->isObjCObjectPointerType())
3164 TDF |= TDF_IgnoreQualifiers;
3165 // - If P is a class and P has the form simple-template-id, then the
3166 // transformed A can be a derived class of the deduced A. Likewise,
3167 // if P is a pointer to a class of the form simple-template-id, the
3168 // transformed A can be a pointer to a derived class pointed to by
3169 // the deduced A.
3170 if (isSimpleTemplateIdType(ParamType) ||
3171 (isa<PointerType>(ParamType) &&
3172 isSimpleTemplateIdType(
3173 ParamType->getAs<PointerType>()->getPointeeType())))
3174 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003175
Douglas Gregor7825bf32011-01-06 22:09:01 +00003176 return false;
3177}
3178
Nico Weberc153d242014-07-28 00:02:09 +00003179static bool
3180hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3181 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003182
Hubert Tong3280b332015-06-25 00:25:49 +00003183static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3184 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3185 Expr *Arg, TemplateDeductionInfo &Info,
3186 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3187
3188/// \brief Attempt template argument deduction from an initializer list
3189/// deemed to be an argument in a function call.
3190static bool
3191DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3192 QualType AdjustedParamType, InitListExpr *ILE,
3193 TemplateDeductionInfo &Info,
3194 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3195 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003196
3197 // [temp.deduct.call] p1 (post CWG-1591)
3198 // If removing references and cv-qualifiers from P gives
3199 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3200 // non-empty initializer list (8.5.4), then deduction is performed instead for
3201 // each element of the initializer list, taking P0 as a function template
3202 // parameter type and the initializer element as its argument, and in the
3203 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3204 // length of the initializer list. Otherwise, an initializer list argument
3205 // causes the parameter to be considered a non-deduced context
3206
3207 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3208
3209 const bool IsDependentSizedArray =
3210 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3211
Faisal Validd76cc12015-12-10 12:29:11 +00003212 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003213
3214 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3215 S.isStdInitializerList(AdjustedParamType, &ElTy);
3216
3217 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003218 return false;
3219
3220 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003221 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3222 // deduce against the 'T' in T[N].
3223 if (ElTy.isNull()) {
3224 assert(!IsSTDList);
3225 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003226 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003227 // Deduction only needs to be done for dependent types.
3228 if (ElTy->isDependentType()) {
3229 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003230 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3231 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003232 return true;
3233 }
3234 }
3235 if (IsDependentSizedArray) {
3236 const DependentSizedArrayType *ArrTy =
3237 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3238 // Determine the array bound is something we can deduce.
3239 if (NonTypeTemplateParmDecl *NTTP =
3240 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3241 // We can perform template argument deduction for the given non-type
3242 // template parameter.
3243 assert(NTTP->getDepth() == 0 &&
3244 "Cannot deduce non-type template argument at depth > 0");
3245 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3246 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003247
Faisal Valif6dfdb32015-12-10 05:36:39 +00003248 Result = DeduceNonTypeTemplateArgument(
3249 S, NTTP, llvm::APSInt(Size), NTTP->getType(),
3250 /*ArrayBound=*/true, Info, Deduced);
3251 }
3252 }
Hubert Tong3280b332015-06-25 00:25:49 +00003253 return true;
3254}
3255
Sebastian Redl19181662012-03-15 21:40:51 +00003256/// \brief Perform template argument deduction by matching a parameter type
3257/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003258/// an initializer list that was originally matched against a parameter
3259/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003260static Sema::TemplateDeductionResult
3261DeduceTemplateArgumentByListElement(Sema &S,
3262 TemplateParameterList *TemplateParams,
3263 QualType ParamType, Expr *Arg,
3264 TemplateDeductionInfo &Info,
3265 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3266 unsigned TDF) {
3267 // Handle the case where an init list contains another init list as the
3268 // element.
3269 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003270 Sema::TemplateDeductionResult Result;
3271 if (!DeduceFromInitializerList(S, TemplateParams,
3272 ParamType.getNonReferenceType(), ILE, Info,
3273 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003274 return Sema::TDK_Success; // Just ignore this expression.
3275
Hubert Tong3280b332015-06-25 00:25:49 +00003276 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003277 }
3278
3279 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003280 QualType ArgType = Arg->getType();
3281 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003282 ArgType, Arg, TDF)) {
3283 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003284 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003285 }
Sebastian Redl19181662012-03-15 21:40:51 +00003286 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003287 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003288}
3289
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003290/// \brief Perform template argument deduction from a function call
3291/// (C++ [temp.deduct.call]).
3292///
3293/// \param FunctionTemplate the function template for which we are performing
3294/// template argument deduction.
3295///
James Dennett18348b62012-06-22 08:52:37 +00003296/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003297/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003298///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003299/// \param Args the function call arguments
3300///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003301/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003302/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003303/// template argument deduction.
3304///
3305/// \param Info the argument will be updated to provide additional information
3306/// about template argument deduction.
3307///
3308/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003309Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3310 FunctionTemplateDecl *FunctionTemplate,
3311 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003312 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3313 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003314 if (FunctionTemplate->isInvalidDecl())
3315 return TDK_Invalid;
3316
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003317 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003318 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003319
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003320 // C++ [temp.deduct.call]p1:
3321 // Template argument deduction is done by comparing each function template
3322 // parameter type (call it P) with the type of the corresponding argument
3323 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003324 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003325 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003326 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003327 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003328 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003329 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003330 if (Proto->isTemplateVariadic())
3331 /* Do nothing */;
3332 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003333 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003335 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003336 }
Mike Stump11289f42009-09-09 15:08:12 +00003337
Douglas Gregor89026b52009-06-30 23:57:56 +00003338 // The types of the parameters from which we will perform template argument
3339 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003340 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003341 TemplateParameterList *TemplateParams
3342 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003343 SmallVector<DeducedTemplateArgument, 4> Deduced;
3344 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003345 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003346 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003347 TemplateDeductionResult Result =
3348 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003349 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003350 Deduced,
3351 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003352 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003353 Info);
3354 if (Result)
3355 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003356
3357 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003358 } else {
3359 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003360 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003361 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3362 }
Mike Stump11289f42009-09-09 15:08:12 +00003363
Douglas Gregor89026b52009-06-30 23:57:56 +00003364 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003365 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003366 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003367 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003368 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3369 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003370 QualType OrigParamType = ParamTypes[ParamIdx];
3371 QualType ParamType = OrigParamType;
3372
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003373 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003374 = dyn_cast<PackExpansionType>(ParamType);
3375 if (!ParamExpansion) {
3376 // Simple case: matching a function parameter to a function argument.
3377 if (ArgIdx >= CheckArgs)
3378 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003379
Douglas Gregor7825bf32011-01-06 22:09:01 +00003380 Expr *Arg = Args[ArgIdx++];
3381 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003382
Douglas Gregor7825bf32011-01-06 22:09:01 +00003383 unsigned TDF = 0;
3384 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3385 ParamType, ArgType, Arg,
3386 TDF))
3387 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003388
Douglas Gregor0c83c812011-10-09 22:06:46 +00003389 // If we have nothing to deduce, we're done.
3390 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3391 continue;
3392
Sebastian Redl43144e72012-01-17 22:49:58 +00003393 // If the argument is an initializer list ...
3394 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003395 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003396 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003397 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3398 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003399 continue;
3400
Hubert Tong3280b332015-06-25 00:25:49 +00003401 if (Result)
3402 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003403 // Don't track the argument type, since an initializer list has none.
3404 continue;
3405 }
3406
Douglas Gregore65aacb2011-06-16 16:50:48 +00003407 // Keep track of the argument type and corresponding parameter index,
3408 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003409 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3410 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003411
Douglas Gregor7825bf32011-01-06 22:09:01 +00003412 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003413 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3414 ParamType, ArgType,
3415 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003416 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003417
Douglas Gregor7825bf32011-01-06 22:09:01 +00003418 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
Douglas Gregor7825bf32011-01-06 22:09:01 +00003421 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422 // For a function parameter pack that occurs at the end of the
3423 // parameter-declaration-list, the type A of each remaining argument of
3424 // the call is compared with the type P of the declarator-id of the
3425 // function parameter pack. Each comparison deduces template arguments
3426 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003427 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003429 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003430 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003431 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432
Douglas Gregor7825bf32011-01-06 22:09:01 +00003433 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003434 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3435 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003436
Douglas Gregor7825bf32011-01-06 22:09:01 +00003437 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003438 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003439 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440
Douglas Gregore65aacb2011-06-16 16:50:48 +00003441 QualType OrigParamType = ParamPattern;
3442 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003443 Expr *Arg = Args[ArgIdx];
3444 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003445
Douglas Gregor7825bf32011-01-06 22:09:01 +00003446 unsigned TDF = 0;
3447 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3448 ParamType, ArgType, Arg,
3449 TDF)) {
3450 // We can't actually perform any deduction for this argument, so stop
3451 // deduction at this point.
3452 ++ArgIdx;
3453 break;
3454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455
Sebastian Redl43144e72012-01-17 22:49:58 +00003456 // As above, initializer lists need special handling.
3457 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003458 TemplateDeductionResult Result;
3459 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3460 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003461 ++ArgIdx;
3462 break;
3463 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003464
Hubert Tong3280b332015-06-25 00:25:49 +00003465 if (Result)
3466 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003467 } else {
3468
3469 // Keep track of the argument type and corresponding argument index,
3470 // so we can check for compatibility between the deduced A and A.
3471 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3472 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3473 ArgType));
3474
3475 if (TemplateDeductionResult Result
3476 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3477 ParamType, ArgType, Info,
3478 Deduced, TDF))
3479 return Result;
3480 }
Mike Stump11289f42009-09-09 15:08:12 +00003481
Richard Smith0a80d572014-05-29 01:12:14 +00003482 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003483 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484
Douglas Gregor7825bf32011-01-06 22:09:01 +00003485 // Build argument packs for each of the parameter packs expanded by this
3486 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003487 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003489
Douglas Gregor7825bf32011-01-06 22:09:01 +00003490 // After we've matching against a parameter pack, we're done.
3491 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003492 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003493
Mike Stump11289f42009-09-09 15:08:12 +00003494 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003495 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003496 Info, &OriginalCallArgs,
3497 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003498}
3499
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003500QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3501 QualType FunctionType) {
3502 if (ArgFunctionType.isNull())
3503 return ArgFunctionType;
3504
3505 const FunctionProtoType *FunctionTypeP =
3506 FunctionType->castAs<FunctionProtoType>();
3507 CallingConv CC = FunctionTypeP->getCallConv();
3508 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3509 const FunctionProtoType *ArgFunctionTypeP =
3510 ArgFunctionType->getAs<FunctionProtoType>();
3511 if (ArgFunctionTypeP->getCallConv() == CC &&
3512 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3513 return ArgFunctionType;
3514
3515 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3516 EI = EI.withNoReturn(NoReturn);
3517 ArgFunctionTypeP =
3518 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3519 return QualType(ArgFunctionTypeP, 0);
3520}
3521
Douglas Gregor9b146582009-07-08 20:55:45 +00003522/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003523/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3524/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003525///
3526/// \param FunctionTemplate the function template for which we are performing
3527/// template argument deduction.
3528///
James Dennett18348b62012-06-22 08:52:37 +00003529/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003530/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003531///
3532/// \param ArgFunctionType the function type that will be used as the
3533/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003534/// function template's function type. This type may be NULL, if there is no
3535/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003536///
3537/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003538/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003539/// template argument deduction.
3540///
3541/// \param Info the argument will be updated to provide additional information
3542/// about template argument deduction.
3543///
3544/// \returns the result of template argument deduction.
3545Sema::TemplateDeductionResult
3546Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003547 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003548 QualType ArgFunctionType,
3549 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003550 TemplateDeductionInfo &Info,
3551 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003552 if (FunctionTemplate->isInvalidDecl())
3553 return TDK_Invalid;
3554
Douglas Gregor9b146582009-07-08 20:55:45 +00003555 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3556 TemplateParameterList *TemplateParams
3557 = FunctionTemplate->getTemplateParameters();
3558 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003559 if (!InOverloadResolution)
3560 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003561
Douglas Gregor9b146582009-07-08 20:55:45 +00003562 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003563 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003564 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003565 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003566 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003567 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003568 if (TemplateDeductionResult Result
3569 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003570 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003571 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003572 &FunctionType, Info))
3573 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003574
3575 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003576 }
3577
Eli Friedman77dcc722012-02-08 03:07:05 +00003578 // Unevaluated SFINAE context.
3579 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003580 SFINAETrap Trap(*this);
3581
John McCallc1f69982010-02-02 02:21:27 +00003582 Deduced.resize(TemplateParams->size());
3583
Richard Smith2a7d4812013-05-04 07:00:32 +00003584 // If the function has a deduced return type, substitute it for a dependent
3585 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003586 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003587 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003588 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003589 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003590 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003591 }
3592
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003593 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003594 unsigned TDF = TDF_TopLevelParameterTypeList;
3595 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003596 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003597 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003598 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003599 FunctionType, ArgFunctionType,
3600 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003601 return Result;
3602 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003603
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003605 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3606 NumExplicitlySpecified,
3607 Specialization, Info))
3608 return Result;
3609
Richard Smith2a7d4812013-05-04 07:00:32 +00003610 // If the function has a deduced return type, deduce it now, so we can check
3611 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003612 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003613 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003614 DeduceReturnType(Specialization, Info.getLocation(), false))
3615 return TDK_MiscellaneousDeductionFailure;
3616
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003617 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003618 // specialization with respect to arguments of compatible pointer to function
3619 // types, template argument deduction fails.
3620 if (!ArgFunctionType.isNull()) {
3621 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3622 Context.getCanonicalType(Specialization->getType()),
3623 Context.getCanonicalType(ArgFunctionType)))
3624 return TDK_MiscellaneousDeductionFailure;
3625 else if(!InOverloadResolution &&
3626 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3627 return TDK_MiscellaneousDeductionFailure;
3628 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003629
3630 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003631}
3632
Faisal Vali850da1a2013-09-29 17:08:32 +00003633/// \brief Given a function declaration (e.g. a generic lambda conversion
3634/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003635/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3636/// to replace 'auto' with and not the actual result type you want
3637/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003638static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003639SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003640 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003641 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003642 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003643 assert(AutoResultType->getContainedAutoType());
3644 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003645 TypeToReplaceAutoWith);
3646 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3647}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003648
3649/// \brief Given a specialized conversion operator of a generic lambda
3650/// create the corresponding specializations of the call operator and
3651/// the static-invoker. If the return type of the call operator is auto,
3652/// deduce its return type and check if that matches the
3653/// return type of the destination function ptr.
3654
3655static inline Sema::TemplateDeductionResult
3656SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3657 CXXConversionDecl *ConversionSpecialized,
3658 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3659 QualType ReturnTypeOfDestFunctionPtr,
3660 TemplateDeductionInfo &TDInfo,
3661 Sema &S) {
3662
3663 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3664 assert(LambdaClass && LambdaClass->isGenericLambda());
3665
3666 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003667 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003668 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3669 CallOpResultType->getContainedAutoType();
3670
3671 FunctionTemplateDecl *CallOpTemplate =
3672 CallOpGeneric->getDescribedFunctionTemplate();
3673
Craig Topperc3ec1492014-05-26 06:22:03 +00003674 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003675 // Use the deduced arguments of the conversion function, to specialize our
3676 // generic lambda's call operator.
3677 if (Sema::TemplateDeductionResult Result
3678 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3679 DeducedArguments,
3680 0, CallOpSpecialized, TDInfo))
3681 return Result;
3682
3683 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003684 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3685 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003686 S.DeduceReturnType(CallOpSpecialized,
3687 CallOpSpecialized->getPointOfInstantiation(),
3688 /*Diagnose*/ true);
3689
3690 // Check to see if the return type of the destination ptr-to-function
3691 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003692 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003693 ReturnTypeOfDestFunctionPtr))
3694 return Sema::TDK_NonDeducedMismatch;
3695 // Since we have succeeded in matching the source and destination
3696 // ptr-to-functions (now including return type), and have successfully
3697 // specialized our corresponding call operator, we are ready to
3698 // specialize the static invoker with the deduced arguments of our
3699 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003700 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003701 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3702 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3703
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003704#ifndef NDEBUG
3705 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3706#endif
3707 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003708 InvokerSpecialized, TDInfo);
3709 assert(Result == Sema::TDK_Success &&
3710 "If the call operator succeeded so should the invoker!");
3711 // Set the result type to match the corresponding call operator
3712 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003713 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3714 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003715 // Be sure to get the type to replace 'auto' with and not
3716 // the full result type of the call op specialization
3717 // to substitute into the 'auto' of the invoker and conversion
3718 // function.
3719 // For e.g.
3720 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3721 // We don't want to subst 'int*' into 'auto' to get int**.
3722
Alp Toker314cc812014-01-25 16:55:45 +00003723 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3724 ->getContainedAutoType()
3725 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003726 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3727 TypeToReplaceAutoWith, S);
3728 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3729 TypeToReplaceAutoWith, S);
3730 }
3731
3732 // Ensure that static invoker doesn't have a const qualifier.
3733 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3734 // do not use the CallOperator's TypeSourceInfo which allows
3735 // the const qualifier to leak through.
3736 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3737 getType().getTypePtr()->castAs<FunctionProtoType>();
3738 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3739 EPI.TypeQuals = 0;
3740 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003741 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003742 return Sema::TDK_Success;
3743}
Douglas Gregor05155d82009-08-21 23:19:43 +00003744/// \brief Deduce template arguments for a templated conversion
3745/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3746/// conversion function template specialization.
3747Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003748Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003749 QualType ToType,
3750 CXXConversionDecl *&Specialization,
3751 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003752 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003753 return TDK_Invalid;
3754
Faisal Vali2b3a3012013-10-24 23:40:02 +00003755 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003756 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3757
Faisal Vali2b3a3012013-10-24 23:40:02 +00003758 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003759
3760 // Canonicalize the types for deduction.
3761 QualType P = Context.getCanonicalType(FromType);
3762 QualType A = Context.getCanonicalType(ToType);
3763
Douglas Gregord99609a2011-03-06 09:03:20 +00003764 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003765 // If P is a reference type, the type referred to by P is used for
3766 // type deduction.
3767 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3768 P = PRef->getPointeeType();
3769
Douglas Gregord99609a2011-03-06 09:03:20 +00003770 // C++0x [temp.deduct.conv]p4:
3771 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003772 // for type deduction.
3773 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003774 A = ARef->getPointeeType().getUnqualifiedType();
3775 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003776 //
Mike Stump11289f42009-09-09 15:08:12 +00003777 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003778 else {
3779 assert(!A->isReferenceType() && "Reference types were handled above");
3780
3781 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003782 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003783 // of P for type deduction; otherwise,
3784 if (P->isArrayType())
3785 P = Context.getArrayDecayedType(P);
3786 // - If P is a function type, the pointer type produced by the
3787 // function-to-pointer standard conversion (4.3) is used in
3788 // place of P for type deduction; otherwise,
3789 else if (P->isFunctionType())
3790 P = Context.getPointerType(P);
3791 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003792 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003793 else
3794 P = P.getUnqualifiedType();
3795
Douglas Gregord99609a2011-03-06 09:03:20 +00003796 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003797 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003798 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003799 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003800 A = A.getUnqualifiedType();
3801 }
3802
Eli Friedman77dcc722012-02-08 03:07:05 +00003803 // Unevaluated SFINAE context.
3804 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003805 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003806
3807 // C++ [temp.deduct.conv]p1:
3808 // Template argument deduction is done by comparing the return
3809 // type of the template conversion function (call it P) with the
3810 // type that is required as the result of the conversion (call it
3811 // A) as described in 14.8.2.4.
3812 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003813 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003814 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003815 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003816
3817 // C++0x [temp.deduct.conv]p4:
3818 // In general, the deduction process attempts to find template
3819 // argument values that will make the deduced A identical to
3820 // A. However, there are two cases that allow a difference:
3821 unsigned TDF = 0;
3822 // - If the original A is a reference type, A can be more
3823 // cv-qualified than the deduced A (i.e., the type referred to
3824 // by the reference)
3825 if (ToType->isReferenceType())
3826 TDF |= TDF_ParamWithReferenceType;
3827 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003828 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003829 // conversion.
3830 //
3831 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3832 // both P and A are pointers or member pointers. In this case, we
3833 // just ignore cv-qualifiers completely).
3834 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003835 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003836 TDF |= TDF_IgnoreQualifiers;
3837 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003838 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3839 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003840 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003841
3842 // Create an Instantiation Scope for finalizing the operator.
3843 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003844 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003845 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003846 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003847 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3848 ConversionSpecialized, Info);
3849 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3850
3851 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003852 // to a ptr-to-function, use the deduced arguments from the conversion
3853 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003854 // e.g., int (*fp)(int) = [](auto a) { return a; };
3855 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3856
3857 // Get the return type of the destination ptr-to-function we are converting
3858 // to. This is necessary for matching the lambda call operator's return
3859 // type to that of the destination ptr-to-function's return type.
3860 assert(A->isPointerType() &&
3861 "Can only convert from lambda to ptr-to-function");
3862 const FunctionType *ToFunType =
3863 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003864 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3865
Faisal Vali2b3a3012013-10-24 23:40:02 +00003866 // Create the corresponding specializations of the call operator and
3867 // the static-invoker; and if the return type is auto,
3868 // deduce the return type and check if it matches the
3869 // DestFunctionPtrReturnType.
3870 // For instance:
3871 // auto L = [](auto a) { return f(a); };
3872 // int (*fp)(int) = L;
3873 // char (*fp2)(int) = L; <-- Not OK.
3874
3875 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3876 Specialization, Deduced, DestFunctionPtrReturnType,
3877 Info, *this);
3878 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003879 return Result;
3880}
3881
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003882/// \brief Deduce template arguments for a function template when there is
3883/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3884///
3885/// \param FunctionTemplate the function template for which we are performing
3886/// template argument deduction.
3887///
James Dennett18348b62012-06-22 08:52:37 +00003888/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003889/// arguments.
3890///
3891/// \param Specialization if template argument deduction was successful,
3892/// this will be set to the function template specialization produced by
3893/// template argument deduction.
3894///
3895/// \param Info the argument will be updated to provide additional information
3896/// about template argument deduction.
3897///
3898/// \returns the result of template argument deduction.
3899Sema::TemplateDeductionResult
3900Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003901 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003902 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003903 TemplateDeductionInfo &Info,
3904 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003905 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003906 QualType(), Specialization, Info,
3907 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003908}
3909
Richard Smith30482bc2011-02-20 03:19:35 +00003910namespace {
3911 /// Substitute the 'auto' type specifier within a type for a given replacement
3912 /// type.
3913 class SubstituteAutoTransform :
3914 public TreeTransform<SubstituteAutoTransform> {
3915 QualType Replacement;
3916 public:
Nico Weberc153d242014-07-28 00:02:09 +00003917 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3918 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3919 Replacement(Replacement) {}
3920
Richard Smith30482bc2011-02-20 03:19:35 +00003921 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3922 // If we're building the type pattern to deduce against, don't wrap the
3923 // substituted type in an AutoType. Certain template deduction rules
3924 // apply only when a template type parameter appears directly (and not if
3925 // the parameter is found through desugaring). For instance:
3926 // auto &&lref = lvalue;
3927 // must transform into "rvalue reference to T" not "rvalue reference to
3928 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003929 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003930 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003931 TemplateTypeParmTypeLoc NewTL =
3932 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003933 NewTL.setNameLoc(TL.getNameLoc());
3934 return Result;
3935 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003936 bool Dependent =
3937 !Replacement.isNull() && Replacement->isDependentType();
3938 QualType Result =
3939 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00003940 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003941 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003942 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3943 NewTL.setNameLoc(TL.getNameLoc());
3944 return Result;
3945 }
3946 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003947
3948 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3949 // Lambdas never need to be transformed.
3950 return E;
3951 }
Richard Smith061f1e22013-04-30 21:23:01 +00003952
Richard Smith2a7d4812013-05-04 07:00:32 +00003953 QualType Apply(TypeLoc TL) {
3954 // Create some scratch storage for the transformed type locations.
3955 // FIXME: We're just going to throw this information away. Don't build it.
3956 TypeLocBuilder TLB;
3957 TLB.reserve(TL.getFullDataSize());
3958 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003959 }
Richard Smith30482bc2011-02-20 03:19:35 +00003960 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003961}
Richard Smith30482bc2011-02-20 03:19:35 +00003962
Richard Smith2a7d4812013-05-04 07:00:32 +00003963Sema::DeduceAutoResult
3964Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3965 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3966}
3967
Richard Smith061f1e22013-04-30 21:23:01 +00003968/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003969///
3970/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003971/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003972/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003973/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003974Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003975Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003976 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003977 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3978 if (NonPlaceholder.isInvalid())
3979 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003980 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003981 }
3982
Richard Smith2a7d4812013-05-04 07:00:32 +00003983 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003984 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003985 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003986 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00003987 }
3988
Richard Smith74aeef52013-04-26 16:15:35 +00003989 // If this is a 'decltype(auto)' specifier, do the decltype dance.
3990 // Since 'decltype(auto)' can only occur at the top of the type, we
3991 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00003992 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00003993 if (AT->isDecltypeAuto()) {
3994 if (isa<InitListExpr>(Init)) {
3995 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
3996 return DAR_FailedAlreadyDiagnosed;
3997 }
3998
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00003999 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004000 if (Deduced.isNull())
4001 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004002 // FIXME: Support a non-canonical deduced type for 'auto'.
4003 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004004 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004005 if (Result.isNull())
4006 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004007 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004008 } else if (!getLangOpts().CPlusPlus) {
4009 if (isa<InitListExpr>(Init)) {
4010 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4011 return DAR_FailedAlreadyDiagnosed;
4012 }
Richard Smith74aeef52013-04-26 16:15:35 +00004013 }
4014 }
4015
Richard Smith30482bc2011-02-20 03:19:35 +00004016 SourceLocation Loc = Init->getExprLoc();
4017
4018 LocalInstantiationScope InstScope(*this);
4019
4020 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004021 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004022 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4023 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004024 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4025 NamedDecl *TemplParamPtr = TemplParam;
James Y Knight7a22b242015-08-06 20:26:32 +00004026 FixedSizeTemplateParameterListStorage<1> TemplateParamsSt(
David Majnemer902f8c62015-12-27 07:16:27 +00004027 Loc, Loc, TemplParamPtr, Loc);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004028
Richard Smith061f1e22013-04-30 21:23:01 +00004029 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4030 assert(!FuncParam.isNull() &&
4031 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004032
4033 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004034 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004035 Deduced.resize(1);
4036 QualType InitType = Init->getType();
4037 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004038
Craig Toppere6706e42012-09-19 02:26:47 +00004039 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004040
Richard Smith74801c82012-07-08 04:13:07 +00004041 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004042 if (InitList) {
4043 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004044 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4045 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004046 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004047 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004048 }
4049 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004050 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4051 Diag(Loc, diag::err_auto_bitfield);
4052 return DAR_FailedAlreadyDiagnosed;
4053 }
4054
James Y Knight7a22b242015-08-06 20:26:32 +00004055 if (AdjustFunctionParmAndArgTypesForDeduction(
4056 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004057 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004058
James Y Knight7a22b242015-08-06 20:26:32 +00004059 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4060 FuncParam, InitType, Info, Deduced,
4061 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004062 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004063 }
Richard Smith30482bc2011-02-20 03:19:35 +00004064
Eli Friedmane4310952012-11-06 23:56:42 +00004065 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004066 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004067
Eli Friedmane4310952012-11-06 23:56:42 +00004068 QualType DeducedType = Deduced[0].getAsType();
4069
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004070 if (InitList) {
4071 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4072 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004073 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004074 }
4075
Richard Smith061f1e22013-04-30 21:23:01 +00004076 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004077 if (Result.isNull())
4078 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004079
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004080 // Check that the deduced argument type is compatible with the original
4081 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004082 if (!InitList && !Result.isNull() &&
4083 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004084 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004085 Result)) {
4086 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004087 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004088 }
4089
Sebastian Redl09edce02012-01-23 22:09:39 +00004090 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004091}
4092
Faisal Vali2b391ab2013-09-26 19:54:12 +00004093QualType Sema::SubstAutoType(QualType TypeWithAuto,
4094 QualType TypeToReplaceAuto) {
4095 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4096 TransformType(TypeWithAuto);
4097}
4098
4099TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4100 QualType TypeToReplaceAuto) {
4101 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4102 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004103}
4104
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004105void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4106 if (isa<InitListExpr>(Init))
4107 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004108 VDecl->isInitCapture()
4109 ? diag::err_init_capture_deduction_failure_from_init_list
4110 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004111 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4112 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004113 Diag(VDecl->getLocation(),
4114 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4115 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004116 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4117 << Init->getSourceRange();
4118}
4119
Richard Smith2a7d4812013-05-04 07:00:32 +00004120bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4121 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004122 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004123
4124 if (FD->getTemplateInstantiationPattern())
4125 InstantiateFunctionDefinition(Loc, FD);
4126
Alp Toker314cc812014-01-25 16:55:45 +00004127 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004128 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4129 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4130 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4131 }
4132
4133 return StillUndeduced;
4134}
4135
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004136static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004137MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004138 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004139 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004140 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141
4142/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004143static void
4144AddImplicitObjectParameterType(ASTContext &Context,
4145 CXXMethodDecl *Method,
4146 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004147 // C++11 [temp.func.order]p3:
4148 // [...] The new parameter is of type "reference to cv A," where cv are
4149 // the cv-qualifiers of the function template (if any) and A is
4150 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004151 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004152 // The standard doesn't say explicitly, but we pick the appropriate kind of
4153 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004154 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4155 ArgTy = Context.getQualifiedType(ArgTy,
4156 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004157 if (Method->getRefQualifier() == RQ_RValue)
4158 ArgTy = Context.getRValueReferenceType(ArgTy);
4159 else
4160 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004161 ArgTypes.push_back(ArgTy);
4162}
4163
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004164/// \brief Determine whether the function template \p FT1 is at least as
4165/// specialized as \p FT2.
4166static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004167 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004168 FunctionTemplateDecl *FT1,
4169 FunctionTemplateDecl *FT2,
4170 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004171 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004172 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004174 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4175 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004177 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4178 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004179 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004180 Deduced.resize(TemplateParams->size());
4181
4182 // C++0x [temp.deduct.partial]p3:
4183 // The types used to determine the ordering depend on the context in which
4184 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004185 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004186 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004187 switch (TPOC) {
4188 case TPOC_Call: {
4189 // - In the context of a function call, the function parameter types are
4190 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004191 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4192 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004193
Eli Friedman3b5774a2012-09-19 23:27:04 +00004194 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004195 // [...] If only one of the function templates is a non-static
4196 // member, that function template is considered to have a new
4197 // first parameter inserted in its function parameter list. The
4198 // new parameter is of type "reference to cv A," where cv are
4199 // the cv-qualifiers of the function template (if any) and A is
4200 // the class of which the function template is a member.
4201 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004202 // Note that we interpret this to mean "if one of the function
4203 // templates is a non-static member and the other is a non-member";
4204 // otherwise, the ordering rules for static functions against non-static
4205 // functions don't make any sense.
4206 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004207 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4208 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004209 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004210
Richard Smithe5b52202013-09-11 00:52:39 +00004211 unsigned NumComparedArguments = NumCallArguments1;
4212
4213 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004214 // Compare 'this' from Method1 against first parameter from Method2.
4215 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4216 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004217 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004218 // Compare 'this' from Method2 against first parameter from Method1.
4219 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004220 }
4221
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004222 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004223 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004224 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004225 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226
Douglas Gregorb837ea42011-01-11 17:34:58 +00004227 // C++ [temp.func.order]p5:
4228 // The presence of unused ellipsis and default arguments has no effect on
4229 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004230 if (Args1.size() > NumComparedArguments)
4231 Args1.resize(NumComparedArguments);
4232 if (Args2.size() > NumComparedArguments)
4233 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004234 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4235 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004236 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004237 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004239 break;
4240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004241
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004242 case TPOC_Conversion:
4243 // - In the context of a call to a conversion operator, the return types
4244 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004245 if (DeduceTemplateArgumentsByTypeMatch(
4246 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4247 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004248 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004249 return false;
4250 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004251
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004252 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004253 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004254 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004255 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4256 FD2->getType(), FD1->getType(),
4257 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004258 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004259 return false;
4260 break;
4261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004263 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004264 // In most cases, all template parameters must have values in order for
4265 // deduction to succeed, but for partial ordering purposes a template
4266 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004267 // types being used for partial ordering. [ Note: a template parameter used
4268 // in a non-deduced context is considered used. -end note]
4269 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4270 for (; ArgIdx != NumArgs; ++ArgIdx)
4271 if (Deduced[ArgIdx].isNull())
4272 break;
4273
4274 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004276 // as FT2.
4277 return true;
4278 }
4279
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004280 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004281 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004282 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004283 case TPOC_Call:
4284 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4285 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004286 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004287 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004288 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004289
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004290 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004291 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4292 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004293 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004295 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004296 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004297 TemplateParams->getDepth(),
4298 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004299 break;
4300 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004302 for (; ArgIdx != NumArgs; ++ArgIdx)
4303 // If this argument had no value deduced but was used in one of the types
4304 // used for partial ordering, then deduction fails.
4305 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4306 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004307
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004308 return true;
4309}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310
Douglas Gregorcef1a032011-01-16 16:03:23 +00004311/// \brief Determine whether this a function template whose parameter-type-list
4312/// ends with a function parameter pack.
4313static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4314 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4315 unsigned NumParams = Function->getNumParams();
4316 if (NumParams == 0)
4317 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318
Douglas Gregorcef1a032011-01-16 16:03:23 +00004319 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4320 if (!Last->isParameterPack())
4321 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322
Douglas Gregorcef1a032011-01-16 16:03:23 +00004323 // Make sure that no previous parameter is a parameter pack.
4324 while (--NumParams > 0) {
4325 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4326 return false;
4327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328
Douglas Gregorcef1a032011-01-16 16:03:23 +00004329 return true;
4330}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331
Douglas Gregorbe999392009-09-15 16:23:51 +00004332/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004333/// to the rules of function template partial ordering (C++ [temp.func.order]).
4334///
4335/// \param FT1 the first function template
4336///
4337/// \param FT2 the second function template
4338///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004339/// \param TPOC the context in which we are performing partial ordering of
4340/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004341///
Richard Smithe5b52202013-09-11 00:52:39 +00004342/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4343/// only when \c TPOC is \c TPOC_Call.
4344///
4345/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4346/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004347///
Douglas Gregorbe999392009-09-15 16:23:51 +00004348/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004349/// template is more specialized, returns NULL.
4350FunctionTemplateDecl *
4351Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4352 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004353 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004354 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004355 unsigned NumCallArguments1,
4356 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004358 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004360 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004362 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004363 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004365 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004366 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004367
Douglas Gregorcef1a032011-01-16 16:03:23 +00004368 // FIXME: This mimics what GCC implements, but doesn't match up with the
4369 // proposed resolution for core issue 692. This area needs to be sorted out,
4370 // but for now we attempt to maintain compatibility.
4371 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4372 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4373 if (Variadic1 != Variadic2)
4374 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375
Craig Topperc3ec1492014-05-26 06:22:03 +00004376 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004377}
Douglas Gregor9b146582009-07-08 20:55:45 +00004378
Douglas Gregor450f00842009-09-25 18:43:00 +00004379/// \brief Determine if the two templates are equivalent.
4380static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4381 if (T1 == T2)
4382 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
Douglas Gregor450f00842009-09-25 18:43:00 +00004384 if (!T1 || !T2)
4385 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004386
Douglas Gregor450f00842009-09-25 18:43:00 +00004387 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4388}
4389
4390/// \brief Retrieve the most specialized of the given function template
4391/// specializations.
4392///
John McCall58cc69d2010-01-27 01:50:18 +00004393/// \param SpecBegin the start iterator of the function template
4394/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004395///
John McCall58cc69d2010-01-27 01:50:18 +00004396/// \param SpecEnd the end iterator of the function template
4397/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004398///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004400/// diagnostic should occur.
4401///
4402/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4403/// no matching candidates.
4404///
4405/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4406/// occurs.
4407///
4408/// \param CandidateDiag partial diagnostic used for each function template
4409/// specialization that is a candidate in the ambiguous ordering. One parameter
4410/// in this diagnostic should be unbound, which will correspond to the string
4411/// describing the template arguments for the function template specialization.
4412///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004413/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004414/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004415UnresolvedSetIterator Sema::getMostSpecialized(
4416 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4417 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004418 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4419 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4420 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004421 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004422 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004423 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004424 FailedCandidates.NoteCandidates(*this, Loc);
4425 }
John McCall58cc69d2010-01-27 01:50:18 +00004426 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004428
4429 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004430 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Douglas Gregor450f00842009-09-25 18:43:00 +00004432 // Find the function template that is better than all of the templates it
4433 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004434 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004436 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004437 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004438 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4439 FunctionTemplateDecl *Challenger
4440 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004441 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004442 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004443 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004444 Challenger)) {
4445 Best = I;
4446 BestTemplate = Challenger;
4447 }
4448 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449
Douglas Gregor450f00842009-09-25 18:43:00 +00004450 // Make sure that the "best" function template is more specialized than all
4451 // of the others.
4452 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004453 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4454 FunctionTemplateDecl *Challenger
4455 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004456 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004458 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004459 BestTemplate)) {
4460 Ambiguous = true;
4461 break;
4462 }
4463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464
Douglas Gregor450f00842009-09-25 18:43:00 +00004465 if (!Ambiguous) {
4466 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004467 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004469
Douglas Gregor450f00842009-09-25 18:43:00 +00004470 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004471 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004472 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473
Richard Smithb875c432013-05-04 01:51:08 +00004474 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004475 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4476 PartialDiagnostic PD = CandidateDiag;
4477 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004478 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004479 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004480 if (!TargetType.isNull())
4481 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4482 TargetType);
4483 Diag((*I)->getLocation(), PD);
4484 }
Richard Smithb875c432013-05-04 01:51:08 +00004485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004486
John McCall58cc69d2010-01-27 01:50:18 +00004487 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004488}
4489
Douglas Gregorbe999392009-09-15 16:23:51 +00004490/// \brief Returns the more specialized class template partial specialization
4491/// according to the rules of partial ordering of class template partial
4492/// specializations (C++ [temp.class.order]).
4493///
4494/// \param PS1 the first class template partial specialization
4495///
4496/// \param PS2 the second class template partial specialization
4497///
4498/// \returns the more specialized class template partial specialization. If
4499/// neither partial specialization is more specialized, returns NULL.
4500ClassTemplatePartialSpecializationDecl *
4501Sema::getMoreSpecializedPartialSpecialization(
4502 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004503 ClassTemplatePartialSpecializationDecl *PS2,
4504 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004505 // C++ [temp.class.order]p1:
4506 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507 // specialized as the second if, given the following rewrite to two
4508 // function templates, the first function template is at least as
4509 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004510 // templates (14.6.6.2):
4511 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004512 // first partial specialization and has a single function parameter
4513 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004514 // arguments of the first partial specialization, and
4515 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516 // second partial specialization and has a single function parameter
4517 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004518 // arguments of the second partial specialization.
4519 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004520 // Rather than synthesize function templates, we merely perform the
4521 // equivalent partial ordering by performing deduction directly on
4522 // the template arguments of the class template partial
4523 // specializations. This computation is slightly simpler than the
4524 // general problem of function template partial ordering, because
4525 // class template partial specializations are more constrained. We
4526 // know that every template parameter is deducible from the class
4527 // template partial specialization's template arguments, for
4528 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004529 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004530 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004531
4532 QualType PT1 = PS1->getInjectedSpecializationType();
4533 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004534
Douglas Gregorbe999392009-09-15 16:23:51 +00004535 // Determine whether PS1 is at least as specialized as PS2
4536 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004537 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4538 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004539 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004540 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004541 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004542 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004543 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004544 Better1 = !::FinishTemplateArgumentDeduction(
4545 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4546 }
4547
4548 // Determine whether PS2 is at least as specialized as PS1
4549 Deduced.clear();
4550 Deduced.resize(PS1->getTemplateParameters()->size());
4551 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4552 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004553 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004554 if (Better2) {
4555 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4556 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004557 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004558 Better2 = !::FinishTemplateArgumentDeduction(
4559 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4560 }
4561
4562 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004563 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004564
4565 return Better1 ? PS1 : PS2;
4566}
4567
Larisse Voufo30616382013-08-23 22:21:36 +00004568/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4569/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4570/// VarTemplate(Partial)SpecializationDecl with a new data
4571/// structure Template(Partial)SpecializationDecl, and
4572/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004573VarTemplatePartialSpecializationDecl *
4574Sema::getMoreSpecializedPartialSpecialization(
4575 VarTemplatePartialSpecializationDecl *PS1,
4576 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4577 SmallVector<DeducedTemplateArgument, 4> Deduced;
4578 TemplateDeductionInfo Info(Loc);
4579
Richard Smithf04fd0b2013-12-12 23:14:16 +00004580 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004581 "the partial specializations being compared should specialize"
4582 " the same template.");
4583 TemplateName Name(PS1->getSpecializedTemplate());
4584 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4585 QualType PT1 = Context.getTemplateSpecializationType(
4586 CanonTemplate, PS1->getTemplateArgs().data(),
4587 PS1->getTemplateArgs().size());
4588 QualType PT2 = Context.getTemplateSpecializationType(
4589 CanonTemplate, PS2->getTemplateArgs().data(),
4590 PS2->getTemplateArgs().size());
4591
4592 // Determine whether PS1 is at least as specialized as PS2
4593 Deduced.resize(PS2->getTemplateParameters()->size());
4594 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4595 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004596 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004597 if (Better1) {
4598 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4599 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004600 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4602 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004603 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004605
Douglas Gregorbe999392009-09-15 16:23:51 +00004606 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004607 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004608 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004609 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4610 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004611 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004612 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004613 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004614 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004615 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4617 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004618 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004620
Douglas Gregorbe999392009-09-15 16:23:51 +00004621 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004622 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623
Douglas Gregorbe999392009-09-15 16:23:51 +00004624 return Better1? PS1 : PS2;
4625}
4626
Mike Stump11289f42009-09-09 15:08:12 +00004627static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004628MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004629 const TemplateArgument &TemplateArg,
4630 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004631 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004632 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004633
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004634/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004635/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004636static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004637MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004638 const Expr *E,
4639 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004640 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004641 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004642 // We can deduce from a pack expansion.
4643 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4644 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645
Richard Smith34349002012-07-09 03:07:20 +00004646 // Skip through any implicit casts we added while type-checking, and any
4647 // substitutions performed by template alias expansion.
4648 while (1) {
4649 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4650 E = ICE->getSubExpr();
4651 else if (const SubstNonTypeTemplateParmExpr *Subst =
4652 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4653 E = Subst->getReplacement();
4654 else
4655 break;
4656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657
4658 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004659 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004660 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004661 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004662 return;
4663
Mike Stump11289f42009-09-09 15:08:12 +00004664 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004665 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4666 if (!NTTP)
4667 return;
4668
Douglas Gregor21610382009-10-29 00:04:11 +00004669 if (NTTP->getDepth() == Depth)
4670 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004671}
4672
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004673/// \brief Mark the template parameters that are used by the given
4674/// nested name specifier.
4675static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004676MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004677 NestedNameSpecifier *NNS,
4678 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004679 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004680 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004681 if (!NNS)
4682 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004684 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004685 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004686 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004687 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004688}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004690/// \brief Mark the template parameters that are used by the given
4691/// template name.
4692static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004693MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004694 TemplateName Name,
4695 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004696 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004697 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004698 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4699 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004700 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4701 if (TTP->getDepth() == Depth)
4702 Used[TTP->getIndex()] = true;
4703 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004704 return;
4705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004706
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004707 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004708 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004709 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004710 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004711 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004712 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004713}
4714
4715/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004716/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004717static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004718MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004719 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004720 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004721 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004722 if (T.isNull())
4723 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724
Douglas Gregor91772d12009-06-13 00:26:55 +00004725 // Non-dependent types have nothing deducible
4726 if (!T->isDependentType())
4727 return;
4728
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004729 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004730 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004731 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004732 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004733 cast<PointerType>(T)->getPointeeType(),
4734 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004735 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004736 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004737 break;
4738
4739 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004740 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004741 cast<BlockPointerType>(T)->getPointeeType(),
4742 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004743 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004744 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004745 break;
4746
4747 case Type::LValueReference:
4748 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004749 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004750 cast<ReferenceType>(T)->getPointeeType(),
4751 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004752 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004753 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004754 break;
4755
4756 case Type::MemberPointer: {
4757 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004758 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004759 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004760 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004761 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004762 break;
4763 }
4764
4765 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004766 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004767 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004768 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004769 // Fall through to check the element type
4770
4771 case Type::ConstantArray:
4772 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004773 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004774 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004775 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004776 break;
4777
4778 case Type::Vector:
4779 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004780 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004781 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004782 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004783 break;
4784
Douglas Gregor758a8692009-06-17 21:51:59 +00004785 case Type::DependentSizedExtVector: {
4786 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004787 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004788 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004789 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004790 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004791 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004792 break;
4793 }
4794
Douglas Gregor91772d12009-06-13 00:26:55 +00004795 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004796 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004797 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4798 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004799 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4800 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004801 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004802 break;
4803 }
4804
Douglas Gregor21610382009-10-29 00:04:11 +00004805 case Type::TemplateTypeParm: {
4806 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4807 if (TTP->getDepth() == Depth)
4808 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004809 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004810 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004811
Douglas Gregorfb322d82011-01-14 05:11:40 +00004812 case Type::SubstTemplateTypeParmPack: {
4813 const SubstTemplateTypeParmPackType *Subst
4814 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004815 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004816 QualType(Subst->getReplacedParameter(), 0),
4817 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004818 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004819 OnlyDeduced, Depth, Used);
4820 break;
4821 }
4822
John McCall2408e322010-04-27 00:57:59 +00004823 case Type::InjectedClassName:
4824 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4825 // fall through
4826
Douglas Gregor91772d12009-06-13 00:26:55 +00004827 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004828 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004829 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004830 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004831 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832
Douglas Gregord0ad2942010-12-23 01:24:45 +00004833 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004834 // If the template argument list of P contains a pack expansion that is
4835 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004836 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004837 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004838 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4839 break;
4840
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004841 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004842 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004843 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004844 break;
4845 }
4846
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004847 case Type::Complex:
4848 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004849 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004850 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004851 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004852 break;
4853
Eli Friedman0dfb8892011-10-06 23:00:33 +00004854 case Type::Atomic:
4855 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004856 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004857 cast<AtomicType>(T)->getValueType(),
4858 OnlyDeduced, Depth, Used);
4859 break;
4860
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004861 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004862 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004863 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004864 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004865 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004866 break;
4867
John McCallc392f372010-06-11 00:33:02 +00004868 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004869 // C++14 [temp.deduct.type]p5:
4870 // The non-deduced contexts are:
4871 // -- The nested-name-specifier of a type that was specified using a
4872 // qualified-id
4873 //
4874 // C++14 [temp.deduct.type]p6:
4875 // When a type name is specified in a way that includes a non-deduced
4876 // context, all of the types that comprise that type name are also
4877 // non-deduced.
4878 if (OnlyDeduced)
4879 break;
4880
John McCallc392f372010-06-11 00:33:02 +00004881 const DependentTemplateSpecializationType *Spec
4882 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004883
Richard Smith50d5b972015-12-30 20:56:05 +00004884 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4885 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004886
John McCallc392f372010-06-11 00:33:02 +00004887 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004888 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004889 Used);
4890 break;
4891 }
4892
John McCallbd8d9bd2010-03-01 23:49:17 +00004893 case Type::TypeOf:
4894 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004895 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004896 cast<TypeOfType>(T)->getUnderlyingType(),
4897 OnlyDeduced, Depth, Used);
4898 break;
4899
4900 case Type::TypeOfExpr:
4901 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004902 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004903 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4904 OnlyDeduced, Depth, Used);
4905 break;
4906
4907 case Type::Decltype:
4908 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004909 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004910 cast<DecltypeType>(T)->getUnderlyingExpr(),
4911 OnlyDeduced, Depth, Used);
4912 break;
4913
Alexis Hunte852b102011-05-24 22:41:36 +00004914 case Type::UnaryTransform:
4915 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004916 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004917 cast<UnaryTransformType>(T)->getUnderlyingType(),
4918 OnlyDeduced, Depth, Used);
4919 break;
4920
Douglas Gregord2fa7662010-12-20 02:24:11 +00004921 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004922 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004923 cast<PackExpansionType>(T)->getPattern(),
4924 OnlyDeduced, Depth, Used);
4925 break;
4926
Richard Smith30482bc2011-02-20 03:19:35 +00004927 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004928 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004929 cast<AutoType>(T)->getDeducedType(),
4930 OnlyDeduced, Depth, Used);
4931
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004932 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004933 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004934 case Type::VariableArray:
4935 case Type::FunctionNoProto:
4936 case Type::Record:
4937 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004938 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004939 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004940 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004941 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00004942 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00004943#define TYPE(Class, Base)
4944#define ABSTRACT_TYPE(Class, Base)
4945#define DEPENDENT_TYPE(Class, Base)
4946#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4947#include "clang/AST/TypeNodes.def"
4948 break;
4949 }
4950}
4951
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004952/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004953/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004954static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004955MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004956 const TemplateArgument &TemplateArg,
4957 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004958 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004959 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004960 switch (TemplateArg.getKind()) {
4961 case TemplateArgument::Null:
4962 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004963 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004964 break;
Mike Stump11289f42009-09-09 15:08:12 +00004965
Eli Friedmanb826a002012-09-26 02:36:12 +00004966 case TemplateArgument::NullPtr:
4967 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4968 Depth, Used);
4969 break;
4970
Douglas Gregor91772d12009-06-13 00:26:55 +00004971 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004972 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004973 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004974 break;
4975
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004976 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004977 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004978 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004979 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004980 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004981 break;
4982
4983 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004984 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004985 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004986 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987
Anders Carlssonbc343912009-06-15 17:04:53 +00004988 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00004989 for (const auto &P : TemplateArg.pack_elements())
4990 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00004991 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00004992 }
4993}
4994
James Dennett41725122012-06-22 10:16:05 +00004995/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00004996/// template argument list.
4997///
4998/// \param TemplateArgs the template argument list from which template
4999/// parameters will be deduced.
5000///
James Dennett41725122012-06-22 10:16:05 +00005001/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005002/// to indicate when the corresponding template parameter will be
5003/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005004void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005005Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005006 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005007 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005008 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005009 // If the template argument list of P contains a pack expansion that is not
5010 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005011 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005012 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005013 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5014 return;
5015
Douglas Gregor91772d12009-06-13 00:26:55 +00005016 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005017 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005018 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005019}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005020
5021/// \brief Marks all of the template parameters that will be deduced by a
5022/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005023void Sema::MarkDeducedTemplateParameters(
5024 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5025 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005027 = FunctionTemplate->getTemplateParameters();
5028 Deduced.clear();
5029 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030
Douglas Gregorce23bae2009-09-18 23:21:38 +00005031 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5032 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005033 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005034 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005035}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005036
5037bool hasDeducibleTemplateParameters(Sema &S,
5038 FunctionTemplateDecl *FunctionTemplate,
5039 QualType T) {
5040 if (!T->isDependentType())
5041 return false;
5042
5043 TemplateParameterList *TemplateParams
5044 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005045 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005046 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005047 Deduced);
5048
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005049 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005050}