blob: aa824c37fe1adb7f1ec714b9eb62bcc10fc5e84f [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
John McCallc8e321d2016-03-01 02:09:25 +00002555 ExtParameterInfoBuilder ExtParamInfos;
2556
Douglas Gregor9b146582009-07-08 20:55:45 +00002557 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002558 // explicitly-specified template arguments. If the function has a trailing
2559 // return type, substitute it after the arguments to ensure we substitute
2560 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002561 if (Proto->hasTrailingReturn()) {
2562 if (SubstParmTypes(Function->getLocation(),
2563 Function->param_begin(), Function->getNumParams(),
John McCallc8e321d2016-03-01 02:09:25 +00002564 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002565 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002566 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002567 return TDK_SubstitutionFailure;
2568 }
2569
Richard Smith5e580292012-02-10 09:58:53 +00002570 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002571 QualType ResultType;
2572 {
2573 // C++11 [expr.prim.general]p3:
2574 // If a declaration declares a member function or member function
2575 // template of a class X, the expression this is a prvalue of type
2576 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2577 // and the end of the function-definition, member-declarator, or
2578 // declarator.
2579 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002580 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002581 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2582 ThisContext = Method->getParent();
2583 ThisTypeQuals = Method->getTypeQualifiers();
2584 }
2585
2586 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002587 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002588
2589 ResultType =
2590 SubstType(Proto->getReturnType(),
2591 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2592 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002593 if (ResultType.isNull() || Trap.hasErrorOccurred())
2594 return TDK_SubstitutionFailure;
2595 }
John McCallc8e321d2016-03-01 02:09:25 +00002596
Richard Smith5e580292012-02-10 09:58:53 +00002597 // Instantiate the types of each of the function parameters given the
2598 // explicitly-specified template arguments if we didn't do so earlier.
2599 if (!Proto->hasTrailingReturn() &&
2600 SubstParmTypes(Function->getLocation(),
2601 Function->param_begin(), Function->getNumParams(),
John McCallc8e321d2016-03-01 02:09:25 +00002602 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002603 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002604 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002605 return TDK_SubstitutionFailure;
2606
Douglas Gregor9b146582009-07-08 20:55:45 +00002607 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002608 auto EPI = Proto->getExtProtoInfo();
2609 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002610 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002611 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002612 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002613 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002614 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2615 return TDK_SubstitutionFailure;
2616 }
Mike Stump11289f42009-09-09 15:08:12 +00002617
Douglas Gregor9b146582009-07-08 20:55:45 +00002618 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002619 // Trailing template arguments that can be deduced (14.8.2) may be
2620 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002621 // template arguments can be deduced, they may all be omitted; in this
2622 // case, the empty template argument list <> itself may also be omitted.
2623 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002624 // Take all of the explicitly-specified arguments and put them into
2625 // the set of deduced template arguments. Explicitly-specified
2626 // parameter packs, however, will be set to NULL since the deduction
2627 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002628 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002629 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2630 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2631 if (Arg.getKind() == TemplateArgument::Pack)
2632 Deduced.push_back(DeducedTemplateArgument());
2633 else
2634 Deduced.push_back(Arg);
2635 }
Mike Stump11289f42009-09-09 15:08:12 +00002636
Douglas Gregor9b146582009-07-08 20:55:45 +00002637 return TDK_Success;
2638}
2639
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002640/// \brief Check whether the deduced argument type for a call to a function
2641/// template matches the actual argument type per C++ [temp.deduct.call]p4.
2642static bool
2643CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2644 QualType DeducedA) {
2645 ASTContext &Context = S.Context;
2646
2647 QualType A = OriginalArg.OriginalArgType;
2648 QualType OriginalParamType = OriginalArg.OriginalParamType;
2649
2650 // Check for type equality (top-level cv-qualifiers are ignored).
2651 if (Context.hasSameUnqualifiedType(A, DeducedA))
2652 return false;
2653
2654 // Strip off references on the argument types; they aren't needed for
2655 // the following checks.
2656 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2657 DeducedA = DeducedARef->getPointeeType();
2658 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2659 A = ARef->getPointeeType();
2660
2661 // C++ [temp.deduct.call]p4:
2662 // [...] However, there are three cases that allow a difference:
2663 // - If the original P is a reference type, the deduced A (i.e., the
2664 // type referred to by the reference) can be more cv-qualified than
2665 // the transformed A.
2666 if (const ReferenceType *OriginalParamRef
2667 = OriginalParamType->getAs<ReferenceType>()) {
2668 // We don't want to keep the reference around any more.
2669 OriginalParamType = OriginalParamRef->getPointeeType();
2670
2671 Qualifiers AQuals = A.getQualifiers();
2672 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002673
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002674 // Under Objective-C++ ARC, the deduced type may have implicitly
2675 // been given strong or (when dealing with a const reference)
2676 // unsafe_unretained lifetime. If so, update the original
2677 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002678 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002679 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2680 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2681 (DeducedAQuals.hasConst() &&
2682 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2683 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002684 }
2685
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002686 if (AQuals == DeducedAQuals) {
2687 // Qualifiers match; there's nothing to do.
2688 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002689 return true;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002690 } else {
2691 // Qualifiers are compatible, so have the argument type adopt the
2692 // deduced argument type's qualifiers as if we had performed the
2693 // qualification conversion.
2694 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2695 }
2696 }
2697
2698 // - The transformed A can be another pointer or pointer to member
2699 // type that can be converted to the deduced A via a qualification
2700 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002701 //
2702 // Also allow conversions which merely strip [[noreturn]] from function types
2703 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002704 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002705 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002706 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002707 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002708 (S.IsQualificationConversion(A, DeducedA, false,
2709 ObjCLifetimeConversion) ||
2710 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002711 return false;
2712
2713
2714 // - If P is a class and P has the form simple-template-id, then the
2715 // transformed A can be a derived class of the deduced A. [...]
2716 // [...] Likewise, if P is a pointer to a class of the form
2717 // simple-template-id, the transformed A can be a pointer to a
2718 // derived class pointed to by the deduced A.
2719 if (const PointerType *OriginalParamPtr
2720 = OriginalParamType->getAs<PointerType>()) {
2721 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2722 if (const PointerType *APtr = A->getAs<PointerType>()) {
2723 if (A->getPointeeType()->isRecordType()) {
2724 OriginalParamType = OriginalParamPtr->getPointeeType();
2725 DeducedA = DeducedAPtr->getPointeeType();
2726 A = APtr->getPointeeType();
2727 }
2728 }
2729 }
2730 }
2731
2732 if (Context.hasSameUnqualifiedType(A, DeducedA))
2733 return false;
2734
2735 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002736 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002737 return false;
2738
2739 return true;
2740}
2741
Mike Stump11289f42009-09-09 15:08:12 +00002742/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002743/// checking the deduced template arguments for completeness and forming
2744/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002745///
2746/// \param OriginalCallArgs If non-NULL, the original call arguments against
2747/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002748Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002749Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002750 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002751 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002752 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002753 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002754 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2755 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002756 TemplateParameterList *TemplateParams
2757 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002758
Eli Friedman77dcc722012-02-08 03:07:05 +00002759 // Unevaluated SFINAE context.
2760 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002761 SFINAETrap Trap(*this);
2762
Douglas Gregor9b146582009-07-08 20:55:45 +00002763 // Enter a new template instantiation context while we instantiate the
2764 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002765 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002766 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2767 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002768 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2769 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002770 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002771 return TDK_InstantiationDepth;
2772
John McCalle23b8712010-04-29 01:18:58 +00002773 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002774
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002775 // C++ [temp.deduct.type]p2:
2776 // [...] or if any template argument remains neither deduced nor
2777 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002778 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002779 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2780 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002781
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002782 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002783 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002784 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002785 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002786 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002787 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002788 // We may have had explicitly-specified template arguments for a
2789 // template parameter pack (that may or may not have been extended
2790 // via additional deduced arguments).
2791 if (Param->isParameterPack() && CurrentInstantiationScope) {
2792 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2793 Param) {
2794 // Forget the partially-substituted pack; its substitution is now
2795 // complete.
2796 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2797 }
2798 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002799 continue;
2800 }
Richard Smith37acb792016-02-03 20:15:01 +00002801
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002802 // We have deduced this argument, so it still needs to be
2803 // checked and converted.
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002804 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002805 FunctionTemplate, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002806 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002807 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002808 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002809 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2810 Builder.size()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002811 return TDK_SubstitutionFailure;
2812 }
2813
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002814 continue;
2815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002817 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002819 // be deduced to an empty sequence of template arguments.
2820 // FIXME: Where did the word "trailing" come from?
2821 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002822 // We may have had explicitly-specified template arguments for this
2823 // template parameter pack. If so, our empty deduction extends the
2824 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2825 const TemplateArgument *ExplicitArgs;
2826 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002827 if (CurrentInstantiationScope &&
2828 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002829 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002830 == Param) {
Benjamin Kramercce63472015-08-05 09:40:22 +00002831 Builder.push_back(TemplateArgument(
2832 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002833
Richard Smithdf18ee92016-02-03 20:40:30 +00002834 // Forget the partially-substituted pack; its substitution is now
Douglas Gregorcaddba92013-01-18 22:27:09 +00002835 // complete.
2836 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2837 } else {
Richard Smithdf18ee92016-02-03 20:40:30 +00002838 // Go through the motions of checking the empty argument pack against
2839 // the parameter pack.
2840 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2841 if (ConvertDeducedTemplateArgument(*this, Param, DeducedPack,
2842 FunctionTemplate, Info, true,
2843 Builder)) {
2844 Info.Param = makeTemplateParameter(Param);
2845 // FIXME: These template arguments are temporary. Free them!
2846 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2847 Builder.size()));
2848 return TDK_SubstitutionFailure;
2849 }
Douglas Gregorcaddba92013-01-18 22:27:09 +00002850 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002851 continue;
2852 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002853
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002854 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002855 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002856 TemplateArgumentLoc DefArg
2857 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2858 FunctionTemplate->getLocation(),
2859 FunctionTemplate->getSourceRange().getEnd(),
2860 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002861 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002862
2863 // If there was no default argument, deduction is incomplete.
2864 if (DefArg.getArgument().isNull()) {
2865 Info.Param = makeTemplateParameter(
2866 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Richard Smithc87b9382013-07-04 01:01:24 +00002867 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2868 Builder.size()));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002869 if (PartialOverloading) break;
2870
Richard Smithc87b9382013-07-04 01:01:24 +00002871 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002872 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002874 // Check whether we can actually use the default argument.
2875 if (CheckTemplateArgument(Param, DefArg,
2876 FunctionTemplate,
2877 FunctionTemplate->getLocation(),
2878 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002879 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002880 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002881 Info.Param = makeTemplateParameter(
2882 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002883 // FIXME: These template arguments are temporary. Free them!
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002884 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002885 Builder.size()));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002886 return TDK_SubstitutionFailure;
2887 }
2888
2889 // If we get here, we successfully used the default template argument.
2890 }
2891
2892 // Form the template argument list from the deduced template arguments.
2893 TemplateArgumentList *DeducedArgumentList
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002894 = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002895 Info.reset(DeducedArgumentList);
2896
Mike Stump11289f42009-09-09 15:08:12 +00002897 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002898 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002899 DeclContext *Owner = FunctionTemplate->getDeclContext();
2900 if (FunctionTemplate->getFriendObjectKind())
2901 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002902 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002903 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002904 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002905 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002906 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002907
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002908 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002909 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002910
Mike Stump11289f42009-09-09 15:08:12 +00002911 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002912 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002913 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2914 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002915 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002916
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002917 // There may have been an error that did not prevent us from constructing a
2918 // declaration. Mark the declaration invalid and return with a substitution
2919 // failure.
2920 if (Trap.hasErrorOccurred()) {
2921 Specialization->setInvalidDecl(true);
2922 return TDK_SubstitutionFailure;
2923 }
2924
Douglas Gregore65aacb2011-06-16 16:50:48 +00002925 if (OriginalCallArgs) {
2926 // C++ [temp.deduct.call]p4:
2927 // In general, the deduction process attempts to find template argument
2928 // values that will make the deduced A identical to A (after the type A
2929 // is transformed as described above). [...]
2930 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2931 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002932 unsigned ParamIdx = OriginalArg.ArgIdx;
2933
2934 if (ParamIdx >= Specialization->getNumParams())
2935 continue;
2936
2937 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002938 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2939 Info.FirstArg = TemplateArgument(DeducedA);
2940 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2941 Info.CallArgIndex = OriginalArg.ArgIdx;
2942 return TDK_DeducedMismatch;
2943 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002944 }
2945 }
2946
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002947 // If we suppressed any diagnostics while performing template argument
2948 // deduction, and if we haven't already instantiated this declaration,
2949 // keep track of these diagnostics. They'll be emitted if this specialization
2950 // is actually used.
2951 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002952 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002953 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2954 if (Pos == SuppressedDiagnostics.end())
2955 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2956 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002957 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002958
Mike Stump11289f42009-09-09 15:08:12 +00002959 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002960}
2961
John McCall8d08b9b2010-08-27 09:08:28 +00002962/// Gets the type of a function for template-argument-deducton
2963/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002964static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002965 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002966 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002967 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002968 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002969 return QualType();
2970
John McCallc1f69982010-02-02 02:21:27 +00002971 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002972 if (Method->isInstance()) {
2973 // An instance method that's referenced in a form that doesn't
2974 // look like a member pointer is just invalid.
2975 if (!R.HasFormOfMemberPointer) return QualType();
2976
Richard Smith2a7d4812013-05-04 07:00:32 +00002977 return S.Context.getMemberPointerType(Fn->getType(),
2978 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002979 }
2980
2981 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002982 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002983}
2984
2985/// Apply the deduction rules for overload sets.
2986///
2987/// \return the null type if this argument should be treated as an
2988/// undeduced context
2989static QualType
2990ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002991 Expr *Arg, QualType ParamType,
2992 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002993
John McCall8d08b9b2010-08-27 09:08:28 +00002994 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00002995
John McCall8d08b9b2010-08-27 09:08:28 +00002996 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00002997
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002998 // C++0x [temp.deduct.call]p4
2999 unsigned TDF = 0;
3000 if (ParamWasReference)
3001 TDF |= TDF_ParamWithReferenceType;
3002 if (R.IsAddressOfOperand)
3003 TDF |= TDF_IgnoreQualifiers;
3004
John McCallc1f69982010-02-02 02:21:27 +00003005 // C++0x [temp.deduct.call]p6:
3006 // When P is a function type, pointer to function type, or pointer
3007 // to member function type:
3008
3009 if (!ParamType->isFunctionType() &&
3010 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003011 !ParamType->isMemberFunctionPointerType()) {
3012 if (Ovl->hasExplicitTemplateArgs()) {
3013 // But we can still look for an explicit specialization.
3014 if (FunctionDecl *ExplicitSpec
3015 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003016 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003017 }
John McCallc1f69982010-02-02 02:21:27 +00003018
George Burgess IVcc2f3552016-03-19 21:51:45 +00003019 DeclAccessPair DAP;
3020 if (FunctionDecl *Viable =
3021 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3022 return GetTypeOfFunction(S, R, Viable);
3023
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003024 return QualType();
3025 }
3026
3027 // Gather the explicit template arguments, if any.
3028 TemplateArgumentListInfo ExplicitTemplateArgs;
3029 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003030 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003031 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003032 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3033 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003034 NamedDecl *D = (*I)->getUnderlyingDecl();
3035
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003036 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3037 // - If the argument is an overload set containing one or more
3038 // function templates, the parameter is treated as a
3039 // non-deduced context.
3040 if (!Ovl->hasExplicitTemplateArgs())
3041 return QualType();
3042
3043 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003044 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003045 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003046 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3047 Specialization, Info))
3048 continue;
3049
3050 D = Specialization;
3051 }
John McCallc1f69982010-02-02 02:21:27 +00003052
3053 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003054 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003055 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003056
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003057 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003059 ArgType->isFunctionType())
3060 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003061
John McCallc1f69982010-02-02 02:21:27 +00003062 // - If the argument is an overload set (not containing function
3063 // templates), trial argument deduction is attempted using each
3064 // of the members of the set. If deduction succeeds for only one
3065 // of the overload set members, that member is used as the
3066 // argument value for the deduction. If deduction succeeds for
3067 // more than one member of the overload set the parameter is
3068 // treated as a non-deduced context.
3069
3070 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3071 // Type deduction is done independently for each P/A pair, and
3072 // the deduced template argument values are then combined.
3073 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003074 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003075 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003076 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003077 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003078 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3079 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003080 if (Result) continue;
3081 if (!Match.isNull()) return QualType();
3082 Match = ArgType;
3083 }
3084
3085 return Match;
3086}
3087
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003088/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003089/// described in C++ [temp.deduct.call].
3090///
3091/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003092/// argument deduction based on this P/A pair because the argument is an
3093/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003094static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3095 TemplateParameterList *TemplateParams,
3096 QualType &ParamType,
3097 QualType &ArgType,
3098 Expr *Arg,
3099 unsigned &TDF) {
3100 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003101 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003102 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003103 if (ParamType.hasQualifiers())
3104 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003105
3106 // [...] If P is a reference type, the type referred to by P is
3107 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003108 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003109 if (ParamRefType)
3110 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003111
Nathan Sidwell96090022015-01-16 15:20:14 +00003112 // Overload sets usually make this parameter an undeduced context,
3113 // but there are sometimes special circumstances. Typically
3114 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003115 if (ArgType == S.Context.OverloadTy) {
3116 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3117 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003118 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003119 if (ArgType.isNull())
3120 return true;
3121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003122
Douglas Gregor7825bf32011-01-06 22:09:01 +00003123 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003124 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003125 if (ArgType->isIncompleteArrayType()) {
3126 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003127 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003128 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003129
Douglas Gregor7825bf32011-01-06 22:09:01 +00003130 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003131 // If P is an rvalue reference to a cv-unqualified template
3132 // parameter and the argument is an lvalue, the type "lvalue
3133 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003134 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003135 !ParamType.getQualifiers() &&
3136 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003137 Arg->isLValue())
3138 ArgType = S.Context.getLValueReferenceType(ArgType);
3139 } else {
3140 // C++ [temp.deduct.call]p2:
3141 // If P is not a reference type:
3142 // - If A is an array type, the pointer type produced by the
3143 // array-to-pointer standard conversion (4.2) is used in place of
3144 // A for type deduction; otherwise,
3145 if (ArgType->isArrayType())
3146 ArgType = S.Context.getArrayDecayedType(ArgType);
3147 // - If A is a function type, the pointer type produced by the
3148 // function-to-pointer standard conversion (4.3) is used in place
3149 // of A for type deduction; otherwise,
3150 else if (ArgType->isFunctionType())
3151 ArgType = S.Context.getPointerType(ArgType);
3152 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003153 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003154 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003155 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003156 }
3157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158
Douglas Gregor7825bf32011-01-06 22:09:01 +00003159 // C++0x [temp.deduct.call]p4:
3160 // In general, the deduction process attempts to find template argument
3161 // values that will make the deduced A identical to A (after the type A
3162 // is transformed as described above). [...]
3163 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003164
Douglas Gregor7825bf32011-01-06 22:09:01 +00003165 // - If the original P is a reference type, the deduced A (i.e., the
3166 // type referred to by the reference) can be more cv-qualified than
3167 // the transformed A.
3168 if (ParamRefType)
3169 TDF |= TDF_ParamWithReferenceType;
3170 // - The transformed A can be another pointer or pointer to member
3171 // type that can be converted to the deduced A via a qualification
3172 // conversion (4.4).
3173 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3174 ArgType->isObjCObjectPointerType())
3175 TDF |= TDF_IgnoreQualifiers;
3176 // - If P is a class and P has the form simple-template-id, then the
3177 // transformed A can be a derived class of the deduced A. Likewise,
3178 // if P is a pointer to a class of the form simple-template-id, the
3179 // transformed A can be a pointer to a derived class pointed to by
3180 // the deduced A.
3181 if (isSimpleTemplateIdType(ParamType) ||
3182 (isa<PointerType>(ParamType) &&
3183 isSimpleTemplateIdType(
3184 ParamType->getAs<PointerType>()->getPointeeType())))
3185 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003186
Douglas Gregor7825bf32011-01-06 22:09:01 +00003187 return false;
3188}
3189
Nico Weberc153d242014-07-28 00:02:09 +00003190static bool
3191hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3192 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003193
Hubert Tong3280b332015-06-25 00:25:49 +00003194static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3195 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3196 Expr *Arg, TemplateDeductionInfo &Info,
3197 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3198
3199/// \brief Attempt template argument deduction from an initializer list
3200/// deemed to be an argument in a function call.
3201static bool
3202DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3203 QualType AdjustedParamType, InitListExpr *ILE,
3204 TemplateDeductionInfo &Info,
3205 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3206 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003207
3208 // [temp.deduct.call] p1 (post CWG-1591)
3209 // If removing references and cv-qualifiers from P gives
3210 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3211 // non-empty initializer list (8.5.4), then deduction is performed instead for
3212 // each element of the initializer list, taking P0 as a function template
3213 // parameter type and the initializer element as its argument, and in the
3214 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3215 // length of the initializer list. Otherwise, an initializer list argument
3216 // causes the parameter to be considered a non-deduced context
3217
3218 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3219
3220 const bool IsDependentSizedArray =
3221 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3222
Faisal Validd76cc12015-12-10 12:29:11 +00003223 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003224
3225 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3226 S.isStdInitializerList(AdjustedParamType, &ElTy);
3227
3228 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003229 return false;
3230
3231 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003232 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3233 // deduce against the 'T' in T[N].
3234 if (ElTy.isNull()) {
3235 assert(!IsSTDList);
3236 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003237 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003238 // Deduction only needs to be done for dependent types.
3239 if (ElTy->isDependentType()) {
3240 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003241 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3242 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003243 return true;
3244 }
3245 }
3246 if (IsDependentSizedArray) {
3247 const DependentSizedArrayType *ArrTy =
3248 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3249 // Determine the array bound is something we can deduce.
3250 if (NonTypeTemplateParmDecl *NTTP =
3251 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3252 // We can perform template argument deduction for the given non-type
3253 // template parameter.
3254 assert(NTTP->getDepth() == 0 &&
3255 "Cannot deduce non-type template argument at depth > 0");
3256 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3257 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003258
Faisal Valif6dfdb32015-12-10 05:36:39 +00003259 Result = DeduceNonTypeTemplateArgument(
3260 S, NTTP, llvm::APSInt(Size), NTTP->getType(),
3261 /*ArrayBound=*/true, Info, Deduced);
3262 }
3263 }
Hubert Tong3280b332015-06-25 00:25:49 +00003264 return true;
3265}
3266
Sebastian Redl19181662012-03-15 21:40:51 +00003267/// \brief Perform template argument deduction by matching a parameter type
3268/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003269/// an initializer list that was originally matched against a parameter
3270/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003271static Sema::TemplateDeductionResult
3272DeduceTemplateArgumentByListElement(Sema &S,
3273 TemplateParameterList *TemplateParams,
3274 QualType ParamType, Expr *Arg,
3275 TemplateDeductionInfo &Info,
3276 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3277 unsigned TDF) {
3278 // Handle the case where an init list contains another init list as the
3279 // element.
3280 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003281 Sema::TemplateDeductionResult Result;
3282 if (!DeduceFromInitializerList(S, TemplateParams,
3283 ParamType.getNonReferenceType(), ILE, Info,
3284 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003285 return Sema::TDK_Success; // Just ignore this expression.
3286
Hubert Tong3280b332015-06-25 00:25:49 +00003287 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003288 }
3289
3290 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003291 QualType ArgType = Arg->getType();
3292 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003293 ArgType, Arg, TDF)) {
3294 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003295 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003296 }
Sebastian Redl19181662012-03-15 21:40:51 +00003297 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003298 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003299}
3300
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003301/// \brief Perform template argument deduction from a function call
3302/// (C++ [temp.deduct.call]).
3303///
3304/// \param FunctionTemplate the function template for which we are performing
3305/// template argument deduction.
3306///
James Dennett18348b62012-06-22 08:52:37 +00003307/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003308/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003309///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003310/// \param Args the function call arguments
3311///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003312/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003313/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003314/// template argument deduction.
3315///
3316/// \param Info the argument will be updated to provide additional information
3317/// about template argument deduction.
3318///
3319/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003320Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3321 FunctionTemplateDecl *FunctionTemplate,
3322 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003323 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3324 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003325 if (FunctionTemplate->isInvalidDecl())
3326 return TDK_Invalid;
3327
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003328 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003329 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003330
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003331 // C++ [temp.deduct.call]p1:
3332 // Template argument deduction is done by comparing each function template
3333 // parameter type (call it P) with the type of the corresponding argument
3334 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003335 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003336 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003337 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003338 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003339 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003340 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003341 if (Proto->isTemplateVariadic())
3342 /* Do nothing */;
3343 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003344 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003346 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003347 }
Mike Stump11289f42009-09-09 15:08:12 +00003348
Douglas Gregor89026b52009-06-30 23:57:56 +00003349 // The types of the parameters from which we will perform template argument
3350 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003351 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003352 TemplateParameterList *TemplateParams
3353 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003354 SmallVector<DeducedTemplateArgument, 4> Deduced;
3355 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003356 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003357 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003358 TemplateDeductionResult Result =
3359 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003360 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003361 Deduced,
3362 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003363 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003364 Info);
3365 if (Result)
3366 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003367
3368 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003369 } else {
3370 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003371 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003372 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3373 }
Mike Stump11289f42009-09-09 15:08:12 +00003374
Douglas Gregor89026b52009-06-30 23:57:56 +00003375 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003376 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003377 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003378 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003379 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3380 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003381 QualType OrigParamType = ParamTypes[ParamIdx];
3382 QualType ParamType = OrigParamType;
3383
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003385 = dyn_cast<PackExpansionType>(ParamType);
3386 if (!ParamExpansion) {
3387 // Simple case: matching a function parameter to a function argument.
3388 if (ArgIdx >= CheckArgs)
3389 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
Douglas Gregor7825bf32011-01-06 22:09:01 +00003391 Expr *Arg = Args[ArgIdx++];
3392 QualType ArgType = Arg->getType();
Douglas Gregore65aacb2011-06-16 16:50:48 +00003393
Douglas Gregor7825bf32011-01-06 22:09:01 +00003394 unsigned TDF = 0;
3395 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3396 ParamType, ArgType, Arg,
3397 TDF))
3398 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399
Douglas Gregor0c83c812011-10-09 22:06:46 +00003400 // If we have nothing to deduce, we're done.
3401 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3402 continue;
3403
Sebastian Redl43144e72012-01-17 22:49:58 +00003404 // If the argument is an initializer list ...
3405 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003406 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003407 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003408 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3409 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003410 continue;
3411
Hubert Tong3280b332015-06-25 00:25:49 +00003412 if (Result)
3413 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003414 // Don't track the argument type, since an initializer list has none.
3415 continue;
3416 }
3417
Douglas Gregore65aacb2011-06-16 16:50:48 +00003418 // Keep track of the argument type and corresponding parameter index,
3419 // so we can check for compatibility between the deduced A and A.
Douglas Gregor0c83c812011-10-09 22:06:46 +00003420 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3421 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003422
Douglas Gregor7825bf32011-01-06 22:09:01 +00003423 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003424 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3425 ParamType, ArgType,
3426 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003427 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003428
Douglas Gregor7825bf32011-01-06 22:09:01 +00003429 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431
Douglas Gregor7825bf32011-01-06 22:09:01 +00003432 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433 // For a function parameter pack that occurs at the end of the
3434 // parameter-declaration-list, the type A of each remaining argument of
3435 // the call is compared with the type P of the declarator-id of the
3436 // function parameter pack. Each comparison deduces template arguments
3437 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003438 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003440 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003441 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003442 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003443
Douglas Gregor7825bf32011-01-06 22:09:01 +00003444 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003445 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3446 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447
Douglas Gregor7825bf32011-01-06 22:09:01 +00003448 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003449 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003450 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451
Douglas Gregore65aacb2011-06-16 16:50:48 +00003452 QualType OrigParamType = ParamPattern;
3453 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003454 Expr *Arg = Args[ArgIdx];
3455 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003456
Douglas Gregor7825bf32011-01-06 22:09:01 +00003457 unsigned TDF = 0;
3458 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3459 ParamType, ArgType, Arg,
3460 TDF)) {
3461 // We can't actually perform any deduction for this argument, so stop
3462 // deduction at this point.
3463 ++ArgIdx;
3464 break;
3465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466
Sebastian Redl43144e72012-01-17 22:49:58 +00003467 // As above, initializer lists need special handling.
3468 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003469 TemplateDeductionResult Result;
3470 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3471 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003472 ++ArgIdx;
3473 break;
3474 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003475
Hubert Tong3280b332015-06-25 00:25:49 +00003476 if (Result)
3477 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003478 } else {
3479
3480 // Keep track of the argument type and corresponding argument index,
3481 // so we can check for compatibility between the deduced A and A.
3482 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3483 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3484 ArgType));
3485
3486 if (TemplateDeductionResult Result
3487 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3488 ParamType, ArgType, Info,
3489 Deduced, TDF))
3490 return Result;
3491 }
Mike Stump11289f42009-09-09 15:08:12 +00003492
Richard Smith0a80d572014-05-29 01:12:14 +00003493 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003494 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003495
Douglas Gregor7825bf32011-01-06 22:09:01 +00003496 // Build argument packs for each of the parameter packs expanded by this
3497 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003498 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003499 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003500
Douglas Gregor7825bf32011-01-06 22:09:01 +00003501 // After we've matching against a parameter pack, we're done.
3502 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003503 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003504
Mike Stump11289f42009-09-09 15:08:12 +00003505 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003506 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003507 Info, &OriginalCallArgs,
3508 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003509}
3510
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003511QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3512 QualType FunctionType) {
3513 if (ArgFunctionType.isNull())
3514 return ArgFunctionType;
3515
3516 const FunctionProtoType *FunctionTypeP =
3517 FunctionType->castAs<FunctionProtoType>();
3518 CallingConv CC = FunctionTypeP->getCallConv();
3519 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3520 const FunctionProtoType *ArgFunctionTypeP =
3521 ArgFunctionType->getAs<FunctionProtoType>();
3522 if (ArgFunctionTypeP->getCallConv() == CC &&
3523 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3524 return ArgFunctionType;
3525
3526 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3527 EI = EI.withNoReturn(NoReturn);
3528 ArgFunctionTypeP =
3529 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3530 return QualType(ArgFunctionTypeP, 0);
3531}
3532
Douglas Gregor9b146582009-07-08 20:55:45 +00003533/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003534/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3535/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003536///
3537/// \param FunctionTemplate the function template for which we are performing
3538/// template argument deduction.
3539///
James Dennett18348b62012-06-22 08:52:37 +00003540/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003541/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003542///
3543/// \param ArgFunctionType the function type that will be used as the
3544/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003545/// function template's function type. This type may be NULL, if there is no
3546/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003547///
3548/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003549/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003550/// template argument deduction.
3551///
3552/// \param Info the argument will be updated to provide additional information
3553/// about template argument deduction.
3554///
3555/// \returns the result of template argument deduction.
3556Sema::TemplateDeductionResult
3557Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003558 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003559 QualType ArgFunctionType,
3560 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003561 TemplateDeductionInfo &Info,
3562 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003563 if (FunctionTemplate->isInvalidDecl())
3564 return TDK_Invalid;
3565
Douglas Gregor9b146582009-07-08 20:55:45 +00003566 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3567 TemplateParameterList *TemplateParams
3568 = FunctionTemplate->getTemplateParameters();
3569 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003570 if (!InOverloadResolution)
3571 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003572
Douglas Gregor9b146582009-07-08 20:55:45 +00003573 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003574 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003575 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003576 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003577 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003578 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003579 if (TemplateDeductionResult Result
3580 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003581 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003582 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003583 &FunctionType, Info))
3584 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003585
3586 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003587 }
3588
Eli Friedman77dcc722012-02-08 03:07:05 +00003589 // Unevaluated SFINAE context.
3590 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003591 SFINAETrap Trap(*this);
3592
John McCallc1f69982010-02-02 02:21:27 +00003593 Deduced.resize(TemplateParams->size());
3594
Richard Smith2a7d4812013-05-04 07:00:32 +00003595 // If the function has a deduced return type, substitute it for a dependent
3596 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003597 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003598 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003599 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003600 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003601 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003602 }
3603
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003604 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003605 unsigned TDF = TDF_TopLevelParameterTypeList;
3606 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003607 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003608 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003609 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003610 FunctionType, ArgFunctionType,
3611 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003612 return Result;
3613 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003614
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003616 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3617 NumExplicitlySpecified,
3618 Specialization, Info))
3619 return Result;
3620
Richard Smith2a7d4812013-05-04 07:00:32 +00003621 // If the function has a deduced return type, deduce it now, so we can check
3622 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003623 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003624 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003625 DeduceReturnType(Specialization, Info.getLocation(), false))
3626 return TDK_MiscellaneousDeductionFailure;
3627
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003628 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003629 // specialization with respect to arguments of compatible pointer to function
3630 // types, template argument deduction fails.
3631 if (!ArgFunctionType.isNull()) {
3632 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3633 Context.getCanonicalType(Specialization->getType()),
3634 Context.getCanonicalType(ArgFunctionType)))
3635 return TDK_MiscellaneousDeductionFailure;
3636 else if(!InOverloadResolution &&
3637 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3638 return TDK_MiscellaneousDeductionFailure;
3639 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003640
3641 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003642}
3643
Faisal Vali850da1a2013-09-29 17:08:32 +00003644/// \brief Given a function declaration (e.g. a generic lambda conversion
3645/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003646/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3647/// to replace 'auto' with and not the actual result type you want
3648/// to set the function to.
Faisal Vali571df122013-09-29 08:45:24 +00003649static inline void
Faisal Vali2b3a3012013-10-24 23:40:02 +00003650SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003651 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003652 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003653 QualType AutoResultType = F->getReturnType();
Faisal Vali850da1a2013-09-29 17:08:32 +00003654 assert(AutoResultType->getContainedAutoType());
3655 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003656 TypeToReplaceAutoWith);
3657 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3658}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003659
3660/// \brief Given a specialized conversion operator of a generic lambda
3661/// create the corresponding specializations of the call operator and
3662/// the static-invoker. If the return type of the call operator is auto,
3663/// deduce its return type and check if that matches the
3664/// return type of the destination function ptr.
3665
3666static inline Sema::TemplateDeductionResult
3667SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3668 CXXConversionDecl *ConversionSpecialized,
3669 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3670 QualType ReturnTypeOfDestFunctionPtr,
3671 TemplateDeductionInfo &TDInfo,
3672 Sema &S) {
3673
3674 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3675 assert(LambdaClass && LambdaClass->isGenericLambda());
3676
3677 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003678 QualType CallOpResultType = CallOpGeneric->getReturnType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003679 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3680 CallOpResultType->getContainedAutoType();
3681
3682 FunctionTemplateDecl *CallOpTemplate =
3683 CallOpGeneric->getDescribedFunctionTemplate();
3684
Craig Topperc3ec1492014-05-26 06:22:03 +00003685 FunctionDecl *CallOpSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003686 // Use the deduced arguments of the conversion function, to specialize our
3687 // generic lambda's call operator.
3688 if (Sema::TemplateDeductionResult Result
3689 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3690 DeducedArguments,
3691 0, CallOpSpecialized, TDInfo))
3692 return Result;
3693
3694 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003695 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3696 CallOpSpecialized->getReturnType()->isUndeducedType())
Faisal Vali2b3a3012013-10-24 23:40:02 +00003697 S.DeduceReturnType(CallOpSpecialized,
3698 CallOpSpecialized->getPointOfInstantiation(),
3699 /*Diagnose*/ true);
3700
3701 // Check to see if the return type of the destination ptr-to-function
3702 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003703 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003704 ReturnTypeOfDestFunctionPtr))
3705 return Sema::TDK_NonDeducedMismatch;
3706 // Since we have succeeded in matching the source and destination
3707 // ptr-to-functions (now including return type), and have successfully
3708 // specialized our corresponding call operator, we are ready to
3709 // specialize the static invoker with the deduced arguments of our
3710 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003711 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003712 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3713 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3714
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003715#ifndef NDEBUG
3716 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3717#endif
3718 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003719 InvokerSpecialized, TDInfo);
3720 assert(Result == Sema::TDK_Success &&
3721 "If the call operator succeeded so should the invoker!");
3722 // Set the result type to match the corresponding call operator
3723 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003724 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3725 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003726 // Be sure to get the type to replace 'auto' with and not
3727 // the full result type of the call op specialization
3728 // to substitute into the 'auto' of the invoker and conversion
3729 // function.
3730 // For e.g.
3731 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3732 // We don't want to subst 'int*' into 'auto' to get int**.
3733
Alp Toker314cc812014-01-25 16:55:45 +00003734 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3735 ->getContainedAutoType()
3736 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003737 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3738 TypeToReplaceAutoWith, S);
3739 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3740 TypeToReplaceAutoWith, S);
3741 }
3742
3743 // Ensure that static invoker doesn't have a const qualifier.
3744 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3745 // do not use the CallOperator's TypeSourceInfo which allows
3746 // the const qualifier to leak through.
3747 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3748 getType().getTypePtr()->castAs<FunctionProtoType>();
3749 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3750 EPI.TypeQuals = 0;
3751 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003752 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003753 return Sema::TDK_Success;
3754}
Douglas Gregor05155d82009-08-21 23:19:43 +00003755/// \brief Deduce template arguments for a templated conversion
3756/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3757/// conversion function template specialization.
3758Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003759Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003760 QualType ToType,
3761 CXXConversionDecl *&Specialization,
3762 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003763 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003764 return TDK_Invalid;
3765
Faisal Vali2b3a3012013-10-24 23:40:02 +00003766 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003767 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3768
Faisal Vali2b3a3012013-10-24 23:40:02 +00003769 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003770
3771 // Canonicalize the types for deduction.
3772 QualType P = Context.getCanonicalType(FromType);
3773 QualType A = Context.getCanonicalType(ToType);
3774
Douglas Gregord99609a2011-03-06 09:03:20 +00003775 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003776 // If P is a reference type, the type referred to by P is used for
3777 // type deduction.
3778 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3779 P = PRef->getPointeeType();
3780
Douglas Gregord99609a2011-03-06 09:03:20 +00003781 // C++0x [temp.deduct.conv]p4:
3782 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003783 // for type deduction.
3784 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003785 A = ARef->getPointeeType().getUnqualifiedType();
3786 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003787 //
Mike Stump11289f42009-09-09 15:08:12 +00003788 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003789 else {
3790 assert(!A->isReferenceType() && "Reference types were handled above");
3791
3792 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003793 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003794 // of P for type deduction; otherwise,
3795 if (P->isArrayType())
3796 P = Context.getArrayDecayedType(P);
3797 // - If P is a function type, the pointer type produced by the
3798 // function-to-pointer standard conversion (4.3) is used in
3799 // place of P for type deduction; otherwise,
3800 else if (P->isFunctionType())
3801 P = Context.getPointerType(P);
3802 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003803 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003804 else
3805 P = P.getUnqualifiedType();
3806
Douglas Gregord99609a2011-03-06 09:03:20 +00003807 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003808 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003809 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003810 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003811 A = A.getUnqualifiedType();
3812 }
3813
Eli Friedman77dcc722012-02-08 03:07:05 +00003814 // Unevaluated SFINAE context.
3815 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003816 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003817
3818 // C++ [temp.deduct.conv]p1:
3819 // Template argument deduction is done by comparing the return
3820 // type of the template conversion function (call it P) with the
3821 // type that is required as the result of the conversion (call it
3822 // A) as described in 14.8.2.4.
3823 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003824 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003825 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003826 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003827
3828 // C++0x [temp.deduct.conv]p4:
3829 // In general, the deduction process attempts to find template
3830 // argument values that will make the deduced A identical to
3831 // A. However, there are two cases that allow a difference:
3832 unsigned TDF = 0;
3833 // - If the original A is a reference type, A can be more
3834 // cv-qualified than the deduced A (i.e., the type referred to
3835 // by the reference)
3836 if (ToType->isReferenceType())
3837 TDF |= TDF_ParamWithReferenceType;
3838 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003839 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003840 // conversion.
3841 //
3842 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3843 // both P and A are pointers or member pointers. In this case, we
3844 // just ignore cv-qualifiers completely).
3845 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003846 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003847 TDF |= TDF_IgnoreQualifiers;
3848 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003849 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3850 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003851 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003852
3853 // Create an Instantiation Scope for finalizing the operator.
3854 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003855 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003856 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003857 TemplateDeductionResult Result
Faisal Vali2b3a3012013-10-24 23:40:02 +00003858 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3859 ConversionSpecialized, Info);
3860 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3861
3862 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003863 // to a ptr-to-function, use the deduced arguments from the conversion
3864 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003865 // e.g., int (*fp)(int) = [](auto a) { return a; };
3866 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3867
3868 // Get the return type of the destination ptr-to-function we are converting
3869 // to. This is necessary for matching the lambda call operator's return
3870 // type to that of the destination ptr-to-function's return type.
3871 assert(A->isPointerType() &&
3872 "Can only convert from lambda to ptr-to-function");
3873 const FunctionType *ToFunType =
3874 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003875 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3876
Faisal Vali2b3a3012013-10-24 23:40:02 +00003877 // Create the corresponding specializations of the call operator and
3878 // the static-invoker; and if the return type is auto,
3879 // deduce the return type and check if it matches the
3880 // DestFunctionPtrReturnType.
3881 // For instance:
3882 // auto L = [](auto a) { return f(a); };
3883 // int (*fp)(int) = L;
3884 // char (*fp2)(int) = L; <-- Not OK.
3885
3886 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3887 Specialization, Deduced, DestFunctionPtrReturnType,
3888 Info, *this);
3889 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003890 return Result;
3891}
3892
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003893/// \brief Deduce template arguments for a function template when there is
3894/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3895///
3896/// \param FunctionTemplate the function template for which we are performing
3897/// template argument deduction.
3898///
James Dennett18348b62012-06-22 08:52:37 +00003899/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003900/// arguments.
3901///
3902/// \param Specialization if template argument deduction was successful,
3903/// this will be set to the function template specialization produced by
3904/// template argument deduction.
3905///
3906/// \param Info the argument will be updated to provide additional information
3907/// about template argument deduction.
3908///
3909/// \returns the result of template argument deduction.
3910Sema::TemplateDeductionResult
3911Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003912 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003913 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003914 TemplateDeductionInfo &Info,
3915 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003916 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003917 QualType(), Specialization, Info,
3918 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003919}
3920
Richard Smith30482bc2011-02-20 03:19:35 +00003921namespace {
3922 /// Substitute the 'auto' type specifier within a type for a given replacement
3923 /// type.
3924 class SubstituteAutoTransform :
3925 public TreeTransform<SubstituteAutoTransform> {
3926 QualType Replacement;
3927 public:
Nico Weberc153d242014-07-28 00:02:09 +00003928 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3929 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3930 Replacement(Replacement) {}
3931
Richard Smith30482bc2011-02-20 03:19:35 +00003932 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3933 // If we're building the type pattern to deduce against, don't wrap the
3934 // substituted type in an AutoType. Certain template deduction rules
3935 // apply only when a template type parameter appears directly (and not if
3936 // the parameter is found through desugaring). For instance:
3937 // auto &&lref = lvalue;
3938 // must transform into "rvalue reference to T" not "rvalue reference to
3939 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003940 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003941 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003942 TemplateTypeParmTypeLoc NewTL =
3943 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003944 NewTL.setNameLoc(TL.getNameLoc());
3945 return Result;
3946 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003947 bool Dependent =
3948 !Replacement.isNull() && Replacement->isDependentType();
3949 QualType Result =
3950 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00003951 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003952 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003953 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3954 NewTL.setNameLoc(TL.getNameLoc());
3955 return Result;
3956 }
3957 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003958
3959 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3960 // Lambdas never need to be transformed.
3961 return E;
3962 }
Richard Smith061f1e22013-04-30 21:23:01 +00003963
Richard Smith2a7d4812013-05-04 07:00:32 +00003964 QualType Apply(TypeLoc TL) {
3965 // Create some scratch storage for the transformed type locations.
3966 // FIXME: We're just going to throw this information away. Don't build it.
3967 TypeLocBuilder TLB;
3968 TLB.reserve(TL.getFullDataSize());
3969 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003970 }
Richard Smith30482bc2011-02-20 03:19:35 +00003971 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003972}
Richard Smith30482bc2011-02-20 03:19:35 +00003973
Richard Smith2a7d4812013-05-04 07:00:32 +00003974Sema::DeduceAutoResult
3975Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
3976 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3977}
3978
Richard Smith061f1e22013-04-30 21:23:01 +00003979/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003980///
3981/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003982/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003983/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003984/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00003985Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00003986Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00003987 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003988 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3989 if (NonPlaceholder.isInvalid())
3990 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003991 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003992 }
3993
Richard Smith2a7d4812013-05-04 07:00:32 +00003994 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003995 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00003996 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00003997 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00003998 }
3999
Richard Smith74aeef52013-04-26 16:15:35 +00004000 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4001 // Since 'decltype(auto)' can only occur at the top of the type, we
4002 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004003 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004004 if (AT->isDecltypeAuto()) {
4005 if (isa<InitListExpr>(Init)) {
4006 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4007 return DAR_FailedAlreadyDiagnosed;
4008 }
4009
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004010 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004011 if (Deduced.isNull())
4012 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004013 // FIXME: Support a non-canonical deduced type for 'auto'.
4014 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004015 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004016 if (Result.isNull())
4017 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004018 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004019 } else if (!getLangOpts().CPlusPlus) {
4020 if (isa<InitListExpr>(Init)) {
4021 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4022 return DAR_FailedAlreadyDiagnosed;
4023 }
Richard Smith74aeef52013-04-26 16:15:35 +00004024 }
4025 }
4026
Richard Smith30482bc2011-02-20 03:19:35 +00004027 SourceLocation Loc = Init->getExprLoc();
4028
4029 LocalInstantiationScope InstScope(*this);
4030
4031 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004032 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004033 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4034 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004035 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4036 NamedDecl *TemplParamPtr = TemplParam;
James Y Knight7a22b242015-08-06 20:26:32 +00004037 FixedSizeTemplateParameterListStorage<1> TemplateParamsSt(
David Majnemer902f8c62015-12-27 07:16:27 +00004038 Loc, Loc, TemplParamPtr, Loc);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004039
Richard Smith061f1e22013-04-30 21:23:01 +00004040 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4041 assert(!FuncParam.isNull() &&
4042 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004043
4044 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004045 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004046 Deduced.resize(1);
4047 QualType InitType = Init->getType();
4048 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004049
Craig Toppere6706e42012-09-19 02:26:47 +00004050 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004051
Richard Smith74801c82012-07-08 04:13:07 +00004052 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004053 if (InitList) {
4054 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004055 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4056 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004057 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004058 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004059 }
4060 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004061 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4062 Diag(Loc, diag::err_auto_bitfield);
4063 return DAR_FailedAlreadyDiagnosed;
4064 }
4065
James Y Knight7a22b242015-08-06 20:26:32 +00004066 if (AdjustFunctionParmAndArgTypesForDeduction(
4067 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004068 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004069
James Y Knight7a22b242015-08-06 20:26:32 +00004070 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4071 FuncParam, InitType, Info, Deduced,
4072 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004073 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004074 }
Richard Smith30482bc2011-02-20 03:19:35 +00004075
Eli Friedmane4310952012-11-06 23:56:42 +00004076 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004077 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004078
Eli Friedmane4310952012-11-06 23:56:42 +00004079 QualType DeducedType = Deduced[0].getAsType();
4080
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004081 if (InitList) {
4082 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4083 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004084 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004085 }
4086
Richard Smith061f1e22013-04-30 21:23:01 +00004087 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004088 if (Result.isNull())
4089 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004090
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004091 // Check that the deduced argument type is compatible with the original
4092 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004093 if (!InitList && !Result.isNull() &&
4094 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004095 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004096 Result)) {
4097 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004098 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004099 }
4100
Sebastian Redl09edce02012-01-23 22:09:39 +00004101 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004102}
4103
Faisal Vali2b391ab2013-09-26 19:54:12 +00004104QualType Sema::SubstAutoType(QualType TypeWithAuto,
4105 QualType TypeToReplaceAuto) {
4106 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4107 TransformType(TypeWithAuto);
4108}
4109
4110TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4111 QualType TypeToReplaceAuto) {
4112 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4113 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004114}
4115
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004116void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4117 if (isa<InitListExpr>(Init))
4118 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004119 VDecl->isInitCapture()
4120 ? diag::err_init_capture_deduction_failure_from_init_list
4121 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004122 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4123 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004124 Diag(VDecl->getLocation(),
4125 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4126 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004127 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4128 << Init->getSourceRange();
4129}
4130
Richard Smith2a7d4812013-05-04 07:00:32 +00004131bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4132 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004133 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004134
4135 if (FD->getTemplateInstantiationPattern())
4136 InstantiateFunctionDefinition(Loc, FD);
4137
Alp Toker314cc812014-01-25 16:55:45 +00004138 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004139 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4140 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4141 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4142 }
4143
4144 return StillUndeduced;
4145}
4146
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004147static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004148MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004149 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004150 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004151 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004152
4153/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004154static void
4155AddImplicitObjectParameterType(ASTContext &Context,
4156 CXXMethodDecl *Method,
4157 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004158 // C++11 [temp.func.order]p3:
4159 // [...] The new parameter is of type "reference to cv A," where cv are
4160 // the cv-qualifiers of the function template (if any) and A is
4161 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004162 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004163 // The standard doesn't say explicitly, but we pick the appropriate kind of
4164 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004165 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4166 ArgTy = Context.getQualifiedType(ArgTy,
4167 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004168 if (Method->getRefQualifier() == RQ_RValue)
4169 ArgTy = Context.getRValueReferenceType(ArgTy);
4170 else
4171 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004172 ArgTypes.push_back(ArgTy);
4173}
4174
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004175/// \brief Determine whether the function template \p FT1 is at least as
4176/// specialized as \p FT2.
4177static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004178 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004179 FunctionTemplateDecl *FT1,
4180 FunctionTemplateDecl *FT2,
4181 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004182 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004183 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004185 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4186 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004187
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004188 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4189 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004190 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004191 Deduced.resize(TemplateParams->size());
4192
4193 // C++0x [temp.deduct.partial]p3:
4194 // The types used to determine the ordering depend on the context in which
4195 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004196 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004197 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004198 switch (TPOC) {
4199 case TPOC_Call: {
4200 // - In the context of a function call, the function parameter types are
4201 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004202 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4203 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004204
Eli Friedman3b5774a2012-09-19 23:27:04 +00004205 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004206 // [...] If only one of the function templates is a non-static
4207 // member, that function template is considered to have a new
4208 // first parameter inserted in its function parameter list. The
4209 // new parameter is of type "reference to cv A," where cv are
4210 // the cv-qualifiers of the function template (if any) and A is
4211 // the class of which the function template is a member.
4212 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004213 // Note that we interpret this to mean "if one of the function
4214 // templates is a non-static member and the other is a non-member";
4215 // otherwise, the ordering rules for static functions against non-static
4216 // functions don't make any sense.
4217 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004218 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4219 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004220 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004221
Richard Smithe5b52202013-09-11 00:52:39 +00004222 unsigned NumComparedArguments = NumCallArguments1;
4223
4224 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004225 // Compare 'this' from Method1 against first parameter from Method2.
4226 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4227 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004228 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004229 // Compare 'this' from Method2 against first parameter from Method1.
4230 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004231 }
4232
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004233 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004234 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004235 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004236 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237
Douglas Gregorb837ea42011-01-11 17:34:58 +00004238 // C++ [temp.func.order]p5:
4239 // The presence of unused ellipsis and default arguments has no effect on
4240 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004241 if (Args1.size() > NumComparedArguments)
4242 Args1.resize(NumComparedArguments);
4243 if (Args2.size() > NumComparedArguments)
4244 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004245 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4246 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004247 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004248 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004249
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004250 break;
4251 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004252
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004253 case TPOC_Conversion:
4254 // - In the context of a call to a conversion operator, the return types
4255 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004256 if (DeduceTemplateArgumentsByTypeMatch(
4257 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4258 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004259 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004260 return false;
4261 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004263 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004264 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004265 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004266 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4267 FD2->getType(), FD1->getType(),
4268 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004269 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004270 return false;
4271 break;
4272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004274 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275 // In most cases, all template parameters must have values in order for
4276 // deduction to succeed, but for partial ordering purposes a template
4277 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004278 // types being used for partial ordering. [ Note: a template parameter used
4279 // in a non-deduced context is considered used. -end note]
4280 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4281 for (; ArgIdx != NumArgs; ++ArgIdx)
4282 if (Deduced[ArgIdx].isNull())
4283 break;
4284
4285 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004286 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004287 // as FT2.
4288 return true;
4289 }
4290
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004291 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004292 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004293 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004294 case TPOC_Call:
4295 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4296 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004297 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004298 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004299 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004301 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004302 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4303 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004304 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004305
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004306 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004307 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004308 TemplateParams->getDepth(),
4309 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004310 break;
4311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004313 for (; ArgIdx != NumArgs; ++ArgIdx)
4314 // If this argument had no value deduced but was used in one of the types
4315 // used for partial ordering, then deduction fails.
4316 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4317 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004319 return true;
4320}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321
Douglas Gregorcef1a032011-01-16 16:03:23 +00004322/// \brief Determine whether this a function template whose parameter-type-list
4323/// ends with a function parameter pack.
4324static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4325 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4326 unsigned NumParams = Function->getNumParams();
4327 if (NumParams == 0)
4328 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329
Douglas Gregorcef1a032011-01-16 16:03:23 +00004330 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4331 if (!Last->isParameterPack())
4332 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333
Douglas Gregorcef1a032011-01-16 16:03:23 +00004334 // Make sure that no previous parameter is a parameter pack.
4335 while (--NumParams > 0) {
4336 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4337 return false;
4338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339
Douglas Gregorcef1a032011-01-16 16:03:23 +00004340 return true;
4341}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342
Douglas Gregorbe999392009-09-15 16:23:51 +00004343/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004344/// to the rules of function template partial ordering (C++ [temp.func.order]).
4345///
4346/// \param FT1 the first function template
4347///
4348/// \param FT2 the second function template
4349///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004350/// \param TPOC the context in which we are performing partial ordering of
4351/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004352///
Richard Smithe5b52202013-09-11 00:52:39 +00004353/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4354/// only when \c TPOC is \c TPOC_Call.
4355///
4356/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4357/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004358///
Douglas Gregorbe999392009-09-15 16:23:51 +00004359/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004360/// template is more specialized, returns NULL.
4361FunctionTemplateDecl *
4362Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4363 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004364 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004365 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004366 unsigned NumCallArguments1,
4367 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004369 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004371 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004373 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004374 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004376 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004377 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004378
Douglas Gregorcef1a032011-01-16 16:03:23 +00004379 // FIXME: This mimics what GCC implements, but doesn't match up with the
4380 // proposed resolution for core issue 692. This area needs to be sorted out,
4381 // but for now we attempt to maintain compatibility.
4382 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4383 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4384 if (Variadic1 != Variadic2)
4385 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004386
Craig Topperc3ec1492014-05-26 06:22:03 +00004387 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004388}
Douglas Gregor9b146582009-07-08 20:55:45 +00004389
Douglas Gregor450f00842009-09-25 18:43:00 +00004390/// \brief Determine if the two templates are equivalent.
4391static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4392 if (T1 == T2)
4393 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Douglas Gregor450f00842009-09-25 18:43:00 +00004395 if (!T1 || !T2)
4396 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397
Douglas Gregor450f00842009-09-25 18:43:00 +00004398 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4399}
4400
4401/// \brief Retrieve the most specialized of the given function template
4402/// specializations.
4403///
John McCall58cc69d2010-01-27 01:50:18 +00004404/// \param SpecBegin the start iterator of the function template
4405/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004406///
John McCall58cc69d2010-01-27 01:50:18 +00004407/// \param SpecEnd the end iterator of the function template
4408/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004409///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004411/// diagnostic should occur.
4412///
4413/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4414/// no matching candidates.
4415///
4416/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4417/// occurs.
4418///
4419/// \param CandidateDiag partial diagnostic used for each function template
4420/// specialization that is a candidate in the ambiguous ordering. One parameter
4421/// in this diagnostic should be unbound, which will correspond to the string
4422/// describing the template arguments for the function template specialization.
4423///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004424/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004425/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004426UnresolvedSetIterator Sema::getMostSpecialized(
4427 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4428 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004429 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4430 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4431 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004432 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004433 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004434 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004435 FailedCandidates.NoteCandidates(*this, Loc);
4436 }
John McCall58cc69d2010-01-27 01:50:18 +00004437 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439
4440 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004441 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442
Douglas Gregor450f00842009-09-25 18:43:00 +00004443 // Find the function template that is better than all of the templates it
4444 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004445 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004446 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004447 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004448 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004449 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4450 FunctionTemplateDecl *Challenger
4451 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004452 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004453 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004454 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004455 Challenger)) {
4456 Best = I;
4457 BestTemplate = Challenger;
4458 }
4459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460
Douglas Gregor450f00842009-09-25 18:43:00 +00004461 // Make sure that the "best" function template is more specialized than all
4462 // of the others.
4463 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004464 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4465 FunctionTemplateDecl *Challenger
4466 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004467 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004469 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004470 BestTemplate)) {
4471 Ambiguous = true;
4472 break;
4473 }
4474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregor450f00842009-09-25 18:43:00 +00004476 if (!Ambiguous) {
4477 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004478 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004479 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004480
Douglas Gregor450f00842009-09-25 18:43:00 +00004481 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004482 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004483 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004484
Richard Smithb875c432013-05-04 01:51:08 +00004485 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004486 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4487 PartialDiagnostic PD = CandidateDiag;
4488 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004489 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004490 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004491 if (!TargetType.isNull())
4492 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4493 TargetType);
4494 Diag((*I)->getLocation(), PD);
4495 }
Richard Smithb875c432013-05-04 01:51:08 +00004496 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004497
John McCall58cc69d2010-01-27 01:50:18 +00004498 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004499}
4500
Douglas Gregorbe999392009-09-15 16:23:51 +00004501/// \brief Returns the more specialized class template partial specialization
4502/// according to the rules of partial ordering of class template partial
4503/// specializations (C++ [temp.class.order]).
4504///
4505/// \param PS1 the first class template partial specialization
4506///
4507/// \param PS2 the second class template partial specialization
4508///
4509/// \returns the more specialized class template partial specialization. If
4510/// neither partial specialization is more specialized, returns NULL.
4511ClassTemplatePartialSpecializationDecl *
4512Sema::getMoreSpecializedPartialSpecialization(
4513 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004514 ClassTemplatePartialSpecializationDecl *PS2,
4515 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004516 // C++ [temp.class.order]p1:
4517 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518 // specialized as the second if, given the following rewrite to two
4519 // function templates, the first function template is at least as
4520 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004521 // templates (14.6.6.2):
4522 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523 // first partial specialization and has a single function parameter
4524 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004525 // arguments of the first partial specialization, and
4526 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527 // second partial specialization and has a single function parameter
4528 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004529 // arguments of the second partial specialization.
4530 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004531 // Rather than synthesize function templates, we merely perform the
4532 // equivalent partial ordering by performing deduction directly on
4533 // the template arguments of the class template partial
4534 // specializations. This computation is slightly simpler than the
4535 // general problem of function template partial ordering, because
4536 // class template partial specializations are more constrained. We
4537 // know that every template parameter is deducible from the class
4538 // template partial specialization's template arguments, for
4539 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004540 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004541 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004542
4543 QualType PT1 = PS1->getInjectedSpecializationType();
4544 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545
Douglas Gregorbe999392009-09-15 16:23:51 +00004546 // Determine whether PS1 is at least as specialized as PS2
4547 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004548 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4549 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004550 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004551 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004552 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004553 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004554 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004555 Better1 = !::FinishTemplateArgumentDeduction(
4556 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4557 }
4558
4559 // Determine whether PS2 is at least as specialized as PS1
4560 Deduced.clear();
4561 Deduced.resize(PS1->getTemplateParameters()->size());
4562 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4563 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004564 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004565 if (Better2) {
4566 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4567 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004568 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004569 Better2 = !::FinishTemplateArgumentDeduction(
4570 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4571 }
4572
4573 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004574 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004575
4576 return Better1 ? PS1 : PS2;
4577}
4578
Larisse Voufo30616382013-08-23 22:21:36 +00004579/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4580/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4581/// VarTemplate(Partial)SpecializationDecl with a new data
4582/// structure Template(Partial)SpecializationDecl, and
4583/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004584VarTemplatePartialSpecializationDecl *
4585Sema::getMoreSpecializedPartialSpecialization(
4586 VarTemplatePartialSpecializationDecl *PS1,
4587 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4588 SmallVector<DeducedTemplateArgument, 4> Deduced;
4589 TemplateDeductionInfo Info(Loc);
4590
Richard Smithf04fd0b2013-12-12 23:14:16 +00004591 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004592 "the partial specializations being compared should specialize"
4593 " the same template.");
4594 TemplateName Name(PS1->getSpecializedTemplate());
4595 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4596 QualType PT1 = Context.getTemplateSpecializationType(
4597 CanonTemplate, PS1->getTemplateArgs().data(),
4598 PS1->getTemplateArgs().size());
4599 QualType PT2 = Context.getTemplateSpecializationType(
4600 CanonTemplate, PS2->getTemplateArgs().data(),
4601 PS2->getTemplateArgs().size());
4602
4603 // Determine whether PS1 is at least as specialized as PS2
4604 Deduced.resize(PS2->getTemplateParameters()->size());
4605 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4606 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004607 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004608 if (Better1) {
4609 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4610 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004611 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4613 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004614 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616
Douglas Gregorbe999392009-09-15 16:23:51 +00004617 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004618 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004619 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004620 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4621 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004622 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004623 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004624 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004625 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004626 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4628 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004629 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004630 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004631
Douglas Gregorbe999392009-09-15 16:23:51 +00004632 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004633 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004634
Douglas Gregorbe999392009-09-15 16:23:51 +00004635 return Better1? PS1 : PS2;
4636}
4637
Mike Stump11289f42009-09-09 15:08:12 +00004638static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004639MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004640 const TemplateArgument &TemplateArg,
4641 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004642 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004643 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004644
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004645/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004646/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004647static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004648MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004649 const Expr *E,
4650 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004651 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004652 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004653 // We can deduce from a pack expansion.
4654 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4655 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656
Richard Smith34349002012-07-09 03:07:20 +00004657 // Skip through any implicit casts we added while type-checking, and any
4658 // substitutions performed by template alias expansion.
4659 while (1) {
4660 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4661 E = ICE->getSubExpr();
4662 else if (const SubstNonTypeTemplateParmExpr *Subst =
4663 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4664 E = Subst->getReplacement();
4665 else
4666 break;
4667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668
4669 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004670 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004671 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004672 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004673 return;
4674
Mike Stump11289f42009-09-09 15:08:12 +00004675 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004676 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4677 if (!NTTP)
4678 return;
4679
Douglas Gregor21610382009-10-29 00:04:11 +00004680 if (NTTP->getDepth() == Depth)
4681 Used[NTTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004682}
4683
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004684/// \brief Mark the template parameters that are used by the given
4685/// nested name specifier.
4686static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004687MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004688 NestedNameSpecifier *NNS,
4689 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004690 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004691 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004692 if (!NNS)
4693 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004694
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004695 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004696 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004697 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004698 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004699}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004701/// \brief Mark the template parameters that are used by the given
4702/// template name.
4703static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004704MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004705 TemplateName Name,
4706 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004707 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004708 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004709 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4710 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004711 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4712 if (TTP->getDepth() == Depth)
4713 Used[TTP->getIndex()] = true;
4714 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004715 return;
4716 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004717
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004718 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004719 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004720 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004721 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004722 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004723 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004724}
4725
4726/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004727/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004728static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004729MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004730 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004731 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004732 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004733 if (T.isNull())
4734 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735
Douglas Gregor91772d12009-06-13 00:26:55 +00004736 // Non-dependent types have nothing deducible
4737 if (!T->isDependentType())
4738 return;
4739
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004740 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004741 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004742 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004743 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004744 cast<PointerType>(T)->getPointeeType(),
4745 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004746 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004747 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004748 break;
4749
4750 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004751 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004752 cast<BlockPointerType>(T)->getPointeeType(),
4753 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004754 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004755 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004756 break;
4757
4758 case Type::LValueReference:
4759 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004760 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004761 cast<ReferenceType>(T)->getPointeeType(),
4762 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004763 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004764 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004765 break;
4766
4767 case Type::MemberPointer: {
4768 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004769 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004770 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004771 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004772 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004773 break;
4774 }
4775
4776 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004777 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004778 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004779 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004780 // Fall through to check the element type
4781
4782 case Type::ConstantArray:
4783 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004784 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004785 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004786 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004787 break;
4788
4789 case Type::Vector:
4790 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004791 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004792 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004793 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004794 break;
4795
Douglas Gregor758a8692009-06-17 21:51:59 +00004796 case Type::DependentSizedExtVector: {
4797 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004798 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004799 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004800 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004801 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004802 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004803 break;
4804 }
4805
Douglas Gregor91772d12009-06-13 00:26:55 +00004806 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004807 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004808 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4809 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004810 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4811 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004812 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004813 break;
4814 }
4815
Douglas Gregor21610382009-10-29 00:04:11 +00004816 case Type::TemplateTypeParm: {
4817 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4818 if (TTP->getDepth() == Depth)
4819 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004820 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004821 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004822
Douglas Gregorfb322d82011-01-14 05:11:40 +00004823 case Type::SubstTemplateTypeParmPack: {
4824 const SubstTemplateTypeParmPackType *Subst
4825 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004826 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004827 QualType(Subst->getReplacedParameter(), 0),
4828 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004829 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004830 OnlyDeduced, Depth, Used);
4831 break;
4832 }
4833
John McCall2408e322010-04-27 00:57:59 +00004834 case Type::InjectedClassName:
4835 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4836 // fall through
4837
Douglas Gregor91772d12009-06-13 00:26:55 +00004838 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004839 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004840 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004841 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004842 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004843
Douglas Gregord0ad2942010-12-23 01:24:45 +00004844 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004845 // If the template argument list of P contains a pack expansion that is
4846 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004847 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004849 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4850 break;
4851
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004852 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004853 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004854 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004855 break;
4856 }
4857
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004858 case Type::Complex:
4859 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004860 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004861 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004862 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004863 break;
4864
Eli Friedman0dfb8892011-10-06 23:00:33 +00004865 case Type::Atomic:
4866 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004867 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004868 cast<AtomicType>(T)->getValueType(),
4869 OnlyDeduced, Depth, Used);
4870 break;
4871
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004872 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004873 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004874 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004875 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004876 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004877 break;
4878
John McCallc392f372010-06-11 00:33:02 +00004879 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004880 // C++14 [temp.deduct.type]p5:
4881 // The non-deduced contexts are:
4882 // -- The nested-name-specifier of a type that was specified using a
4883 // qualified-id
4884 //
4885 // C++14 [temp.deduct.type]p6:
4886 // When a type name is specified in a way that includes a non-deduced
4887 // context, all of the types that comprise that type name are also
4888 // non-deduced.
4889 if (OnlyDeduced)
4890 break;
4891
John McCallc392f372010-06-11 00:33:02 +00004892 const DependentTemplateSpecializationType *Spec
4893 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004894
Richard Smith50d5b972015-12-30 20:56:05 +00004895 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4896 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004897
John McCallc392f372010-06-11 00:33:02 +00004898 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004899 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004900 Used);
4901 break;
4902 }
4903
John McCallbd8d9bd2010-03-01 23:49:17 +00004904 case Type::TypeOf:
4905 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004906 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004907 cast<TypeOfType>(T)->getUnderlyingType(),
4908 OnlyDeduced, Depth, Used);
4909 break;
4910
4911 case Type::TypeOfExpr:
4912 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004913 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004914 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4915 OnlyDeduced, Depth, Used);
4916 break;
4917
4918 case Type::Decltype:
4919 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004920 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004921 cast<DecltypeType>(T)->getUnderlyingExpr(),
4922 OnlyDeduced, Depth, Used);
4923 break;
4924
Alexis Hunte852b102011-05-24 22:41:36 +00004925 case Type::UnaryTransform:
4926 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004927 MarkUsedTemplateParameters(Ctx,
Alexis Hunte852b102011-05-24 22:41:36 +00004928 cast<UnaryTransformType>(T)->getUnderlyingType(),
4929 OnlyDeduced, Depth, Used);
4930 break;
4931
Douglas Gregord2fa7662010-12-20 02:24:11 +00004932 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004933 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004934 cast<PackExpansionType>(T)->getPattern(),
4935 OnlyDeduced, Depth, Used);
4936 break;
4937
Richard Smith30482bc2011-02-20 03:19:35 +00004938 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004939 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004940 cast<AutoType>(T)->getDeducedType(),
4941 OnlyDeduced, Depth, Used);
4942
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004943 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004944 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004945 case Type::VariableArray:
4946 case Type::FunctionNoProto:
4947 case Type::Record:
4948 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004949 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004950 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004951 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004952 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00004953 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00004954#define TYPE(Class, Base)
4955#define ABSTRACT_TYPE(Class, Base)
4956#define DEPENDENT_TYPE(Class, Base)
4957#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4958#include "clang/AST/TypeNodes.def"
4959 break;
4960 }
4961}
4962
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004963/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004964/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004965static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004966MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004967 const TemplateArgument &TemplateArg,
4968 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004969 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004970 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004971 switch (TemplateArg.getKind()) {
4972 case TemplateArgument::Null:
4973 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004974 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004975 break;
Mike Stump11289f42009-09-09 15:08:12 +00004976
Eli Friedmanb826a002012-09-26 02:36:12 +00004977 case TemplateArgument::NullPtr:
4978 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4979 Depth, Used);
4980 break;
4981
Douglas Gregor91772d12009-06-13 00:26:55 +00004982 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004983 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004984 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004985 break;
4986
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004987 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004988 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004989 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004990 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004991 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004992 break;
4993
4994 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004995 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004996 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004997 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998
Anders Carlssonbc343912009-06-15 17:04:53 +00004999 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005000 for (const auto &P : TemplateArg.pack_elements())
5001 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005002 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005003 }
5004}
5005
James Dennett41725122012-06-22 10:16:05 +00005006/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005007/// template argument list.
5008///
5009/// \param TemplateArgs the template argument list from which template
5010/// parameters will be deduced.
5011///
James Dennett41725122012-06-22 10:16:05 +00005012/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005013/// to indicate when the corresponding template parameter will be
5014/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005015void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005016Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005017 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005018 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005019 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005020 // If the template argument list of P contains a pack expansion that is not
5021 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005022 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005024 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5025 return;
5026
Douglas Gregor91772d12009-06-13 00:26:55 +00005027 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005028 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005029 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005030}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005031
5032/// \brief Marks all of the template parameters that will be deduced by a
5033/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005034void Sema::MarkDeducedTemplateParameters(
5035 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5036 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005037 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005038 = FunctionTemplate->getTemplateParameters();
5039 Deduced.clear();
5040 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
Douglas Gregorce23bae2009-09-18 23:21:38 +00005042 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5043 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005044 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005045 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005046}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005047
5048bool hasDeducibleTemplateParameters(Sema &S,
5049 FunctionTemplateDecl *FunctionTemplate,
5050 QualType T) {
5051 if (!T->isDependentType())
5052 return false;
5053
5054 TemplateParameterList *TemplateParams
5055 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005056 llvm::SmallBitVector Deduced(TemplateParams->size());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005057 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005058 Deduced);
5059
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005060 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005061}