blob: 2aad3bc249a0f5f3468b19fb77bbb763f9aa9d7c [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 Smith5f274382016-09-28 23:55:27 +0000103 bool PartialOrdering = false,
104 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000105
106static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000107DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000108 ArrayRef<TemplateArgument> Params,
109 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000110 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000111 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
112 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000113
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000114/// \brief If the given expression is of a form that permits the deduction
115/// of a non-type template parameter, return the declaration of that
116/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000117static NonTypeTemplateParmDecl *
118getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000119 // If we are within an alias template, the expression may have undergone
120 // any number of parameter substitutions already.
121 while (1) {
122 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
123 E = IC->getSubExpr();
124 else if (SubstNonTypeTemplateParmExpr *Subst =
125 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
126 E = Subst->getReplacement();
127 else
128 break;
129 }
Mike Stump11289f42009-09-09 15:08:12 +0000130
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000131 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000132 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
133 if (NTTP->getDepth() == Info.getDeducedDepth())
134 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000135
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000137}
138
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000139/// \brief Determine whether two declaration pointers refer to the same
140/// declaration.
141static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000142 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
143 X = NX->getUnderlyingDecl();
144 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
145 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000146
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000147 return X->getCanonicalDecl() == Y->getCanonicalDecl();
148}
149
150/// \brief Verify that the given, deduced template arguments are compatible.
151///
152/// \returns The deduced template argument, or a NULL template argument if
153/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000154static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000155checkDeducedTemplateArguments(ASTContext &Context,
156 const DeducedTemplateArgument &X,
157 const DeducedTemplateArgument &Y) {
158 // We have no deduction for one or both of the arguments; they're compatible.
159 if (X.isNull())
160 return Y;
161 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000162 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000163
Richard Smith593d6a12016-12-23 01:30:39 +0000164 // If we have two non-type template argument values deduced for the same
165 // parameter, they must both match the type of the parameter, and thus must
166 // match each other's type. As we're only keeping one of them, we must check
167 // for that now. The exception is that if either was deduced from an array
168 // bound, the type is permitted to differ.
169 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
170 QualType XType = X.getNonTypeTemplateArgumentType();
171 if (!XType.isNull()) {
172 QualType YType = Y.getNonTypeTemplateArgumentType();
173 if (YType.isNull() || !Context.hasSameType(XType, YType))
174 return DeducedTemplateArgument();
175 }
176 }
177
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000178 switch (X.getKind()) {
179 case TemplateArgument::Null:
180 llvm_unreachable("Non-deduced template arguments handled above");
181
182 case TemplateArgument::Type:
183 // If two template type arguments have the same type, they're compatible.
184 if (Y.getKind() == TemplateArgument::Type &&
185 Context.hasSameType(X.getAsType(), Y.getAsType()))
186 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000187
Richard Smith5f274382016-09-28 23:55:27 +0000188 // If one of the two arguments was deduced from an array bound, the other
189 // supersedes it.
190 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
191 return X.wasDeducedFromArrayBound() ? Y : X;
192
193 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000194 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000196 case TemplateArgument::Integral:
197 // If we deduced a constant in one case and either a dependent expression or
198 // declaration in another case, keep the integral constant.
199 // If both are integral constants with the same value, keep that value.
200 if (Y.getKind() == TemplateArgument::Expression ||
201 Y.getKind() == TemplateArgument::Declaration ||
202 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000203 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000204 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000205
206 // All other combinations are incompatible.
207 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000208
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000209 case TemplateArgument::Template:
210 if (Y.getKind() == TemplateArgument::Template &&
211 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
212 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000213
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000214 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000215 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000216
217 case TemplateArgument::TemplateExpansion:
218 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000220 Y.getAsTemplateOrTemplatePattern()))
221 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000222
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000223 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000225
Richard Smith593d6a12016-12-23 01:30:39 +0000226 case TemplateArgument::Expression: {
227 if (Y.getKind() != TemplateArgument::Expression)
228 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000229
Richard Smith593d6a12016-12-23 01:30:39 +0000230 // Compare the expressions for equality
231 llvm::FoldingSetNodeID ID1, ID2;
232 X.getAsExpr()->Profile(ID1, Context, true);
233 Y.getAsExpr()->Profile(ID2, Context, true);
234 if (ID1 == ID2)
235 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Richard Smith593d6a12016-12-23 01:30:39 +0000237 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000238 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000240
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000241 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000242 assert(!X.wasDeducedFromArrayBound());
243
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000244 // If we deduced a declaration and a dependent expression, keep the
245 // declaration.
246 if (Y.getKind() == TemplateArgument::Expression)
247 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000248
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000249 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000250 // integral constant and whichever type did not come from an array
251 // bound.
252 if (Y.getKind() == TemplateArgument::Integral) {
253 if (Y.wasDeducedFromArrayBound())
254 return TemplateArgument(Context, Y.getAsIntegral(),
255 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000256 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000258
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000259 // If we deduced two declarations, make sure they they refer to the
260 // same declaration.
261 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000262 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000263 return X;
264
265 // All other combinations are incompatible.
266 return DeducedTemplateArgument();
267
268 case TemplateArgument::NullPtr:
269 // If we deduced a null pointer and a dependent expression, keep the
270 // null pointer.
271 if (Y.getKind() == TemplateArgument::Expression)
272 return X;
273
274 // If we deduced a null pointer and an integral constant, keep the
275 // integral constant.
276 if (Y.getKind() == TemplateArgument::Integral)
277 return Y;
278
Richard Smith593d6a12016-12-23 01:30:39 +0000279 // If we deduced two null pointers, they are the same.
280 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000281 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000283 // All other combinations are incompatible.
284 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000285
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000286 case TemplateArgument::Pack:
287 if (Y.getKind() != TemplateArgument::Pack ||
288 X.pack_size() != Y.pack_size())
289 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290
291 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000292 XAEnd = X.pack_end(),
293 YA = Y.pack_begin();
294 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000295 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000296 if (checkDeducedTemplateArguments(Context,
297 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000298 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
299 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000300 return DeducedTemplateArgument();
301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000302
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000303 return X;
304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305
David Blaikiee4d798f2012-01-20 21:50:17 +0000306 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307}
308
Mike Stump11289f42009-09-09 15:08:12 +0000309/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000310/// as the given deduced template argument. All non-type template parameter
311/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000312static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000313 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000314 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
315 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000316 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000317 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
318 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000319
Richard Smith5d102892016-12-27 03:59:58 +0000320 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
321 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000322 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000323 Info.Param = NTTP;
324 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000325 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000326 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000328
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000329 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000330 return S.getLangOpts().CPlusPlus1z
331 ? DeduceTemplateArgumentsByTypeMatch(
332 S, TemplateParams, NTTP->getType(), ValueType, Info, Deduced,
333 TDF_ParamWithReferenceType | TDF_SkipNonDependent,
334 /*PartialOrdering=*/false,
Richard Smith5d102892016-12-27 03:59:58 +0000335 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound())
Richard Smith5f274382016-09-28 23:55:27 +0000336 : Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000337}
338
Mike Stump11289f42009-09-09 15:08:12 +0000339/// \brief Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000340/// from the given integral constant.
341static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
342 Sema &S, TemplateParameterList *TemplateParams,
343 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
344 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
345 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
346 return DeduceNonTypeTemplateArgument(
347 S, TemplateParams, NTTP,
348 DeducedTemplateArgument(S.Context, Value, ValueType,
349 DeducedFromArrayBound),
350 ValueType, Info, Deduced);
351}
352
353/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000354/// from the given null pointer template argument type.
355static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000356 Sema &S, TemplateParameterList *TemplateParams,
357 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000358 TemplateDeductionInfo &Info,
359 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
360 Expr *Value =
361 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
362 S.Context.NullPtrTy, NTTP->getLocation()),
363 NullPtrType, CK_NullToPointer)
364 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000365 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
366 DeducedTemplateArgument(Value),
367 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000368}
369
370/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000371/// from the given type- or value-dependent expression.
372///
373/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000374static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
375 Sema &S, TemplateParameterList *TemplateParams,
376 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
377 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000378 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
379 "Expression template argument must be type- or value-dependent.");
Richard Smith5d102892016-12-27 03:59:58 +0000380 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
381 DeducedTemplateArgument(Value),
382 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000383}
384
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000385/// \brief Deduce the value of the given non-type template parameter
386/// from the given declaration.
387///
388/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000389static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
390 Sema &S, TemplateParameterList *TemplateParams,
391 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
392 TemplateDeductionInfo &Info,
393 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000394 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000395 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000396 return DeduceNonTypeTemplateArgument(
397 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000398}
399
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000400static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000401DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000402 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000403 TemplateName Param,
404 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000405 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000406 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000407 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000408 if (!ParamDecl) {
409 // The parameter type is dependent and is not a template template parameter,
410 // so there is nothing that we can deduce.
411 return Sema::TDK_Success;
412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000413
Douglas Gregoradee3e32009-11-11 23:06:43 +0000414 if (TemplateTemplateParmDecl *TempParam
415 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000416 // If we're not deducing at this depth, there's nothing to deduce.
417 if (TempParam->getDepth() != Info.getDeducedDepth())
418 return Sema::TDK_Success;
419
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000420 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000421 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000422 Deduced[TempParam->getIndex()],
423 NewDeduced);
424 if (Result.isNull()) {
425 Info.Param = TempParam;
426 Info.FirstArg = Deduced[TempParam->getIndex()];
427 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000429 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000430
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000431 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000432 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregoradee3e32009-11-11 23:06:43 +0000435 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000436 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000437 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000438
Douglas Gregoradee3e32009-11-11 23:06:43 +0000439 // Mismatch of non-dependent template parameter to argument.
440 Info.FirstArg = TemplateArgument(Param);
441 Info.SecondArg = TemplateArgument(Arg);
442 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000443}
444
Mike Stump11289f42009-09-09 15:08:12 +0000445/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000446/// type (which is a template-id) with the template argument type.
447///
Chandler Carruthc1263112010-02-07 21:33:28 +0000448/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000449///
450/// \param TemplateParams the template parameters that we are deducing
451///
452/// \param Param the parameter type
453///
454/// \param Arg the argument type
455///
456/// \param Info information about the template argument deduction itself
457///
458/// \param Deduced the deduced template arguments
459///
460/// \returns the result of template argument deduction so far. Note that a
461/// "success" result means that template argument deduction has not yet failed,
462/// but it may still fail, later, for other reasons.
463static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000464DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000465 TemplateParameterList *TemplateParams,
466 const TemplateSpecializationType *Param,
467 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000468 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000469 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000470 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000471
Douglas Gregore81f3e72009-07-07 23:09:34 +0000472 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000473 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000474 = dyn_cast<TemplateSpecializationType>(Arg)) {
475 // Perform template argument deduction for the template name.
476 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000477 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000478 Param->getTemplateName(),
479 SpecArg->getTemplateName(),
480 Info, Deduced))
481 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000482
Mike Stump11289f42009-09-09 15:08:12 +0000483
Douglas Gregore81f3e72009-07-07 23:09:34 +0000484 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000485 // argument. Ignore any missing/extra arguments, since they could be
486 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000487 return DeduceTemplateArguments(S, TemplateParams,
488 Param->template_arguments(),
489 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000490 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000491 }
Mike Stump11289f42009-09-09 15:08:12 +0000492
Douglas Gregore81f3e72009-07-07 23:09:34 +0000493 // If the argument type is a class template specialization, we
494 // perform template argument deduction using its template
495 // arguments.
496 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000497 if (!RecordArg) {
498 Info.FirstArg = TemplateArgument(QualType(Param, 0));
499 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000500 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000501 }
Mike Stump11289f42009-09-09 15:08:12 +0000502
503 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000504 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000505 if (!SpecArg) {
506 Info.FirstArg = TemplateArgument(QualType(Param, 0));
507 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000508 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000509 }
Mike Stump11289f42009-09-09 15:08:12 +0000510
Douglas Gregore81f3e72009-07-07 23:09:34 +0000511 // Perform template argument deduction for the template name.
512 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000513 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000514 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000515 Param->getTemplateName(),
516 TemplateName(SpecArg->getSpecializedTemplate()),
517 Info, Deduced))
518 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000519
Douglas Gregor7baabef2010-12-22 18:17:10 +0000520 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000521 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
522 SpecArg->getTemplateArgs().asArray(), Info,
523 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000524}
525
John McCall08569062010-08-28 22:14:41 +0000526/// \brief Determines whether the given type is an opaque type that
527/// might be more qualified when instantiated.
528static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
529 switch (T->getTypeClass()) {
530 case Type::TypeOfExpr:
531 case Type::TypeOf:
532 case Type::DependentName:
533 case Type::Decltype:
534 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000535 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000536 return true;
537
538 case Type::ConstantArray:
539 case Type::IncompleteArray:
540 case Type::VariableArray:
541 case Type::DependentSizedArray:
542 return IsPossiblyOpaquelyQualifiedType(
543 cast<ArrayType>(T)->getElementType());
544
545 default:
546 return false;
547 }
548}
549
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000550/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000552getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000553 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
554 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555
Douglas Gregor5499af42011-01-05 23:12:31 +0000556 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
557 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor5499af42011-01-05 23:12:31 +0000559 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
560 return std::make_pair(TTP->getDepth(), TTP->getIndex());
561}
562
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000563/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000564static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000565getDepthAndIndex(UnexpandedParameterPack UPP) {
566 if (const TemplateTypeParmType *TTP
567 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
568 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000569
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000570 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
571}
572
Douglas Gregor5499af42011-01-05 23:12:31 +0000573/// \brief Helper function to build a TemplateParameter when we don't
574/// know its type statically.
575static TemplateParameter makeTemplateParameter(Decl *D) {
576 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
577 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000578 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000579 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor5499af42011-01-05 23:12:31 +0000581 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
582}
583
Richard Smith0a80d572014-05-29 01:12:14 +0000584/// A pack that we're currently deducing.
585struct clang::DeducedPack {
586 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000587
Richard Smith0a80d572014-05-29 01:12:14 +0000588 // The index of the pack.
589 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000590
Richard Smith0a80d572014-05-29 01:12:14 +0000591 // The old value of the pack before we started deducing it.
592 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000593
Richard Smith0a80d572014-05-29 01:12:14 +0000594 // A deferred value of this pack from an inner deduction, that couldn't be
595 // deduced because this deduction hadn't happened yet.
596 DeducedTemplateArgument DeferredDeduction;
597
598 // The new value of the pack.
599 SmallVector<DeducedTemplateArgument, 4> New;
600
601 // The outer deduction for this pack, if any.
602 DeducedPack *Outer;
603};
604
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000605namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000606/// A scope in which we're performing pack deduction.
607class PackDeductionScope {
608public:
609 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
610 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
611 TemplateDeductionInfo &Info, TemplateArgument Pattern)
612 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
613 // Compute the set of template parameter indices that correspond to
614 // parameter packs expanded by the pack expansion.
615 {
616 llvm::SmallBitVector SawIndices(TemplateParams->size());
617 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
618 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
619 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
620 unsigned Depth, Index;
621 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
Richard Smith87d263e2016-12-25 08:05:23 +0000622 if (Depth == Info.getDeducedDepth() && !SawIndices[Index]) {
Richard Smith0a80d572014-05-29 01:12:14 +0000623 SawIndices[Index] = true;
624
625 // Save the deduced template argument for the parameter pack expanded
626 // by this pack expansion, then clear out the deduction.
627 DeducedPack Pack(Index);
628 Pack.Saved = Deduced[Index];
629 Deduced[Index] = TemplateArgument();
630
631 Packs.push_back(Pack);
632 }
633 }
634 }
635 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
636
637 for (auto &Pack : Packs) {
638 if (Info.PendingDeducedPacks.size() > Pack.Index)
639 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
640 else
641 Info.PendingDeducedPacks.resize(Pack.Index + 1);
642 Info.PendingDeducedPacks[Pack.Index] = &Pack;
643
644 if (S.CurrentInstantiationScope) {
645 // If the template argument pack was explicitly specified, add that to
646 // the set of deduced arguments.
647 const TemplateArgument *ExplicitArgs;
648 unsigned NumExplicitArgs;
649 NamedDecl *PartiallySubstitutedPack =
650 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
651 &ExplicitArgs, &NumExplicitArgs);
652 if (PartiallySubstitutedPack &&
Richard Smith87d263e2016-12-25 08:05:23 +0000653 getDepthAndIndex(PartiallySubstitutedPack) ==
654 std::make_pair(Info.getDeducedDepth(), Pack.Index))
Richard Smith0a80d572014-05-29 01:12:14 +0000655 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
656 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000657 }
658 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000659
Richard Smith0a80d572014-05-29 01:12:14 +0000660 ~PackDeductionScope() {
661 for (auto &Pack : Packs)
662 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Richard Smith0a80d572014-05-29 01:12:14 +0000665 /// Move to deducing the next element in each pack that is being deduced.
666 void nextPackElement() {
667 // Capture the deduced template arguments for each parameter pack expanded
668 // by this pack expansion, add them to the list of arguments we've deduced
669 // for that pack, then clear out the deduced argument.
670 for (auto &Pack : Packs) {
671 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
672 if (!DeducedArg.isNull()) {
673 Pack.New.push_back(DeducedArg);
674 DeducedArg = DeducedTemplateArgument();
675 }
676 }
677 }
678
679 /// \brief Finish template argument deduction for a set of argument packs,
680 /// producing the argument packs and checking for consistency with prior
681 /// deductions.
682 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
683 // Build argument packs for each of the parameter packs expanded by this
684 // pack expansion.
685 for (auto &Pack : Packs) {
686 // Put back the old value for this pack.
687 Deduced[Pack.Index] = Pack.Saved;
688
689 // Build or find a new value for this pack.
690 DeducedTemplateArgument NewPack;
691 if (HasAnyArguments && Pack.New.empty()) {
692 if (Pack.DeferredDeduction.isNull()) {
693 // We were not able to deduce anything for this parameter pack
694 // (because it only appeared in non-deduced contexts), so just
695 // restore the saved argument pack.
696 continue;
697 }
698
699 NewPack = Pack.DeferredDeduction;
700 Pack.DeferredDeduction = TemplateArgument();
701 } else if (Pack.New.empty()) {
702 // If we deduced an empty argument pack, create it now.
703 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
704 } else {
705 TemplateArgument *ArgumentPack =
706 new (S.Context) TemplateArgument[Pack.New.size()];
707 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
708 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000709 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000710 Pack.New[0].wasDeducedFromArrayBound());
711 }
712
713 // Pick where we're going to put the merged pack.
714 DeducedTemplateArgument *Loc;
715 if (Pack.Outer) {
716 if (Pack.Outer->DeferredDeduction.isNull()) {
717 // Defer checking this pack until we have a complete pack to compare
718 // it against.
719 Pack.Outer->DeferredDeduction = NewPack;
720 continue;
721 }
722 Loc = &Pack.Outer->DeferredDeduction;
723 } else {
724 Loc = &Deduced[Pack.Index];
725 }
726
727 // Check the new pack matches any previous value.
728 DeducedTemplateArgument OldPack = *Loc;
729 DeducedTemplateArgument Result =
730 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
731
732 // If we deferred a deduction of this pack, check that one now too.
733 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
734 OldPack = Result;
735 NewPack = Pack.DeferredDeduction;
736 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
737 }
738
739 if (Result.isNull()) {
740 Info.Param =
741 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
742 Info.FirstArg = OldPack;
743 Info.SecondArg = NewPack;
744 return Sema::TDK_Inconsistent;
745 }
746
747 *Loc = Result;
748 }
749
750 return Sema::TDK_Success;
751 }
752
753private:
754 Sema &S;
755 TemplateParameterList *TemplateParams;
756 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
757 TemplateDeductionInfo &Info;
758
759 SmallVector<DeducedPack, 2> Packs;
760};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000761} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000762
Douglas Gregor5499af42011-01-05 23:12:31 +0000763/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000764/// types to the list of argument types, as in the parameter-type-lists of
765/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000766///
767/// \param S The semantic analysis object within which we are deducing
768///
769/// \param TemplateParams The template parameters that we are deducing
770///
771/// \param Params The list of parameter types
772///
773/// \param NumParams The number of types in \c Params
774///
775/// \param Args The list of argument types
776///
777/// \param NumArgs The number of types in \c Args
778///
779/// \param Info information about the template argument deduction itself
780///
781/// \param Deduced the deduced template arguments
782///
783/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
784/// how template argument deduction is performed.
785///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000786/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000788/// (C++0x [temp.deduct.partial]).
789///
Douglas Gregor5499af42011-01-05 23:12:31 +0000790/// \returns the result of template argument deduction so far. Note that a
791/// "success" result means that template argument deduction has not yet failed,
792/// but it may still fail, later, for other reasons.
793static Sema::TemplateDeductionResult
794DeduceTemplateArguments(Sema &S,
795 TemplateParameterList *TemplateParams,
796 const QualType *Params, unsigned NumParams,
797 const QualType *Args, unsigned NumArgs,
798 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000799 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000800 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000801 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000802 // Fast-path check to see if we have too many/too few arguments.
803 if (NumParams != NumArgs &&
804 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
805 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000806 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000807
Douglas Gregor5499af42011-01-05 23:12:31 +0000808 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809 // Similarly, if P has a form that contains (T), then each parameter type
810 // Pi of the respective parameter-type- list of P is compared with the
811 // corresponding parameter type Ai of the corresponding parameter-type-list
812 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000813 unsigned ArgIdx = 0, ParamIdx = 0;
814 for (; ParamIdx != NumParams; ++ParamIdx) {
815 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000816 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000817 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
818 if (!Expansion) {
819 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregor5499af42011-01-05 23:12:31 +0000821 // Make sure we have an argument.
822 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000823 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000825 if (isa<PackExpansionType>(Args[ArgIdx])) {
826 // C++0x [temp.deduct.type]p22:
827 // If the original function parameter associated with A is a function
828 // parameter pack and the function parameter associated with P is not
829 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000830 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000832
Douglas Gregor5499af42011-01-05 23:12:31 +0000833 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000834 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
835 Params[ParamIdx], Args[ArgIdx],
836 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000837 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000838 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000839
Douglas Gregor5499af42011-01-05 23:12:31 +0000840 ++ArgIdx;
841 continue;
842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000843
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000844 // C++0x [temp.deduct.type]p5:
845 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000846 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000847 // parameter-declaration-clause.
848 if (ParamIdx + 1 < NumParams)
849 return Sema::TDK_Success;
850
Douglas Gregor5499af42011-01-05 23:12:31 +0000851 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000852 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000853 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000854 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000855 // comparison deduces template arguments for subsequent positions in the
856 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857
Douglas Gregor5499af42011-01-05 23:12:31 +0000858 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000859 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000860
Douglas Gregor5499af42011-01-05 23:12:31 +0000861 bool HasAnyArguments = false;
862 for (; ArgIdx < NumArgs; ++ArgIdx) {
863 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000864
Douglas Gregor5499af42011-01-05 23:12:31 +0000865 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000866 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000867 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
868 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000869 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000870 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000871
Richard Smith0a80d572014-05-29 01:12:14 +0000872 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874
Douglas Gregor5499af42011-01-05 23:12:31 +0000875 // Build argument packs for each of the parameter packs expanded by this
876 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000877 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000880
Douglas Gregor5499af42011-01-05 23:12:31 +0000881 // Make sure we don't have any extra arguments.
882 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000883 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000884
Douglas Gregor5499af42011-01-05 23:12:31 +0000885 return Sema::TDK_Success;
886}
887
Douglas Gregor1d684c22011-04-28 00:56:09 +0000888/// \brief Determine whether the parameter has qualifiers that are either
889/// inconsistent with or a superset of the argument's qualifiers.
890static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
891 QualType ArgType) {
892 Qualifiers ParamQs = ParamType.getQualifiers();
893 Qualifiers ArgQs = ArgType.getQualifiers();
894
895 if (ParamQs == ArgQs)
896 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000897
Douglas Gregor1d684c22011-04-28 00:56:09 +0000898 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000899 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000900 ParamQs.hasObjCGCAttr())
901 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000902
Douglas Gregor1d684c22011-04-28 00:56:09 +0000903 // Mismatched (but not missing) address spaces.
904 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
905 ParamQs.hasAddressSpace())
906 return true;
907
John McCall31168b02011-06-15 23:02:42 +0000908 // Mismatched (but not missing) Objective-C lifetime qualifiers.
909 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
910 ParamQs.hasObjCLifetime())
911 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000912
Douglas Gregor1d684c22011-04-28 00:56:09 +0000913 // CVR qualifier superset.
914 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
915 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
916 == ParamQs.getCVRQualifiers());
917}
918
Douglas Gregor19a41f12013-04-17 08:45:07 +0000919/// \brief Compare types for equality with respect to possibly compatible
920/// function types (noreturn adjustment, implicit calling conventions). If any
921/// of parameter and argument is not a function, just perform type comparison.
922///
923/// \param Param the template parameter type.
924///
925/// \param Arg the argument type.
926bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
927 CanQualType Arg) {
928 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
929 *ArgFunction = Arg->getAs<FunctionType>();
930
931 // Just compare if not functions.
932 if (!ParamFunction || !ArgFunction)
933 return Param == Arg;
934
Richard Smith3c4f8d22016-10-16 17:54:23 +0000935 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000936 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000937 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000938 return Arg == Context.getCanonicalType(AdjustedParam);
939
940 // FIXME: Compatible calling conventions.
941
942 return Param == Arg;
943}
944
Douglas Gregorcceb9752009-06-26 18:27:22 +0000945/// \brief Deduce the template arguments by comparing the parameter type and
946/// the argument type (C++ [temp.deduct.type]).
947///
Chandler Carruthc1263112010-02-07 21:33:28 +0000948/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000949///
950/// \param TemplateParams the template parameters that we are deducing
951///
952/// \param ParamIn the parameter type
953///
954/// \param ArgIn the argument type
955///
956/// \param Info information about the template argument deduction itself
957///
958/// \param Deduced the deduced template arguments
959///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000960/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000961/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000962///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000963/// \param PartialOrdering Whether we're performing template argument deduction
964/// in the context of partial ordering (C++0x [temp.deduct.partial]).
965///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000966/// \returns the result of template argument deduction so far. Note that a
967/// "success" result means that template argument deduction has not yet failed,
968/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000969static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000970DeduceTemplateArgumentsByTypeMatch(Sema &S,
971 TemplateParameterList *TemplateParams,
972 QualType ParamIn, QualType ArgIn,
973 TemplateDeductionInfo &Info,
974 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
975 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000976 bool PartialOrdering,
977 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000978 // We only want to look at the canonical types, since typedefs and
979 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +0000980 QualType Param = S.Context.getCanonicalType(ParamIn);
981 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000982
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000983 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000984 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000985 if (const PackExpansionType *ArgExpansion
986 = dyn_cast<PackExpansionType>(Arg))
987 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000988
Douglas Gregorb837ea42011-01-11 17:34:58 +0000989 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +0000990 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000991 // Before the partial ordering is done, certain transformations are
992 // performed on the types used for partial ordering:
993 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +0000994 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
995 if (ParamRef)
996 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000997
Douglas Gregorb837ea42011-01-11 17:34:58 +0000998 // - If A is a reference type, A is replaced by the type referred to.
999 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1000 if (ArgRef)
1001 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001002
Richard Smithed563c22015-02-20 04:45:22 +00001003 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1004 // C++11 [temp.deduct.partial]p9:
1005 // If, for a given type, deduction succeeds in both directions (i.e.,
1006 // the types are identical after the transformations above) and both
1007 // P and A were reference types [...]:
1008 // - if [one type] was an lvalue reference and [the other type] was
1009 // not, [the other type] is not considered to be at least as
1010 // specialized as [the first type]
1011 // - if [one type] is more cv-qualified than [the other type],
1012 // [the other type] is not considered to be at least as specialized
1013 // as [the first type]
1014 // Objective-C ARC adds:
1015 // - [one type] has non-trivial lifetime, [the other type] has
1016 // __unsafe_unretained lifetime, and the types are otherwise
1017 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001018 //
Richard Smithed563c22015-02-20 04:45:22 +00001019 // A is "considered to be at least as specialized" as P iff deduction
1020 // succeeds, so we model this as a deduction failure. Note that
1021 // [the first type] is P and [the other type] is A here; the standard
1022 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001023 Qualifiers ParamQuals = Param.getQualifiers();
1024 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001025 if ((ParamRef->isLValueReferenceType() &&
1026 !ArgRef->isLValueReferenceType()) ||
1027 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1028 (ParamQuals.hasNonTrivialObjCLifetime() &&
1029 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1030 ParamQuals.withoutObjCLifetime() ==
1031 ArgQuals.withoutObjCLifetime())) {
1032 Info.FirstArg = TemplateArgument(ParamIn);
1033 Info.SecondArg = TemplateArgument(ArgIn);
1034 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001035 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001036 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037
Richard Smithed563c22015-02-20 04:45:22 +00001038 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001039 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001040 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001041 // version of P.
1042 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001043 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001044 // version of A.
1045 Arg = Arg.getUnqualifiedType();
1046 } else {
1047 // C++0x [temp.deduct.call]p4 bullet 1:
1048 // - If the original P is a reference type, the deduced A (i.e., the type
1049 // referred to by the reference) can be more cv-qualified than the
1050 // transformed A.
1051 if (TDF & TDF_ParamWithReferenceType) {
1052 Qualifiers Quals;
1053 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1054 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001055 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001056 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001058
Douglas Gregor85f240c2011-01-25 17:19:08 +00001059 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1060 // C++0x [temp.deduct.type]p10:
1061 // If P and A are function types that originated from deduction when
1062 // taking the address of a function template (14.8.2.2) or when deducing
1063 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064 // Ai are parameters of the top-level parameter-type-list of P and A,
1065 // respectively, Pi is adjusted if it is an rvalue reference to a
1066 // cv-unqualified template parameter and Ai is an lvalue reference, in
1067 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001068 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1069 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001070 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001071 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072
Douglas Gregor85f240c2011-01-25 17:19:08 +00001073 if (const RValueReferenceType *ParamRef
1074 = Param->getAs<RValueReferenceType>()) {
1075 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1076 !ParamRef->getPointeeType().getQualifiers())
1077 if (Arg->isLValueReferenceType())
1078 Param = ParamRef->getPointeeType();
1079 }
1080 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001082
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001083 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001084 // A template type argument T, a template template argument TT or a
1085 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001086 // the following forms:
1087 //
1088 // T
1089 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001090 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001091 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001092 // Just skip any attempts to deduce from a placeholder type or a parameter
1093 // at a different depth.
1094 if (Arg->isPlaceholderType() ||
1095 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001096 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001097
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001098 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001099 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001100
Douglas Gregor60454822009-07-22 20:02:25 +00001101 // If the argument type is an array type, move the qualifiers up to the
1102 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001103 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001104 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001105 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001106 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001107 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001108 RecanonicalizeArg = true;
1109 }
1110 }
Mike Stump11289f42009-09-09 15:08:12 +00001111
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001112 // The argument type can not be less qualified than the parameter
1113 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001114 if (!(TDF & TDF_IgnoreQualifiers) &&
1115 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001116 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001117 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001118 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001119 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001120 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001121
Richard Smith87d263e2016-12-25 08:05:23 +00001122 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1123 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001124 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001125 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001126
Douglas Gregor1d684c22011-04-28 00:56:09 +00001127 // Remove any qualifiers on the parameter from the deduced type.
1128 // We checked the qualifiers for consistency above.
1129 Qualifiers DeducedQs = DeducedType.getQualifiers();
1130 Qualifiers ParamQs = Param.getQualifiers();
1131 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1132 if (ParamQs.hasObjCGCAttr())
1133 DeducedQs.removeObjCGCAttr();
1134 if (ParamQs.hasAddressSpace())
1135 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001136 if (ParamQs.hasObjCLifetime())
1137 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001138
Douglas Gregore46db902011-06-17 22:11:49 +00001139 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001140 // If template deduction would produce a lifetime qualifier on a type
1141 // that is not a lifetime type, template argument deduction fails.
1142 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1143 !DeducedType->isDependentType()) {
1144 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1145 Info.FirstArg = TemplateArgument(Param);
1146 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001147 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001148 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001149
Douglas Gregora4f2b432011-07-26 14:53:44 +00001150 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001151 // If template deduction would produce an argument type with lifetime type
1152 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001153 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001154 DeducedType->isObjCLifetimeType() &&
1155 !DeducedQs.hasObjCLifetime())
1156 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001157
Douglas Gregor1d684c22011-04-28 00:56:09 +00001158 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1159 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001160
Douglas Gregord6605db2009-07-22 21:30:48 +00001161 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001162 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001163
Richard Smith5f274382016-09-28 23:55:27 +00001164 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001166 Deduced[Index],
1167 NewDeduced);
1168 if (Result.isNull()) {
1169 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1170 Info.FirstArg = Deduced[Index];
1171 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001174
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001175 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001176 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001177 }
1178
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001179 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001180 Info.FirstArg = TemplateArgument(ParamIn);
1181 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001182
Douglas Gregorfb322d82011-01-14 05:11:40 +00001183 // If the parameter is an already-substituted template parameter
1184 // pack, do nothing: we don't know which of its arguments to look
1185 // at, so we have to wait until all of the parameter packs in this
1186 // expansion have arguments.
1187 if (isa<SubstTemplateTypeParmPackType>(Param))
1188 return Sema::TDK_Success;
1189
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001190 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001191 CanQualType CanParam = S.Context.getCanonicalType(Param);
1192 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001193 if (!(TDF & TDF_IgnoreQualifiers)) {
1194 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001195 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001196 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001197 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001198 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001199 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001200 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001201
Douglas Gregor194ea692012-03-11 03:29:50 +00001202 // If the parameter type is not dependent, there is nothing to deduce.
1203 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001204 if (!(TDF & TDF_SkipNonDependent)) {
1205 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1206 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1207 Param != Arg;
1208 if (NonDeduced) {
1209 return Sema::TDK_NonDeducedMismatch;
1210 }
1211 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001212 return Sema::TDK_Success;
1213 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001214 } else if (!Param->isDependentType()) {
1215 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1216 ArgUnqualType = CanArg.getUnqualifiedType();
1217 bool Success = (TDF & TDF_InOverloadResolution)?
1218 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1219 ArgUnqualType) :
1220 ParamUnqualType == ArgUnqualType;
1221 if (Success)
1222 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001223 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001224
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001225 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001226 // Non-canonical types cannot appear here.
1227#define NON_CANONICAL_TYPE(Class, Base) \
1228 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1229#define TYPE(Class, Base)
1230#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001231
Douglas Gregor39c02722011-06-15 16:02:29 +00001232 case Type::TemplateTypeParm:
1233 case Type::SubstTemplateTypeParmPack:
1234 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001235
1236 // These types cannot be dependent, so simply check whether the types are
1237 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001238 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001239 case Type::VariableArray:
1240 case Type::Vector:
1241 case Type::FunctionNoProto:
1242 case Type::Record:
1243 case Type::Enum:
1244 case Type::ObjCObject:
1245 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001246 case Type::ObjCObjectPointer: {
1247 if (TDF & TDF_SkipNonDependent)
1248 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001249
Douglas Gregor194ea692012-03-11 03:29:50 +00001250 if (TDF & TDF_IgnoreQualifiers) {
1251 Param = Param.getUnqualifiedType();
1252 Arg = Arg.getUnqualifiedType();
1253 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001254
Douglas Gregor194ea692012-03-11 03:29:50 +00001255 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1256 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001257
1258 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001259 case Type::Complex:
1260 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001261 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1262 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001263 ComplexArg->getElementType(),
1264 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001265
1266 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001267
1268 // _Atomic T [extension]
1269 case Type::Atomic:
1270 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001271 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001272 cast<AtomicType>(Param)->getValueType(),
1273 AtomicArg->getValueType(),
1274 Info, Deduced, TDF);
1275
1276 return Sema::TDK_NonDeducedMismatch;
1277
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001278 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001279 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001280 QualType PointeeType;
1281 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1282 PointeeType = PointerArg->getPointeeType();
1283 } else if (const ObjCObjectPointerType *PointerArg
1284 = Arg->getAs<ObjCObjectPointerType>()) {
1285 PointeeType = PointerArg->getPointeeType();
1286 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001287 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001288 }
Mike Stump11289f42009-09-09 15:08:12 +00001289
Douglas Gregorfc516c92009-06-26 23:27:24 +00001290 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001291 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1292 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001293 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001294 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001295 }
Mike Stump11289f42009-09-09 15:08:12 +00001296
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001297 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001298 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001299 const LValueReferenceType *ReferenceArg =
1300 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001301 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001302 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001303
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001304 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001305 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001306 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001307 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001308
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001309 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001310 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001311 const RValueReferenceType *ReferenceArg =
1312 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001313 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001314 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001315
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001316 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1317 cast<RValueReferenceType>(Param)->getPointeeType(),
1318 ReferenceArg->getPointeeType(),
1319 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001320 }
Mike Stump11289f42009-09-09 15:08:12 +00001321
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001322 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001323 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001324 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001325 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001326 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001327 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001328
John McCallf7332682010-08-19 00:20:19 +00001329 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001330 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1331 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1332 IncompleteArrayArg->getElementType(),
1333 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001334 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001335
1336 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001337 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001338 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001339 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001340 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001341 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001342
1343 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001344 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001345 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001346 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001347
John McCallf7332682010-08-19 00:20:19 +00001348 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001349 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1350 ConstantArrayParm->getElementType(),
1351 ConstantArrayArg->getElementType(),
1352 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001353 }
1354
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001355 // type [i]
1356 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001357 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001358 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001359 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001360
John McCallf7332682010-08-19 00:20:19 +00001361 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1362
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001363 // Check the element type of the arrays
1364 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001365 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001366 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001367 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1368 DependentArrayParm->getElementType(),
1369 ArrayArg->getElementType(),
1370 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001371 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001372
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001373 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001374 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001375 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001376 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001377 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001378
1379 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001380 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001381 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1382 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001383 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001384 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1385 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001386 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001387 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001388 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001389 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001390 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001391 if (const DependentSizedArrayType *DependentArrayArg
1392 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001393 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001394 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001395 DependentArrayArg->getSizeExpr(),
1396 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001397
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001398 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001399 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001400 }
Mike Stump11289f42009-09-09 15:08:12 +00001401
1402 // type(*)(T)
1403 // T(*)()
1404 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001405 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001406 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001407 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001408 dyn_cast<FunctionProtoType>(Arg);
1409 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001410 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001411
1412 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001413 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001414
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001415 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001416 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001417 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001418 != FunctionProtoArg->getRefQualifier() ||
1419 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001420 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001421
Anders Carlsson2128ec72009-06-08 15:19:08 +00001422 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001423 if (Sema::TemplateDeductionResult Result =
1424 DeduceTemplateArgumentsByTypeMatch(
1425 S, TemplateParams, FunctionProtoParam->getReturnType(),
1426 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001427 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001428
Alp Toker9cacbab2014-01-20 20:26:09 +00001429 return DeduceTemplateArguments(
1430 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1431 FunctionProtoParam->getNumParams(),
1432 FunctionProtoArg->param_type_begin(),
1433 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001434 }
Mike Stump11289f42009-09-09 15:08:12 +00001435
John McCalle78aac42010-03-10 03:28:59 +00001436 case Type::InjectedClassName: {
1437 // Treat a template's injected-class-name as if the template
1438 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001439 Param = cast<InjectedClassNameType>(Param)
1440 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001441 assert(isa<TemplateSpecializationType>(Param) &&
1442 "injected class name is not a template specialization type");
1443 // fall through
1444 }
1445
Douglas Gregor705c9002009-06-26 20:57:09 +00001446 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001447 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001448 // TT<T>
1449 // TT<i>
1450 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001451 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001452 const TemplateSpecializationType *SpecParam =
1453 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001454
Richard Smith9b296e32016-04-25 19:09:05 +00001455 // When Arg cannot be a derived class, we can just try to deduce template
1456 // arguments from the template-id.
1457 const RecordType *RecordT = Arg->getAs<RecordType>();
1458 if (!(TDF & TDF_DerivedClass) || !RecordT)
1459 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1460 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001461
Richard Smith9b296e32016-04-25 19:09:05 +00001462 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1463 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001464
Richard Smith9b296e32016-04-25 19:09:05 +00001465 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1466 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001467
Richard Smith9b296e32016-04-25 19:09:05 +00001468 if (Result == Sema::TDK_Success)
1469 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001470
Richard Smith9b296e32016-04-25 19:09:05 +00001471 // We cannot inspect base classes as part of deduction when the type
1472 // is incomplete, so either instantiate any templates necessary to
1473 // complete the type, or skip over it if it cannot be completed.
1474 if (!S.isCompleteType(Info.getLocation(), Arg))
1475 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001476
Richard Smith9b296e32016-04-25 19:09:05 +00001477 // C++14 [temp.deduct.call] p4b3:
1478 // If P is a class and P has the form simple-template-id, then the
1479 // transformed A can be a derived class of the deduced A. Likewise if
1480 // P is a pointer to a class of the form simple-template-id, the
1481 // transformed A can be a pointer to a derived class pointed to by the
1482 // deduced A.
1483 //
1484 // These alternatives are considered only if type deduction would
1485 // otherwise fail. If they yield more than one possible deduced A, the
1486 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001487
Faisal Vali683b0742016-05-19 02:28:21 +00001488 // Reset the incorrectly deduced argument from above.
1489 Deduced = DeducedOrig;
1490
1491 // Use data recursion to crawl through the list of base classes.
1492 // Visited contains the set of nodes we have already visited, while
1493 // ToVisit is our stack of records that we still need to visit.
1494 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1495 SmallVector<const RecordType *, 8> ToVisit;
1496 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001497 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001498 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001499 while (!ToVisit.empty()) {
1500 // Retrieve the next class in the inheritance hierarchy.
1501 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001502
Faisal Vali683b0742016-05-19 02:28:21 +00001503 // If we have already seen this type, skip it.
1504 if (!Visited.insert(NextT).second)
1505 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001506
Faisal Vali683b0742016-05-19 02:28:21 +00001507 // If this is a base class, try to perform template argument
1508 // deduction from it.
1509 if (NextT != RecordT) {
1510 TemplateDeductionInfo BaseInfo(Info.getLocation());
1511 Sema::TemplateDeductionResult BaseResult =
1512 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1513 QualType(NextT, 0), BaseInfo, Deduced);
1514
1515 // If template argument deduction for this base was successful,
1516 // note that we had some success. Otherwise, ignore any deductions
1517 // from this base class.
1518 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001519 // If we've already seen some success, then deduction fails due to
1520 // an ambiguity (temp.deduct.call p5).
1521 if (Successful)
1522 return Sema::TDK_MiscellaneousDeductionFailure;
1523
Faisal Vali683b0742016-05-19 02:28:21 +00001524 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001525 std::swap(SuccessfulDeduced, Deduced);
1526
Faisal Vali683b0742016-05-19 02:28:21 +00001527 Info.Param = BaseInfo.Param;
1528 Info.FirstArg = BaseInfo.FirstArg;
1529 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001530 }
1531
1532 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001533 }
Mike Stump11289f42009-09-09 15:08:12 +00001534
Faisal Vali683b0742016-05-19 02:28:21 +00001535 // Visit base classes
1536 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1537 for (const auto &Base : Next->bases()) {
1538 assert(Base.getType()->isRecordType() &&
1539 "Base class that isn't a record?");
1540 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1541 }
1542 }
Mike Stump11289f42009-09-09 15:08:12 +00001543
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001544 if (Successful) {
1545 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001546 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001547 }
Richard Smith9b296e32016-04-25 19:09:05 +00001548
Douglas Gregore81f3e72009-07-07 23:09:34 +00001549 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001550 }
1551
Douglas Gregor637d9982009-06-10 23:47:09 +00001552 // T type::*
1553 // T T::*
1554 // T (type::*)()
1555 // type (T::*)()
1556 // type (type::*)(T)
1557 // type (T::*)(T)
1558 // T (type::*)(T)
1559 // T (T::*)()
1560 // T (T::*)(T)
1561 case Type::MemberPointer: {
1562 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1563 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1564 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001565 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001566
David Majnemera381cda2015-11-30 20:34:28 +00001567 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1568 if (ParamPointeeType->isFunctionType())
1569 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1570 /*IsCtorOrDtor=*/false, Info.getLocation());
1571 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1572 if (ArgPointeeType->isFunctionType())
1573 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1574 /*IsCtorOrDtor=*/false, Info.getLocation());
1575
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001576 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001577 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001578 ParamPointeeType,
1579 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001580 Info, Deduced,
1581 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001582 return Result;
1583
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001584 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1585 QualType(MemPtrParam->getClass(), 0),
1586 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001587 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001588 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001589 }
1590
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001591 // (clang extension)
1592 //
Mike Stump11289f42009-09-09 15:08:12 +00001593 // type(^)(T)
1594 // T(^)()
1595 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001596 case Type::BlockPointer: {
1597 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1598 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001599
Anders Carlssona767eee2009-06-12 16:23:10 +00001600 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001601 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001602
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001603 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1604 BlockPtrParam->getPointeeType(),
1605 BlockPtrArg->getPointeeType(),
1606 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001607 }
1608
Douglas Gregor39c02722011-06-15 16:02:29 +00001609 // (clang extension)
1610 //
1611 // T __attribute__(((ext_vector_type(<integral constant>))))
1612 case Type::ExtVector: {
1613 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1614 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1615 // Make sure that the vectors have the same number of elements.
1616 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1617 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001618
Douglas Gregor39c02722011-06-15 16:02:29 +00001619 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001620 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1621 VectorParam->getElementType(),
1622 VectorArg->getElementType(),
1623 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001624 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001625
1626 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001627 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1628 // We can't check the number of elements, since the argument has a
1629 // dependent number of elements. This can only occur during partial
1630 // ordering.
1631
1632 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001633 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1634 VectorParam->getElementType(),
1635 VectorArg->getElementType(),
1636 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001637 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001638
Douglas Gregor39c02722011-06-15 16:02:29 +00001639 return Sema::TDK_NonDeducedMismatch;
1640 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001641
Douglas Gregor39c02722011-06-15 16:02:29 +00001642 // (clang extension)
1643 //
1644 // T __attribute__(((ext_vector_type(N))))
1645 case Type::DependentSizedExtVector: {
1646 const DependentSizedExtVectorType *VectorParam
1647 = cast<DependentSizedExtVectorType>(Param);
1648
1649 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1650 // Perform deduction on the element types.
1651 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001652 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1653 VectorParam->getElementType(),
1654 VectorArg->getElementType(),
1655 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001656 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001657
Douglas Gregor39c02722011-06-15 16:02:29 +00001658 // Perform deduction on the vector size, if we can.
1659 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001660 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001661 if (!NTTP)
1662 return Sema::TDK_Success;
1663
1664 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1665 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001666 // Note that we use the "array bound" rules here; just like in that
1667 // case, we don't have any particular type for the vector size, but
1668 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001669 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001670 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001671 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001672 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001673
1674 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001675 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1676 // Perform deduction on the element types.
1677 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001678 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1679 VectorParam->getElementType(),
1680 VectorArg->getElementType(),
1681 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001682 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001683
Douglas Gregor39c02722011-06-15 16:02:29 +00001684 // Perform deduction on the vector size, if we can.
1685 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001686 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001687 if (!NTTP)
1688 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001689
Richard Smith5f274382016-09-28 23:55:27 +00001690 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1691 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001692 Info, Deduced);
1693 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001694
Douglas Gregor39c02722011-06-15 16:02:29 +00001695 return Sema::TDK_NonDeducedMismatch;
1696 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001697
Douglas Gregor637d9982009-06-10 23:47:09 +00001698 case Type::TypeOfExpr:
1699 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001700 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001701 case Type::UnresolvedUsing:
1702 case Type::Decltype:
1703 case Type::UnaryTransform:
1704 case Type::Auto:
1705 case Type::DependentTemplateSpecialization:
1706 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001707 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001708 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001709 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001710 }
1711
David Blaikiee4d798f2012-01-20 21:50:17 +00001712 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001713}
1714
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001715static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001716DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001717 TemplateParameterList *TemplateParams,
1718 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001719 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001720 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001721 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001722 // If the template argument is a pack expansion, perform template argument
1723 // deduction against the pattern of that expansion. This only occurs during
1724 // partial ordering.
1725 if (Arg.isPackExpansion())
1726 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001728 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001729 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001730 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001731
1732 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001733 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001734 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1735 Param.getAsType(),
1736 Arg.getAsType(),
1737 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001738 Info.FirstArg = Param;
1739 Info.SecondArg = Arg;
1740 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001741
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001742 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001743 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001744 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001745 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001746 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001747 Info.FirstArg = Param;
1748 Info.SecondArg = Arg;
1749 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001750
1751 case TemplateArgument::TemplateExpansion:
1752 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001753
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001754 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001755 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001756 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001757 return Sema::TDK_Success;
1758
1759 Info.FirstArg = Param;
1760 Info.SecondArg = Arg;
1761 return Sema::TDK_NonDeducedMismatch;
1762
1763 case TemplateArgument::NullPtr:
1764 if (Arg.getKind() == TemplateArgument::NullPtr &&
1765 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001766 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001767
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001768 Info.FirstArg = Param;
1769 Info.SecondArg = Arg;
1770 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001771
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001772 case TemplateArgument::Integral:
1773 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001774 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001775 return Sema::TDK_Success;
1776
1777 Info.FirstArg = Param;
1778 Info.SecondArg = Arg;
1779 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001780 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001781
1782 if (Arg.getKind() == TemplateArgument::Expression) {
1783 Info.FirstArg = Param;
1784 Info.SecondArg = Arg;
1785 return Sema::TDK_NonDeducedMismatch;
1786 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001787
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001788 Info.FirstArg = Param;
1789 Info.SecondArg = Arg;
1790 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001791
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001792 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001793 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001794 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001795 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001796 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001797 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001798 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001799 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001800 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001801 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001802 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1803 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001804 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001805 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001806 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1807 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001808 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001809 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1810 Arg.getAsDecl(),
1811 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001812 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001813
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001814 Info.FirstArg = Param;
1815 Info.SecondArg = Arg;
1816 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001817 }
Mike Stump11289f42009-09-09 15:08:12 +00001818
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001819 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001820 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001821 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001822 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001823 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
David Blaikiee4d798f2012-01-20 21:50:17 +00001826 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001827}
1828
Douglas Gregor7baabef2010-12-22 18:17:10 +00001829/// \brief Determine whether there is a template argument to be used for
1830/// deduction.
1831///
1832/// This routine "expands" argument packs in-place, overriding its input
1833/// parameters so that \c Args[ArgIdx] will be the available template argument.
1834///
1835/// \returns true if there is another template argument (which will be at
1836/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001837static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1838 unsigned &ArgIdx) {
1839 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001840 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001841
Douglas Gregor7baabef2010-12-22 18:17:10 +00001842 const TemplateArgument &Arg = Args[ArgIdx];
1843 if (Arg.getKind() != TemplateArgument::Pack)
1844 return true;
1845
Richard Smith0bda5b52016-12-23 23:46:56 +00001846 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1847 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001848 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001849 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001850}
1851
Douglas Gregord0ad2942010-12-23 01:24:45 +00001852/// \brief Determine whether the given set of template arguments has a pack
1853/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001854static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1855 bool FoundPackExpansion = false;
1856 for (const auto &A : Args) {
1857 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001858 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001859
1860 if (A.getKind() == TemplateArgument::Pack)
1861 return hasPackExpansionBeforeEnd(A.pack_elements());
1862
1863 if (A.isPackExpansion())
1864 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001866
Douglas Gregord0ad2942010-12-23 01:24:45 +00001867 return false;
1868}
1869
Douglas Gregor7baabef2010-12-22 18:17:10 +00001870static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001871DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001872 ArrayRef<TemplateArgument> Params,
1873 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001874 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001875 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1876 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001877 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001878 // If the template argument list of P contains a pack expansion that is not
1879 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001880 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001881 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001882 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001883
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001884 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885 // If P has a form that contains <T> or <i>, then each argument Pi of the
1886 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001887 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001888 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001889 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001890 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001891 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001892
Douglas Gregor7baabef2010-12-22 18:17:10 +00001893 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001894 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001895 return NumberOfArgumentsMustMatch ? Sema::TDK_TooFewArguments
1896 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001897
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001898 if (Args[ArgIdx].isPackExpansion()) {
1899 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1900 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001901 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001902 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001904 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001905 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001906 = DeduceTemplateArguments(S, TemplateParams,
1907 Params[ParamIdx], Args[ArgIdx],
1908 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001909 return Result;
1910
Douglas Gregor7baabef2010-12-22 18:17:10 +00001911 // Move to the next argument.
1912 ++ArgIdx;
1913 continue;
1914 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001915
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001916 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001918 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919 // If Pi is a pack expansion, then the pattern of Pi is compared with
1920 // each remaining argument in the template argument list of A. Each
1921 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001922 // template parameter packs expanded by Pi.
1923 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001925 // FIXME: If there are no remaining arguments, we can bail out early
1926 // and set any deduced parameter packs to an empty argument pack.
1927 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928
Richard Smith0a80d572014-05-29 01:12:14 +00001929 // Prepare to deduce the packs within the pattern.
1930 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001931
1932 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001933 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001934 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001935 bool HasAnyArguments = false;
Richard Smith0bda5b52016-12-23 23:46:56 +00001936 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001937 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001939 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001941 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1942 Info, Deduced))
1943 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944
Richard Smith0a80d572014-05-29 01:12:14 +00001945 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001946 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001948 // Build argument packs for each of the parameter packs expanded by this
1949 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001950 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001951 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953
Douglas Gregor7baabef2010-12-22 18:17:10 +00001954 return Sema::TDK_Success;
1955}
1956
Mike Stump11289f42009-09-09 15:08:12 +00001957static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001958DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001959 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001960 const TemplateArgumentList &ParamList,
1961 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001962 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001963 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00001964 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
1965 ArgList.asArray(), Info, Deduced, false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001966}
1967
Douglas Gregor705c9002009-06-26 20:57:09 +00001968/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001969static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001970 const TemplateArgument &X,
1971 const TemplateArgument &Y) {
1972 if (X.getKind() != Y.getKind())
1973 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001974
Douglas Gregor705c9002009-06-26 20:57:09 +00001975 switch (X.getKind()) {
1976 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001977 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00001978
Douglas Gregor705c9002009-06-26 20:57:09 +00001979 case TemplateArgument::Type:
1980 return Context.getCanonicalType(X.getAsType()) ==
1981 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00001982
Douglas Gregor705c9002009-06-26 20:57:09 +00001983 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00001984 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00001985
1986 case TemplateArgument::NullPtr:
1987 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00001988
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001989 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001990 case TemplateArgument::TemplateExpansion:
1991 return Context.getCanonicalTemplateName(
1992 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1993 Context.getCanonicalTemplateName(
1994 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001995
Douglas Gregor705c9002009-06-26 20:57:09 +00001996 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00001997 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00001998
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001999 case TemplateArgument::Expression: {
2000 llvm::FoldingSetNodeID XID, YID;
2001 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002002 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002003 return XID == YID;
2004 }
Mike Stump11289f42009-09-09 15:08:12 +00002005
Douglas Gregor705c9002009-06-26 20:57:09 +00002006 case TemplateArgument::Pack:
2007 if (X.pack_size() != Y.pack_size())
2008 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002009
2010 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2011 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002012 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002013 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00002014 if (!isSameTemplateArg(Context, *XP, *YP))
2015 return false;
2016
2017 return true;
2018 }
2019
David Blaikiee4d798f2012-01-20 21:50:17 +00002020 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002021}
2022
Douglas Gregorca4686d2011-01-04 23:35:54 +00002023/// \brief Allocate a TemplateArgumentLoc where all locations have
2024/// been initialized to the given location.
2025///
James Dennett634962f2012-06-14 21:40:34 +00002026/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002027/// location information for.
2028///
2029/// \param NTTPType For a declaration template argument, the type of
2030/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002031/// argument. Can be null if no type sugar is available to add to the
2032/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002033///
2034/// \param Loc The source location to use for the resulting template
2035/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002036TemplateArgumentLoc
2037Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2038 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002039 switch (Arg.getKind()) {
2040 case TemplateArgument::Null:
2041 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042
Douglas Gregorca4686d2011-01-04 23:35:54 +00002043 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002044 return TemplateArgumentLoc(
2045 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002046
Douglas Gregorca4686d2011-01-04 23:35:54 +00002047 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002048 if (NTTPType.isNull())
2049 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002050 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2051 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002052 return TemplateArgumentLoc(TemplateArgument(E), E);
2053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054
Eli Friedmanb826a002012-09-26 02:36:12 +00002055 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002056 if (NTTPType.isNull())
2057 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002058 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2059 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002060 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2061 E);
2062 }
2063
Douglas Gregorca4686d2011-01-04 23:35:54 +00002064 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002065 Expr *E =
2066 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002067 return TemplateArgumentLoc(TemplateArgument(E), E);
2068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002069
Douglas Gregor9d802122011-03-02 17:09:35 +00002070 case TemplateArgument::Template:
2071 case TemplateArgument::TemplateExpansion: {
2072 NestedNameSpecifierLocBuilder Builder;
2073 TemplateName Template = Arg.getAsTemplate();
2074 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002075 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002076 else if (QualifiedTemplateName *QTN =
2077 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002078 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002079
Douglas Gregor9d802122011-03-02 17:09:35 +00002080 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002081 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002082 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002083
2084 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002085 Loc, Loc);
2086 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002087
Douglas Gregorca4686d2011-01-04 23:35:54 +00002088 case TemplateArgument::Expression:
2089 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090
Douglas Gregorca4686d2011-01-04 23:35:54 +00002091 case TemplateArgument::Pack:
2092 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094
David Blaikiee4d798f2012-01-20 21:50:17 +00002095 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002096}
2097
2098
2099/// \brief Convert the given deduced template argument and add it to the set of
2100/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002101static bool
2102ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2103 DeducedTemplateArgument Arg,
2104 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002105 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002106 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002107 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002108 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2109 unsigned ArgumentPackIndex) {
2110 // Convert the deduced template argument into a template
2111 // argument that we can check, almost as if the user had written
2112 // the template argument explicitly.
2113 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002114 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002115
2116 // Check the template argument, converting it as necessary.
2117 return S.CheckTemplateArgument(
2118 Param, ArgLoc, Template, Template->getLocation(),
2119 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002120 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002121 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2122 : Sema::CTAK_Deduced)
2123 : Sema::CTAK_Specified);
2124 };
2125
Douglas Gregorca4686d2011-01-04 23:35:54 +00002126 if (Arg.getKind() == TemplateArgument::Pack) {
2127 // This is a template argument pack, so check each of its arguments against
2128 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002129 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002130 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002131 // When converting the deduced template argument, append it to the
2132 // general output list. We need to do this so that the template argument
2133 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002134 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002135 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002136 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2137 "deduced nested pack");
2138 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002139 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002140
Douglas Gregor51bc5712011-01-05 20:52:18 +00002141 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002142 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002144
Richard Smithdf18ee92016-02-03 20:40:30 +00002145 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002146 // itself, in case that substitution fails.
2147 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002148 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002149 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002150 MultiLevelTemplateArgumentList Args(TemplateArgs);
2151
2152 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2153 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2154 NTTP, Output,
2155 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002156 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002157 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2158 NTTP->getDeclName()).isNull())
2159 return true;
2160 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2161 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2162 TTP, Output,
2163 Template->getSourceRange());
2164 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2165 return true;
2166 }
2167 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002168 }
Richard Smith37acb792016-02-03 20:15:01 +00002169
Douglas Gregorca4686d2011-01-04 23:35:54 +00002170 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002171 Output.push_back(
2172 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002173 return false;
2174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175
Richard Smith37acb792016-02-03 20:15:01 +00002176 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002177}
2178
Richard Smith1f5be4d2016-12-21 01:10:31 +00002179// FIXME: This should not be a template, but
2180// ClassTemplatePartialSpecializationDecl sadly does not derive from
2181// TemplateDecl.
2182template<typename TemplateDeclT>
2183static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002184 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002185 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2186 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2187 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2188 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2189 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2190
2191 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2192 NamedDecl *Param = TemplateParams->getParam(I);
2193
2194 if (!Deduced[I].isNull()) {
2195 if (I < NumAlreadyConverted) {
2196 // We have already fully type-checked and converted this
2197 // argument, because it was explicitly-specified. Just record the
2198 // presence of this argument.
2199 Builder.push_back(Deduced[I]);
2200 // We may have had explicitly-specified template arguments for a
2201 // template parameter pack (that may or may not have been extended
2202 // via additional deduced arguments).
2203 if (Param->isParameterPack() && CurrentInstantiationScope) {
2204 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2205 Param) {
2206 // Forget the partially-substituted pack; its substitution is now
2207 // complete.
2208 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2209 }
2210 }
2211 continue;
2212 }
2213
2214 // We have deduced this argument, so it still needs to be
2215 // checked and converted.
2216 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002217 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002218 Info.Param = makeTemplateParameter(Param);
2219 // FIXME: These template arguments are temporary. Free them!
2220 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2221 return Sema::TDK_SubstitutionFailure;
2222 }
2223
2224 continue;
2225 }
2226
2227 // C++0x [temp.arg.explicit]p3:
2228 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2229 // be deduced to an empty sequence of template arguments.
2230 // FIXME: Where did the word "trailing" come from?
2231 if (Param->isTemplateParameterPack()) {
2232 // We may have had explicitly-specified template arguments for this
2233 // template parameter pack. If so, our empty deduction extends the
2234 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2235 const TemplateArgument *ExplicitArgs;
2236 unsigned NumExplicitArgs;
2237 if (CurrentInstantiationScope &&
2238 CurrentInstantiationScope->getPartiallySubstitutedPack(
2239 &ExplicitArgs, &NumExplicitArgs) == Param) {
2240 Builder.push_back(TemplateArgument(
2241 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2242
2243 // Forget the partially-substituted pack; its substitution is now
2244 // complete.
2245 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2246 } else {
2247 // Go through the motions of checking the empty argument pack against
2248 // the parameter pack.
2249 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002250 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2251 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002252 Info.Param = makeTemplateParameter(Param);
2253 // FIXME: These template arguments are temporary. Free them!
2254 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2255 return Sema::TDK_SubstitutionFailure;
2256 }
2257 }
2258 continue;
2259 }
2260
2261 // Substitute into the default template argument, if available.
2262 bool HasDefaultArg = false;
2263 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2264 if (!TD) {
2265 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2266 return Sema::TDK_Incomplete;
2267 }
2268
2269 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2270 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2271 HasDefaultArg);
2272
2273 // If there was no default argument, deduction is incomplete.
2274 if (DefArg.getArgument().isNull()) {
2275 Info.Param = makeTemplateParameter(
2276 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2277 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2278 if (PartialOverloading) break;
2279
2280 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2281 : Sema::TDK_Incomplete;
2282 }
2283
2284 // Check whether we can actually use the default argument.
2285 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2286 TD->getSourceRange().getEnd(), 0, Builder,
2287 Sema::CTAK_Specified)) {
2288 Info.Param = makeTemplateParameter(
2289 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2290 // FIXME: These template arguments are temporary. Free them!
2291 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2292 return Sema::TDK_SubstitutionFailure;
2293 }
2294
2295 // If we get here, we successfully used the default template argument.
2296 }
2297
2298 return Sema::TDK_Success;
2299}
2300
Richard Smith0da6dc42016-12-24 16:40:51 +00002301DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2302 if (auto *DC = dyn_cast<DeclContext>(D))
2303 return DC;
2304 return D->getDeclContext();
2305}
2306
2307template<typename T> struct IsPartialSpecialization {
2308 static constexpr bool value = false;
2309};
2310template<>
2311struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2312 static constexpr bool value = true;
2313};
2314template<>
2315struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2316 static constexpr bool value = true;
2317};
2318
2319/// Complete template argument deduction for a partial specialization.
2320template <typename T>
2321static typename std::enable_if<IsPartialSpecialization<T>::value,
2322 Sema::TemplateDeductionResult>::type
2323FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002324 Sema &S, T *Partial, bool IsPartialOrdering,
2325 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002326 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2327 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002328 // Unevaluated SFINAE context.
2329 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002330 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002331
Richard Smith0da6dc42016-12-24 16:40:51 +00002332 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002333
2334 // C++ [temp.deduct.type]p2:
2335 // [...] or if any template argument remains neither deduced nor
2336 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002337 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002338 if (auto Result = ConvertDeducedTemplateArguments(
2339 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002340 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002341
Douglas Gregor684268d2010-04-29 06:21:43 +00002342 // Form the template argument list from the deduced template arguments.
2343 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002344 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002345
Douglas Gregor684268d2010-04-29 06:21:43 +00002346 Info.reset(DeducedArgumentList);
2347
2348 // Substitute the deduced template arguments into the template
2349 // arguments of the class template partial specialization, and
2350 // verify that the instantiated template arguments are both valid
2351 // and are equivalent to the template arguments originally provided
2352 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002353 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002354 auto *Template = Partial->getSpecializedTemplate();
2355 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2356 Partial->getTemplateArgsAsWritten();
2357 const TemplateArgumentLoc *PartialTemplateArgs =
2358 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002359
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002360 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2361 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002362
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002363 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002364 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2365 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2366 if (ParamIdx >= Partial->getTemplateParameters()->size())
2367 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2368
Richard Smith0da6dc42016-12-24 16:40:51 +00002369 Decl *Param = const_cast<NamedDecl *>(
2370 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002371 Info.Param = makeTemplateParameter(Param);
2372 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2373 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002374 }
2375
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002376 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002377 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2378 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002379 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002380
Richard Smith0da6dc42016-12-24 16:40:51 +00002381 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002382 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002383 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002384 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002385 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002386 Info.FirstArg = TemplateArgs[I];
2387 Info.SecondArg = InstArg;
2388 return Sema::TDK_NonDeducedMismatch;
2389 }
2390 }
2391
2392 if (Trap.hasErrorOccurred())
2393 return Sema::TDK_SubstitutionFailure;
2394
2395 return Sema::TDK_Success;
2396}
2397
Douglas Gregor170bc422009-06-12 22:31:52 +00002398/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002399/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002400/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002401Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002402Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002403 const TemplateArgumentList &TemplateArgs,
2404 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002405 if (Partial->isInvalidDecl())
2406 return TDK_Invalid;
2407
Douglas Gregor170bc422009-06-12 22:31:52 +00002408 // C++ [temp.class.spec.match]p2:
2409 // A partial specialization matches a given actual template
2410 // argument list if the template arguments of the partial
2411 // specialization can be deduced from the actual template argument
2412 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002413
2414 // Unevaluated SFINAE context.
2415 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002416 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002417
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002418 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002419 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002420 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002421 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002422 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002423 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002424 TemplateArgs, Info, Deduced))
2425 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002426
Richard Smith80934652012-07-16 01:09:10 +00002427 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002428 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2429 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002430 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002431 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002432
Douglas Gregore1416332009-06-14 08:02:22 +00002433 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002434 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002435
Richard Smith87d263e2016-12-25 08:05:23 +00002436 return ::FinishTemplateArgumentDeduction(
2437 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002438}
Douglas Gregor91772d12009-06-13 00:26:55 +00002439
Larisse Voufo39a1e502013-08-06 01:03:05 +00002440/// \brief Perform template argument deduction to determine whether
2441/// the given template arguments match the given variable template
2442/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002443Sema::TemplateDeductionResult
2444Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2445 const TemplateArgumentList &TemplateArgs,
2446 TemplateDeductionInfo &Info) {
2447 if (Partial->isInvalidDecl())
2448 return TDK_Invalid;
2449
2450 // C++ [temp.class.spec.match]p2:
2451 // A partial specialization matches a given actual template
2452 // argument list if the template arguments of the partial
2453 // specialization can be deduced from the actual template argument
2454 // list (14.8.2).
2455
2456 // Unevaluated SFINAE context.
2457 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2458 SFINAETrap Trap(*this);
2459
2460 SmallVector<DeducedTemplateArgument, 4> Deduced;
2461 Deduced.resize(Partial->getTemplateParameters()->size());
2462 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2463 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2464 TemplateArgs, Info, Deduced))
2465 return Result;
2466
2467 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002468 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2469 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002470 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002471 return TDK_InstantiationDepth;
2472
2473 if (Trap.hasErrorOccurred())
2474 return Sema::TDK_SubstitutionFailure;
2475
Richard Smith87d263e2016-12-25 08:05:23 +00002476 return ::FinishTemplateArgumentDeduction(
2477 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002478}
2479
Douglas Gregorfc516c92009-06-26 23:27:24 +00002480/// \brief Determine whether the given type T is a simple-template-id type.
2481static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002482 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002483 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002484 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002485
Douglas Gregorfc516c92009-06-26 23:27:24 +00002486 return false;
2487}
Douglas Gregor9b146582009-07-08 20:55:45 +00002488
2489/// \brief Substitute the explicitly-provided template arguments into the
2490/// given function template according to C++ [temp.arg.explicit].
2491///
2492/// \param FunctionTemplate the function template into which the explicit
2493/// template arguments will be substituted.
2494///
James Dennett634962f2012-06-14 21:40:34 +00002495/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002496/// arguments.
2497///
Mike Stump11289f42009-09-09 15:08:12 +00002498/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002499/// with the converted and checked explicit template arguments.
2500///
Mike Stump11289f42009-09-09 15:08:12 +00002501/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002502/// parameters.
2503///
2504/// \param FunctionType if non-NULL, the result type of the function template
2505/// will also be instantiated and the pointed-to value will be updated with
2506/// the instantiated function type.
2507///
2508/// \param Info if substitution fails for any reason, this object will be
2509/// populated with more information about the failure.
2510///
2511/// \returns TDK_Success if substitution was successful, or some failure
2512/// condition.
2513Sema::TemplateDeductionResult
2514Sema::SubstituteExplicitTemplateArguments(
2515 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002516 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002517 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2518 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002519 QualType *FunctionType,
2520 TemplateDeductionInfo &Info) {
2521 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2522 TemplateParameterList *TemplateParams
2523 = FunctionTemplate->getTemplateParameters();
2524
John McCall6b51f282009-11-23 01:53:49 +00002525 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002526 // No arguments to substitute; just copy over the parameter types and
2527 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002528 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002529 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002530
Douglas Gregor9b146582009-07-08 20:55:45 +00002531 if (FunctionType)
2532 *FunctionType = Function->getType();
2533 return TDK_Success;
2534 }
Mike Stump11289f42009-09-09 15:08:12 +00002535
Eli Friedman77dcc722012-02-08 03:07:05 +00002536 // Unevaluated SFINAE context.
2537 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002538 SFINAETrap Trap(*this);
2539
Douglas Gregor9b146582009-07-08 20:55:45 +00002540 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002541 // Template arguments that are present shall be specified in the
2542 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002543 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002544 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002545 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002546
2547 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002548 // explicitly-specified template arguments against this function template,
2549 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002550 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002551 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2552 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002553 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2554 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002555 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002556 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002557
Douglas Gregor9b146582009-07-08 20:55:45 +00002558 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002559 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002560 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002561 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002562 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002563 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002564 if (Index >= TemplateParams->size())
2565 Index = TemplateParams->size() - 1;
2566 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002567 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002568 }
Mike Stump11289f42009-09-09 15:08:12 +00002569
Douglas Gregor9b146582009-07-08 20:55:45 +00002570 // Form the template argument list from the explicitly-specified
2571 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002572 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002573 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002574 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002575
John McCall036855a2010-10-12 19:40:14 +00002576 // Template argument deduction and the final substitution should be
2577 // done in the context of the templated declaration. Explicit
2578 // argument substitution, on the other hand, needs to happen in the
2579 // calling context.
2580 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2581
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002582 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002583 // note that the template argument pack is partially substituted and record
2584 // the explicit template arguments. They'll be used as part of deduction
2585 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002586 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2587 const TemplateArgument &Arg = Builder[I];
2588 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002589 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002590 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002591 Arg.pack_begin(),
2592 Arg.pack_size());
2593 break;
2594 }
2595 }
2596
Richard Smith5e580292012-02-10 09:58:53 +00002597 const FunctionProtoType *Proto
2598 = Function->getType()->getAs<FunctionProtoType>();
2599 assert(Proto && "Function template does not have a prototype?");
2600
Richard Smith70b13042015-01-09 01:19:56 +00002601 // Isolate our substituted parameters from our caller.
2602 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2603
John McCallc8e321d2016-03-01 02:09:25 +00002604 ExtParameterInfoBuilder ExtParamInfos;
2605
Douglas Gregor9b146582009-07-08 20:55:45 +00002606 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002607 // explicitly-specified template arguments. If the function has a trailing
2608 // return type, substitute it after the arguments to ensure we substitute
2609 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002610 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002611 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002612 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002613 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002614 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002615 return TDK_SubstitutionFailure;
2616 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002617
Richard Smith5e580292012-02-10 09:58:53 +00002618 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002619 QualType ResultType;
2620 {
2621 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002622 // If a declaration declares a member function or member function
2623 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002624 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002625 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002626 // declarator.
2627 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002628 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002629 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2630 ThisContext = Method->getParent();
2631 ThisTypeQuals = Method->getTypeQualifiers();
2632 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002633
Douglas Gregor3024f072012-04-16 07:05:22 +00002634 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002635 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002636
2637 ResultType =
2638 SubstType(Proto->getReturnType(),
2639 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2640 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002641 if (ResultType.isNull() || Trap.hasErrorOccurred())
2642 return TDK_SubstitutionFailure;
2643 }
John McCallc8e321d2016-03-01 02:09:25 +00002644
Richard Smith5e580292012-02-10 09:58:53 +00002645 // Instantiate the types of each of the function parameters given the
2646 // explicitly-specified template arguments if we didn't do so earlier.
2647 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002648 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002649 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002650 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002651 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002652 return TDK_SubstitutionFailure;
2653
Douglas Gregor9b146582009-07-08 20:55:45 +00002654 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002655 auto EPI = Proto->getExtProtoInfo();
2656 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002657 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002658 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002659 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002660 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002661 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2662 return TDK_SubstitutionFailure;
2663 }
Mike Stump11289f42009-09-09 15:08:12 +00002664
Douglas Gregor9b146582009-07-08 20:55:45 +00002665 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002666 // Trailing template arguments that can be deduced (14.8.2) may be
2667 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002668 // template arguments can be deduced, they may all be omitted; in this
2669 // case, the empty template argument list <> itself may also be omitted.
2670 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002671 // Take all of the explicitly-specified arguments and put them into
2672 // the set of deduced template arguments. Explicitly-specified
2673 // parameter packs, however, will be set to NULL since the deduction
2674 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002675 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002676 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2677 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2678 if (Arg.getKind() == TemplateArgument::Pack)
2679 Deduced.push_back(DeducedTemplateArgument());
2680 else
2681 Deduced.push_back(Arg);
2682 }
Mike Stump11289f42009-09-09 15:08:12 +00002683
Douglas Gregor9b146582009-07-08 20:55:45 +00002684 return TDK_Success;
2685}
2686
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002687/// \brief Check whether the deduced argument type for a call to a function
2688/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002689static bool
2690CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002691 QualType DeducedA) {
2692 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002693
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002694 QualType A = OriginalArg.OriginalArgType;
2695 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002696
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002697 // Check for type equality (top-level cv-qualifiers are ignored).
2698 if (Context.hasSameUnqualifiedType(A, DeducedA))
2699 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002700
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002701 // Strip off references on the argument types; they aren't needed for
2702 // the following checks.
2703 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2704 DeducedA = DeducedARef->getPointeeType();
2705 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2706 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002707
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002708 // C++ [temp.deduct.call]p4:
2709 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002710 // - If the original P is a reference type, the deduced A (i.e., the
2711 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002712 // the transformed A.
2713 if (const ReferenceType *OriginalParamRef
2714 = OriginalParamType->getAs<ReferenceType>()) {
2715 // We don't want to keep the reference around any more.
2716 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002717
Richard Smith1be59c52016-10-22 01:32:19 +00002718 // FIXME: Resolve core issue (no number yet): if the original P is a
2719 // reference type and the transformed A is function type "noexcept F",
2720 // the deduced A can be F.
2721 QualType Tmp;
2722 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2723 return false;
2724
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002725 Qualifiers AQuals = A.getQualifiers();
2726 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002727
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002728 // Under Objective-C++ ARC, the deduced type may have implicitly
2729 // been given strong or (when dealing with a const reference)
2730 // unsafe_unretained lifetime. If so, update the original
2731 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002732 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002733 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2734 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2735 (DeducedAQuals.hasConst() &&
2736 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2737 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002738 }
2739
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002740 if (AQuals == DeducedAQuals) {
2741 // Qualifiers match; there's nothing to do.
2742 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002743 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002744 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002745 // Qualifiers are compatible, so have the argument type adopt the
2746 // deduced argument type's qualifiers as if we had performed the
2747 // qualification conversion.
2748 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2749 }
2750 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002751
2752 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002753 // type that can be converted to the deduced A via a function pointer
2754 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002755 //
Richard Smith1be59c52016-10-22 01:32:19 +00002756 // Also allow conversions which merely strip __attribute__((noreturn)) from
2757 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002758 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002759 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002760 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002761 (S.IsQualificationConversion(A, DeducedA, false,
2762 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002763 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002764 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002765
Simon Pilgrim728134c2016-08-12 11:43:57 +00002766 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002767 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002768 // [...] Likewise, if P is a pointer to a class of the form
2769 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002770 // derived class pointed to by the deduced A.
2771 if (const PointerType *OriginalParamPtr
2772 = OriginalParamType->getAs<PointerType>()) {
2773 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2774 if (const PointerType *APtr = A->getAs<PointerType>()) {
2775 if (A->getPointeeType()->isRecordType()) {
2776 OriginalParamType = OriginalParamPtr->getPointeeType();
2777 DeducedA = DeducedAPtr->getPointeeType();
2778 A = APtr->getPointeeType();
2779 }
2780 }
2781 }
2782 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002783
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002784 if (Context.hasSameUnqualifiedType(A, DeducedA))
2785 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002786
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002787 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002788 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002789 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002790
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002791 return true;
2792}
2793
Mike Stump11289f42009-09-09 15:08:12 +00002794/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002795/// checking the deduced template arguments for completeness and forming
2796/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002797///
2798/// \param OriginalCallArgs If non-NULL, the original call arguments against
2799/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002800Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002801Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002802 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002803 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002804 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002805 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002806 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2807 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002808 // Unevaluated SFINAE context.
2809 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002810 SFINAETrap Trap(*this);
2811
Douglas Gregor9b146582009-07-08 20:55:45 +00002812 // Enter a new template instantiation context while we instantiate the
2813 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002814 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002815 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2816 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002817 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2818 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002819 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002820 return TDK_InstantiationDepth;
2821
John McCalle23b8712010-04-29 01:18:58 +00002822 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002823
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002824 // C++ [temp.deduct.type]p2:
2825 // [...] or if any template argument remains neither deduced nor
2826 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002827 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002828 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002829 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002830 CurrentInstantiationScope, NumExplicitlySpecified,
2831 PartialOverloading))
2832 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002833
2834 // Form the template argument list from the deduced template arguments.
2835 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002836 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002837 Info.reset(DeducedArgumentList);
2838
Mike Stump11289f42009-09-09 15:08:12 +00002839 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002840 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002841 DeclContext *Owner = FunctionTemplate->getDeclContext();
2842 if (FunctionTemplate->getFriendObjectKind())
2843 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002844 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002845 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002846 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002847 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002848 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002849
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002850 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002851 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002852
Mike Stump11289f42009-09-09 15:08:12 +00002853 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002854 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002855 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2856 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002857 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002858
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002859 // There may have been an error that did not prevent us from constructing a
2860 // declaration. Mark the declaration invalid and return with a substitution
2861 // failure.
2862 if (Trap.hasErrorOccurred()) {
2863 Specialization->setInvalidDecl(true);
2864 return TDK_SubstitutionFailure;
2865 }
2866
Douglas Gregore65aacb2011-06-16 16:50:48 +00002867 if (OriginalCallArgs) {
2868 // C++ [temp.deduct.call]p4:
2869 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002870 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002871 // is transformed as described above). [...]
2872 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2873 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002874 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002875
Douglas Gregore65aacb2011-06-16 16:50:48 +00002876 if (ParamIdx >= Specialization->getNumParams())
2877 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002878
Douglas Gregore65aacb2011-06-16 16:50:48 +00002879 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002880 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2881 Info.FirstArg = TemplateArgument(DeducedA);
2882 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2883 Info.CallArgIndex = OriginalArg.ArgIdx;
2884 return TDK_DeducedMismatch;
2885 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002886 }
2887 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002888
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002889 // If we suppressed any diagnostics while performing template argument
2890 // deduction, and if we haven't already instantiated this declaration,
2891 // keep track of these diagnostics. They'll be emitted if this specialization
2892 // is actually used.
2893 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002894 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002895 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2896 if (Pos == SuppressedDiagnostics.end())
2897 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2898 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002899 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002900
Mike Stump11289f42009-09-09 15:08:12 +00002901 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002902}
2903
John McCall8d08b9b2010-08-27 09:08:28 +00002904/// Gets the type of a function for template-argument-deducton
2905/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002906static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002907 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002908 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002909 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002910 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002911 return QualType();
2912
John McCallc1f69982010-02-02 02:21:27 +00002913 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002914 if (Method->isInstance()) {
2915 // An instance method that's referenced in a form that doesn't
2916 // look like a member pointer is just invalid.
2917 if (!R.HasFormOfMemberPointer) return QualType();
2918
Richard Smith2a7d4812013-05-04 07:00:32 +00002919 return S.Context.getMemberPointerType(Fn->getType(),
2920 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002921 }
2922
2923 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002924 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002925}
2926
2927/// Apply the deduction rules for overload sets.
2928///
2929/// \return the null type if this argument should be treated as an
2930/// undeduced context
2931static QualType
2932ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002933 Expr *Arg, QualType ParamType,
2934 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002935
John McCall8d08b9b2010-08-27 09:08:28 +00002936 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00002937
John McCall8d08b9b2010-08-27 09:08:28 +00002938 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00002939
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002940 // C++0x [temp.deduct.call]p4
2941 unsigned TDF = 0;
2942 if (ParamWasReference)
2943 TDF |= TDF_ParamWithReferenceType;
2944 if (R.IsAddressOfOperand)
2945 TDF |= TDF_IgnoreQualifiers;
2946
John McCallc1f69982010-02-02 02:21:27 +00002947 // C++0x [temp.deduct.call]p6:
2948 // When P is a function type, pointer to function type, or pointer
2949 // to member function type:
2950
2951 if (!ParamType->isFunctionType() &&
2952 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002953 !ParamType->isMemberFunctionPointerType()) {
2954 if (Ovl->hasExplicitTemplateArgs()) {
2955 // But we can still look for an explicit specialization.
2956 if (FunctionDecl *ExplicitSpec
2957 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00002958 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002959 }
John McCallc1f69982010-02-02 02:21:27 +00002960
George Burgess IVcc2f3552016-03-19 21:51:45 +00002961 DeclAccessPair DAP;
2962 if (FunctionDecl *Viable =
2963 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
2964 return GetTypeOfFunction(S, R, Viable);
2965
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002966 return QualType();
2967 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002968
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002969 // Gather the explicit template arguments, if any.
2970 TemplateArgumentListInfo ExplicitTemplateArgs;
2971 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00002972 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00002973 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00002974 for (UnresolvedSetIterator I = Ovl->decls_begin(),
2975 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00002976 NamedDecl *D = (*I)->getUnderlyingDecl();
2977
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002978 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
2979 // - If the argument is an overload set containing one or more
2980 // function templates, the parameter is treated as a
2981 // non-deduced context.
2982 if (!Ovl->hasExplicitTemplateArgs())
2983 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002984
2985 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00002986 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00002987 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002988 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
2989 Specialization, Info))
2990 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002991
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002992 D = Specialization;
2993 }
John McCallc1f69982010-02-02 02:21:27 +00002994
2995 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00002996 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00002997 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00002998
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002999 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003001 ArgType->isFunctionType())
3002 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003
John McCallc1f69982010-02-02 02:21:27 +00003004 // - If the argument is an overload set (not containing function
3005 // templates), trial argument deduction is attempted using each
3006 // of the members of the set. If deduction succeeds for only one
3007 // of the overload set members, that member is used as the
3008 // argument value for the deduction. If deduction succeeds for
3009 // more than one member of the overload set the parameter is
3010 // treated as a non-deduced context.
3011
3012 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3013 // Type deduction is done independently for each P/A pair, and
3014 // the deduced template argument values are then combined.
3015 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003016 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003017 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003018 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003019 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003020 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3021 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003022 if (Result) continue;
3023 if (!Match.isNull()) return QualType();
3024 Match = ArgType;
3025 }
3026
3027 return Match;
3028}
3029
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003031/// described in C++ [temp.deduct.call].
3032///
3033/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003034/// argument deduction based on this P/A pair because the argument is an
3035/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003036static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3037 TemplateParameterList *TemplateParams,
3038 QualType &ParamType,
3039 QualType &ArgType,
3040 Expr *Arg,
3041 unsigned &TDF) {
3042 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003043 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003044 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003045 if (ParamType.hasQualifiers())
3046 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003047
3048 // [...] If P is a reference type, the type referred to by P is
3049 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003050 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003051 if (ParamRefType)
3052 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003053
Nathan Sidwell96090022015-01-16 15:20:14 +00003054 // Overload sets usually make this parameter an undeduced context,
3055 // but there are sometimes special circumstances. Typically
3056 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003057 if (ArgType == S.Context.OverloadTy) {
3058 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3059 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003060 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003061 if (ArgType.isNull())
3062 return true;
3063 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003064
Douglas Gregor7825bf32011-01-06 22:09:01 +00003065 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003066 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003067 if (ArgType->isIncompleteArrayType()) {
3068 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003069 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003070 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003071
Douglas Gregor7825bf32011-01-06 22:09:01 +00003072 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003073 // If P is an rvalue reference to a cv-unqualified template
3074 // parameter and the argument is an lvalue, the type "lvalue
3075 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003076 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003077 !ParamType.getQualifiers() &&
3078 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003079 Arg->isLValue())
3080 ArgType = S.Context.getLValueReferenceType(ArgType);
3081 } else {
3082 // C++ [temp.deduct.call]p2:
3083 // If P is not a reference type:
3084 // - If A is an array type, the pointer type produced by the
3085 // array-to-pointer standard conversion (4.2) is used in place of
3086 // A for type deduction; otherwise,
3087 if (ArgType->isArrayType())
3088 ArgType = S.Context.getArrayDecayedType(ArgType);
3089 // - If A is a function type, the pointer type produced by the
3090 // function-to-pointer standard conversion (4.3) is used in place
3091 // of A for type deduction; otherwise,
3092 else if (ArgType->isFunctionType())
3093 ArgType = S.Context.getPointerType(ArgType);
3094 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003095 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003096 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003097 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003098 }
3099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003100
Douglas Gregor7825bf32011-01-06 22:09:01 +00003101 // C++0x [temp.deduct.call]p4:
3102 // In general, the deduction process attempts to find template argument
3103 // values that will make the deduced A identical to A (after the type A
3104 // is transformed as described above). [...]
3105 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003106
Douglas Gregor7825bf32011-01-06 22:09:01 +00003107 // - If the original P is a reference type, the deduced A (i.e., the
3108 // type referred to by the reference) can be more cv-qualified than
3109 // the transformed A.
3110 if (ParamRefType)
3111 TDF |= TDF_ParamWithReferenceType;
3112 // - The transformed A can be another pointer or pointer to member
3113 // type that can be converted to the deduced A via a qualification
3114 // conversion (4.4).
3115 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3116 ArgType->isObjCObjectPointerType())
3117 TDF |= TDF_IgnoreQualifiers;
3118 // - If P is a class and P has the form simple-template-id, then the
3119 // transformed A can be a derived class of the deduced A. Likewise,
3120 // if P is a pointer to a class of the form simple-template-id, the
3121 // transformed A can be a pointer to a derived class pointed to by
3122 // the deduced A.
3123 if (isSimpleTemplateIdType(ParamType) ||
3124 (isa<PointerType>(ParamType) &&
3125 isSimpleTemplateIdType(
3126 ParamType->getAs<PointerType>()->getPointeeType())))
3127 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003128
Douglas Gregor7825bf32011-01-06 22:09:01 +00003129 return false;
3130}
3131
Nico Weberc153d242014-07-28 00:02:09 +00003132static bool
3133hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3134 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003135
Hubert Tong3280b332015-06-25 00:25:49 +00003136static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3137 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3138 Expr *Arg, TemplateDeductionInfo &Info,
3139 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3140
3141/// \brief Attempt template argument deduction from an initializer list
3142/// deemed to be an argument in a function call.
3143static bool
3144DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3145 QualType AdjustedParamType, InitListExpr *ILE,
3146 TemplateDeductionInfo &Info,
3147 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3148 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003149
3150 // [temp.deduct.call] p1 (post CWG-1591)
3151 // If removing references and cv-qualifiers from P gives
3152 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3153 // non-empty initializer list (8.5.4), then deduction is performed instead for
3154 // each element of the initializer list, taking P0 as a function template
3155 // parameter type and the initializer element as its argument, and in the
3156 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3157 // length of the initializer list. Otherwise, an initializer list argument
3158 // causes the parameter to be considered a non-deduced context
3159
3160 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3161
3162 const bool IsDependentSizedArray =
3163 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3164
Faisal Validd76cc12015-12-10 12:29:11 +00003165 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003166
3167 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3168 S.isStdInitializerList(AdjustedParamType, &ElTy);
3169
3170 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003171 return false;
3172
3173 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003174 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3175 // deduce against the 'T' in T[N].
3176 if (ElTy.isNull()) {
3177 assert(!IsSTDList);
3178 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003179 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003180 // Deduction only needs to be done for dependent types.
3181 if (ElTy->isDependentType()) {
3182 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003183 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3184 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003185 return true;
3186 }
3187 }
3188 if (IsDependentSizedArray) {
3189 const DependentSizedArrayType *ArrTy =
3190 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3191 // Determine the array bound is something we can deduce.
3192 if (NonTypeTemplateParmDecl *NTTP =
Richard Smith87d263e2016-12-25 08:05:23 +00003193 getDeducedParameterFromExpr(Info, ArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003194 // We can perform template argument deduction for the given non-type
3195 // template parameter.
3196 assert(NTTP->getDepth() == 0 &&
3197 "Cannot deduce non-type template argument at depth > 0");
3198 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3199 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003200
Faisal Valif6dfdb32015-12-10 05:36:39 +00003201 Result = DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +00003202 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
Faisal Valif6dfdb32015-12-10 05:36:39 +00003203 /*ArrayBound=*/true, Info, Deduced);
3204 }
3205 }
Hubert Tong3280b332015-06-25 00:25:49 +00003206 return true;
3207}
3208
Sebastian Redl19181662012-03-15 21:40:51 +00003209/// \brief Perform template argument deduction by matching a parameter type
3210/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003211/// an initializer list that was originally matched against a parameter
3212/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003213static Sema::TemplateDeductionResult
3214DeduceTemplateArgumentByListElement(Sema &S,
3215 TemplateParameterList *TemplateParams,
3216 QualType ParamType, Expr *Arg,
3217 TemplateDeductionInfo &Info,
3218 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3219 unsigned TDF) {
3220 // Handle the case where an init list contains another init list as the
3221 // element.
3222 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003223 Sema::TemplateDeductionResult Result;
3224 if (!DeduceFromInitializerList(S, TemplateParams,
3225 ParamType.getNonReferenceType(), ILE, Info,
3226 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003227 return Sema::TDK_Success; // Just ignore this expression.
3228
Hubert Tong3280b332015-06-25 00:25:49 +00003229 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003230 }
3231
3232 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003233 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003234 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003235 ArgType, Arg, TDF)) {
3236 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003237 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003238 }
Sebastian Redl19181662012-03-15 21:40:51 +00003239 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003240 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003241}
3242
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003243/// \brief Perform template argument deduction from a function call
3244/// (C++ [temp.deduct.call]).
3245///
3246/// \param FunctionTemplate the function template for which we are performing
3247/// template argument deduction.
3248///
James Dennett18348b62012-06-22 08:52:37 +00003249/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003250/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003251///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003252/// \param Args the function call arguments
3253///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003254/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003255/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003256/// template argument deduction.
3257///
3258/// \param Info the argument will be updated to provide additional information
3259/// about template argument deduction.
3260///
3261/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003262Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3263 FunctionTemplateDecl *FunctionTemplate,
3264 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003265 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3266 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003267 if (FunctionTemplate->isInvalidDecl())
3268 return TDK_Invalid;
3269
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003270 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003271 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003272
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003273 // C++ [temp.deduct.call]p1:
3274 // Template argument deduction is done by comparing each function template
3275 // parameter type (call it P) with the type of the corresponding argument
3276 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003277 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003278 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003279 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003280 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003281 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003282 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003283 if (Proto->isTemplateVariadic())
3284 /* Do nothing */;
3285 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003286 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003288 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003289 }
Mike Stump11289f42009-09-09 15:08:12 +00003290
Douglas Gregor89026b52009-06-30 23:57:56 +00003291 // The types of the parameters from which we will perform template argument
3292 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003293 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003294 TemplateParameterList *TemplateParams
3295 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003296 SmallVector<DeducedTemplateArgument, 4> Deduced;
3297 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003298 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003299 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003300 TemplateDeductionResult Result =
3301 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003302 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003303 Deduced,
3304 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003305 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003306 Info);
3307 if (Result)
3308 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003309
3310 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003311 } else {
3312 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003313 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003314 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3315 }
Mike Stump11289f42009-09-09 15:08:12 +00003316
Douglas Gregor89026b52009-06-30 23:57:56 +00003317 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003318 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003319 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003320 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003321 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3322 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003323 QualType OrigParamType = ParamTypes[ParamIdx];
3324 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003325
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003326 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003327 = dyn_cast<PackExpansionType>(ParamType);
3328 if (!ParamExpansion) {
3329 // Simple case: matching a function parameter to a function argument.
3330 if (ArgIdx >= CheckArgs)
3331 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332
Douglas Gregor7825bf32011-01-06 22:09:01 +00003333 Expr *Arg = Args[ArgIdx++];
3334 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003335
Douglas Gregor7825bf32011-01-06 22:09:01 +00003336 unsigned TDF = 0;
3337 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3338 ParamType, ArgType, Arg,
3339 TDF))
3340 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003341
Douglas Gregor0c83c812011-10-09 22:06:46 +00003342 // If we have nothing to deduce, we're done.
3343 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3344 continue;
3345
Sebastian Redl43144e72012-01-17 22:49:58 +00003346 // If the argument is an initializer list ...
3347 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003348 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003349 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003350 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3351 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003352 continue;
3353
Hubert Tong3280b332015-06-25 00:25:49 +00003354 if (Result)
3355 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003356 // Don't track the argument type, since an initializer list has none.
3357 continue;
3358 }
3359
Douglas Gregore65aacb2011-06-16 16:50:48 +00003360 // Keep track of the argument type and corresponding parameter index,
3361 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003362 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003363 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003364
Douglas Gregor7825bf32011-01-06 22:09:01 +00003365 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003366 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3367 ParamType, ArgType,
3368 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003369 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003370
Douglas Gregor7825bf32011-01-06 22:09:01 +00003371 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003373
Douglas Gregor7825bf32011-01-06 22:09:01 +00003374 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375 // For a function parameter pack that occurs at the end of the
3376 // parameter-declaration-list, the type A of each remaining argument of
3377 // the call is compared with the type P of the declarator-id of the
3378 // function parameter pack. Each comparison deduces template arguments
3379 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003380 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003382 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003383 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003384 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385
Douglas Gregor7825bf32011-01-06 22:09:01 +00003386 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003387 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3388 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389
Douglas Gregor7825bf32011-01-06 22:09:01 +00003390 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003391 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003392 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003393
Douglas Gregore65aacb2011-06-16 16:50:48 +00003394 QualType OrigParamType = ParamPattern;
3395 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003396 Expr *Arg = Args[ArgIdx];
3397 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003398
Douglas Gregor7825bf32011-01-06 22:09:01 +00003399 unsigned TDF = 0;
3400 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3401 ParamType, ArgType, Arg,
3402 TDF)) {
3403 // We can't actually perform any deduction for this argument, so stop
3404 // deduction at this point.
3405 ++ArgIdx;
3406 break;
3407 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408
Sebastian Redl43144e72012-01-17 22:49:58 +00003409 // As above, initializer lists need special handling.
3410 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003411 TemplateDeductionResult Result;
3412 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3413 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003414 ++ArgIdx;
3415 break;
3416 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003417
Hubert Tong3280b332015-06-25 00:25:49 +00003418 if (Result)
3419 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003420 } else {
3421
3422 // Keep track of the argument type and corresponding argument index,
3423 // so we can check for compatibility between the deduced A and A.
3424 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003425 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003426 ArgType));
3427
3428 if (TemplateDeductionResult Result
3429 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3430 ParamType, ArgType, Info,
3431 Deduced, TDF))
3432 return Result;
3433 }
Mike Stump11289f42009-09-09 15:08:12 +00003434
Richard Smith0a80d572014-05-29 01:12:14 +00003435 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437
Douglas Gregor7825bf32011-01-06 22:09:01 +00003438 // Build argument packs for each of the parameter packs expanded by this
3439 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003440 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003442
Douglas Gregor7825bf32011-01-06 22:09:01 +00003443 // After we've matching against a parameter pack, we're done.
3444 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003445 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003446
Mike Stump11289f42009-09-09 15:08:12 +00003447 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003448 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003449 Info, &OriginalCallArgs,
3450 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003451}
3452
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003453QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003454 QualType FunctionType,
3455 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003456 if (ArgFunctionType.isNull())
3457 return ArgFunctionType;
3458
3459 const FunctionProtoType *FunctionTypeP =
3460 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003461 const FunctionProtoType *ArgFunctionTypeP =
3462 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003463
3464 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3465 bool Rebuild = false;
3466
3467 CallingConv CC = FunctionTypeP->getCallConv();
3468 if (EPI.ExtInfo.getCC() != CC) {
3469 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3470 Rebuild = true;
3471 }
3472
3473 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3474 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3475 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3476 Rebuild = true;
3477 }
3478
3479 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3480 ArgFunctionTypeP->hasExceptionSpec())) {
3481 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3482 Rebuild = true;
3483 }
3484
3485 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003486 return ArgFunctionType;
3487
Richard Smithbaa47832016-12-01 02:11:49 +00003488 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3489 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003490}
3491
Douglas Gregor9b146582009-07-08 20:55:45 +00003492/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003493/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3494/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003495///
3496/// \param FunctionTemplate the function template for which we are performing
3497/// template argument deduction.
3498///
James Dennett18348b62012-06-22 08:52:37 +00003499/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003500/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003501///
3502/// \param ArgFunctionType the function type that will be used as the
3503/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003504/// function template's function type. This type may be NULL, if there is no
3505/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003506///
3507/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003508/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003509/// template argument deduction.
3510///
3511/// \param Info the argument will be updated to provide additional information
3512/// about template argument deduction.
3513///
Richard Smithbaa47832016-12-01 02:11:49 +00003514/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3515/// the address of a function template per [temp.deduct.funcaddr] and
3516/// [over.over]. If \c false, we are looking up a function template
3517/// specialization based on its signature, per [temp.deduct.decl].
3518///
Douglas Gregor9b146582009-07-08 20:55:45 +00003519/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003520Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3521 FunctionTemplateDecl *FunctionTemplate,
3522 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3523 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3524 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003525 if (FunctionTemplate->isInvalidDecl())
3526 return TDK_Invalid;
3527
Douglas Gregor9b146582009-07-08 20:55:45 +00003528 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3529 TemplateParameterList *TemplateParams
3530 = FunctionTemplate->getTemplateParameters();
3531 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003532
3533 // When taking the address of a function, we require convertibility of
3534 // the resulting function type. Otherwise, we allow arbitrary mismatches
3535 // of calling convention, noreturn, and noexcept.
3536 if (!IsAddressOfFunction)
3537 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3538 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003539
Douglas Gregor9b146582009-07-08 20:55:45 +00003540 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003541 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003542 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003543 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003544 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003545 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003546 if (TemplateDeductionResult Result
3547 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003548 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003549 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003550 &FunctionType, Info))
3551 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003552
3553 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003554 }
3555
Eli Friedman77dcc722012-02-08 03:07:05 +00003556 // Unevaluated SFINAE context.
3557 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003558 SFINAETrap Trap(*this);
3559
John McCallc1f69982010-02-02 02:21:27 +00003560 Deduced.resize(TemplateParams->size());
3561
Richard Smith2a7d4812013-05-04 07:00:32 +00003562 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003563 // type so that we treat it as a non-deduced context in what follows. If we
3564 // are looking up by signature, the signature type should also have a deduced
3565 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003566 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003567 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003568 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003569 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003570 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003571 }
3572
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003573 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003574 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003575 if (IsAddressOfFunction)
3576 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003577 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003578 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003579 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003580 FunctionType, ArgFunctionType,
3581 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003582 return Result;
3583 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003584
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003586 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3587 NumExplicitlySpecified,
3588 Specialization, Info))
3589 return Result;
3590
Richard Smith2a7d4812013-05-04 07:00:32 +00003591 // If the function has a deduced return type, deduce it now, so we can check
3592 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003593 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003594 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003595 DeduceReturnType(Specialization, Info.getLocation(), false))
3596 return TDK_MiscellaneousDeductionFailure;
3597
Richard Smith9095e5b2016-11-01 01:31:23 +00003598 // If the function has a dependent exception specification, resolve it now,
3599 // so we can check that the exception specification matches.
3600 auto *SpecializationFPT =
3601 Specialization->getType()->castAs<FunctionProtoType>();
3602 if (getLangOpts().CPlusPlus1z &&
3603 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3604 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3605 return TDK_MiscellaneousDeductionFailure;
3606
Richard Smithbaa47832016-12-01 02:11:49 +00003607 // Adjust the exception specification of the argument again to match the
3608 // substituted and resolved type we just formed. (Calling convention and
3609 // noreturn can't be dependent, so we don't actually need this for them
3610 // right now.)
3611 QualType SpecializationType = Specialization->getType();
3612 if (!IsAddressOfFunction)
3613 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3614 /*AdjustExceptionSpec*/true);
3615
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003616 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003617 // specialization with respect to arguments of compatible pointer to function
3618 // types, template argument deduction fails.
3619 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003620 if (IsAddressOfFunction &&
3621 !isSameOrCompatibleFunctionType(
3622 Context.getCanonicalType(SpecializationType),
3623 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003624 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003625
3626 if (!IsAddressOfFunction &&
3627 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003628 return TDK_MiscellaneousDeductionFailure;
3629 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003630
3631 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003632}
3633
Simon Pilgrim728134c2016-08-12 11:43:57 +00003634/// \brief Given a function declaration (e.g. a generic lambda conversion
3635/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003636/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3637/// to replace 'auto' with and not the actual result type you want
3638/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003639static inline void
3640SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003641 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003642 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003643 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003644 assert(AutoResultType->getContainedAutoType());
3645 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003646 TypeToReplaceAutoWith);
3647 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3648}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003649
Simon Pilgrim728134c2016-08-12 11:43:57 +00003650/// \brief Given a specialized conversion operator of a generic lambda
3651/// create the corresponding specializations of the call operator and
3652/// the static-invoker. If the return type of the call operator is auto,
3653/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003654/// return type of the destination function ptr.
3655
Simon Pilgrim728134c2016-08-12 11:43:57 +00003656static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003657SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3658 CXXConversionDecl *ConversionSpecialized,
3659 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3660 QualType ReturnTypeOfDestFunctionPtr,
3661 TemplateDeductionInfo &TDInfo,
3662 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003663
Faisal Vali2b3a3012013-10-24 23:40:02 +00003664 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003665 assert(LambdaClass && LambdaClass->isGenericLambda());
3666
Faisal Vali2b3a3012013-10-24 23:40:02 +00003667 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003668 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003669 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003670 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003671
3672 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003673 CallOpGeneric->getDescribedFunctionTemplate();
3674
Craig Topperc3ec1492014-05-26 06:22:03 +00003675 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003676 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003677 // generic lambda's call operator.
3678 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003679 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3680 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003681 0, CallOpSpecialized, TDInfo))
3682 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003683
Faisal Vali2b3a3012013-10-24 23:40:02 +00003684 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003685 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3686 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003687 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003688 CallOpSpecialized->getPointOfInstantiation(),
3689 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003690
Faisal Vali2b3a3012013-10-24 23:40:02 +00003691 // Check to see if the return type of the destination ptr-to-function
3692 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003693 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003694 ReturnTypeOfDestFunctionPtr))
3695 return Sema::TDK_NonDeducedMismatch;
3696 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003697 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003698 // specialized our corresponding call operator, we are ready to
3699 // specialize the static invoker with the deduced arguments of our
3700 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003701 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003702 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3703 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3704
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003705#ifndef NDEBUG
3706 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3707#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003708 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003709 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003710 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003711 "If the call operator succeeded so should the invoker!");
3712 // Set the result type to match the corresponding call operator
3713 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003714 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3715 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003716 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003717 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003718 // to substitute into the 'auto' of the invoker and conversion
3719 // function.
3720 // For e.g.
3721 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3722 // We don't want to subst 'int*' into 'auto' to get int**.
3723
Alp Toker314cc812014-01-25 16:55:45 +00003724 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3725 ->getContainedAutoType()
3726 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003727 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3728 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003729 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003730 TypeToReplaceAutoWith, S);
3731 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003732
Faisal Vali2b3a3012013-10-24 23:40:02 +00003733 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003734 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003735 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003736 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003737 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3738 getType().getTypePtr()->castAs<FunctionProtoType>();
3739 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3740 EPI.TypeQuals = 0;
3741 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003742 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003743 return Sema::TDK_Success;
3744}
Douglas Gregor05155d82009-08-21 23:19:43 +00003745/// \brief Deduce template arguments for a templated conversion
3746/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3747/// conversion function template specialization.
3748Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003749Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003750 QualType ToType,
3751 CXXConversionDecl *&Specialization,
3752 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003753 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003754 return TDK_Invalid;
3755
Faisal Vali2b3a3012013-10-24 23:40:02 +00003756 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003757 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3758
Faisal Vali2b3a3012013-10-24 23:40:02 +00003759 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003760
3761 // Canonicalize the types for deduction.
3762 QualType P = Context.getCanonicalType(FromType);
3763 QualType A = Context.getCanonicalType(ToType);
3764
Douglas Gregord99609a2011-03-06 09:03:20 +00003765 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003766 // If P is a reference type, the type referred to by P is used for
3767 // type deduction.
3768 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3769 P = PRef->getPointeeType();
3770
Douglas Gregord99609a2011-03-06 09:03:20 +00003771 // C++0x [temp.deduct.conv]p4:
3772 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003773 // for type deduction.
3774 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003775 A = ARef->getPointeeType().getUnqualifiedType();
3776 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003777 //
Mike Stump11289f42009-09-09 15:08:12 +00003778 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003779 else {
3780 assert(!A->isReferenceType() && "Reference types were handled above");
3781
3782 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003783 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003784 // of P for type deduction; otherwise,
3785 if (P->isArrayType())
3786 P = Context.getArrayDecayedType(P);
3787 // - If P is a function type, the pointer type produced by the
3788 // function-to-pointer standard conversion (4.3) is used in
3789 // place of P for type deduction; otherwise,
3790 else if (P->isFunctionType())
3791 P = Context.getPointerType(P);
3792 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003793 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003794 else
3795 P = P.getUnqualifiedType();
3796
Douglas Gregord99609a2011-03-06 09:03:20 +00003797 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003798 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003799 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003800 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003801 A = A.getUnqualifiedType();
3802 }
3803
Eli Friedman77dcc722012-02-08 03:07:05 +00003804 // Unevaluated SFINAE context.
3805 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003806 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003807
3808 // C++ [temp.deduct.conv]p1:
3809 // Template argument deduction is done by comparing the return
3810 // type of the template conversion function (call it P) with the
3811 // type that is required as the result of the conversion (call it
3812 // A) as described in 14.8.2.4.
3813 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003814 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003815 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003816 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003817
3818 // C++0x [temp.deduct.conv]p4:
3819 // In general, the deduction process attempts to find template
3820 // argument values that will make the deduced A identical to
3821 // A. However, there are two cases that allow a difference:
3822 unsigned TDF = 0;
3823 // - If the original A is a reference type, A can be more
3824 // cv-qualified than the deduced A (i.e., the type referred to
3825 // by the reference)
3826 if (ToType->isReferenceType())
3827 TDF |= TDF_ParamWithReferenceType;
3828 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003829 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003830 // conversion.
3831 //
3832 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3833 // both P and A are pointers or member pointers. In this case, we
3834 // just ignore cv-qualifiers completely).
3835 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003836 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003837 TDF |= TDF_IgnoreQualifiers;
3838 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003839 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3840 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003841 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003842
3843 // Create an Instantiation Scope for finalizing the operator.
3844 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003845 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003846 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003847 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003848 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003849 ConversionSpecialized, Info);
3850 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3851
3852 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003853 // to a ptr-to-function, use the deduced arguments from the conversion
3854 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003855 // e.g., int (*fp)(int) = [](auto a) { return a; };
3856 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003857
Faisal Vali2b3a3012013-10-24 23:40:02 +00003858 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003859 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003860 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003861 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003862 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003863 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003864 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003865 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3866
Simon Pilgrim728134c2016-08-12 11:43:57 +00003867 // Create the corresponding specializations of the call operator and
3868 // the static-invoker; and if the return type is auto,
3869 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003870 // DestFunctionPtrReturnType.
3871 // For instance:
3872 // auto L = [](auto a) { return f(a); };
3873 // int (*fp)(int) = L;
3874 // char (*fp2)(int) = L; <-- Not OK.
3875
3876 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003877 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003878 Info, *this);
3879 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003880 return Result;
3881}
3882
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003883/// \brief Deduce template arguments for a function template when there is
3884/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3885///
3886/// \param FunctionTemplate the function template for which we are performing
3887/// template argument deduction.
3888///
James Dennett18348b62012-06-22 08:52:37 +00003889/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003890/// arguments.
3891///
3892/// \param Specialization if template argument deduction was successful,
3893/// this will be set to the function template specialization produced by
3894/// template argument deduction.
3895///
3896/// \param Info the argument will be updated to provide additional information
3897/// about template argument deduction.
3898///
Richard Smithbaa47832016-12-01 02:11:49 +00003899/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3900/// the address of a function template in a context where we do not have a
3901/// target type, per [over.over]. If \c false, we are looking up a function
3902/// template specialization based on its signature, which only happens when
3903/// deducing a function parameter type from an argument that is a template-id
3904/// naming a function template specialization.
3905///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003906/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003907Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3908 FunctionTemplateDecl *FunctionTemplate,
3909 TemplateArgumentListInfo *ExplicitTemplateArgs,
3910 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3911 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003912 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003913 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00003914 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003915}
3916
Richard Smith30482bc2011-02-20 03:19:35 +00003917namespace {
3918 /// Substitute the 'auto' type specifier within a type for a given replacement
3919 /// type.
3920 class SubstituteAutoTransform :
3921 public TreeTransform<SubstituteAutoTransform> {
3922 QualType Replacement;
Richard Smith87d263e2016-12-25 08:05:23 +00003923 bool UseAutoSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00003924 public:
Richard Smith87d263e2016-12-25 08:05:23 +00003925 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
3926 bool UseAutoSugar = true)
Nico Weberc153d242014-07-28 00:02:09 +00003927 : TreeTransform<SubstituteAutoTransform>(SemaRef),
Richard Smith87d263e2016-12-25 08:05:23 +00003928 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
Nico Weberc153d242014-07-28 00:02:09 +00003929
Richard Smith30482bc2011-02-20 03:19:35 +00003930 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3931 // If we're building the type pattern to deduce against, don't wrap the
3932 // substituted type in an AutoType. Certain template deduction rules
3933 // apply only when a template type parameter appears directly (and not if
3934 // the parameter is found through desugaring). For instance:
3935 // auto &&lref = lvalue;
3936 // must transform into "rvalue reference to T" not "rvalue reference to
3937 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith87d263e2016-12-25 08:05:23 +00003938 if (!UseAutoSugar) {
3939 assert(isa<TemplateTypeParmType>(Replacement) &&
3940 "unexpected unsugared replacement kind");
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 Smith87d263e2016-12-25 08:05:23 +00003947 QualType Result = SemaRef.Context.getAutoType(
3948 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
Richard Smith30482bc2011-02-20 03:19:35 +00003949 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3950 NewTL.setNameLoc(TL.getNameLoc());
3951 return Result;
3952 }
3953 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003954
3955 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3956 // Lambdas never need to be transformed.
3957 return E;
3958 }
Richard Smith061f1e22013-04-30 21:23:01 +00003959
Richard Smith2a7d4812013-05-04 07:00:32 +00003960 QualType Apply(TypeLoc TL) {
3961 // Create some scratch storage for the transformed type locations.
3962 // FIXME: We're just going to throw this information away. Don't build it.
3963 TypeLocBuilder TLB;
3964 TLB.reserve(TL.getFullDataSize());
3965 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003966 }
Richard Smith30482bc2011-02-20 03:19:35 +00003967 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003968}
Richard Smith30482bc2011-02-20 03:19:35 +00003969
Richard Smith2a7d4812013-05-04 07:00:32 +00003970Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00003971Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
3972 Optional<unsigned> DependentDeductionDepth) {
3973 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
3974 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00003975}
3976
Richard Smith061f1e22013-04-30 21:23:01 +00003977/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00003978///
Richard Smith87d263e2016-12-25 08:05:23 +00003979/// Note that this is done even if the initializer is dependent. (This is
3980/// necessary to support partial ordering of templates using 'auto'.)
3981/// A dependent type will be produced when deducing from a dependent type.
3982///
Richard Smith30482bc2011-02-20 03:19:35 +00003983/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00003984/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00003985/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00003986/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00003987/// \param DependentDeductionDepth Set if we should permit deduction in
3988/// dependent cases. This is necessary for template partial ordering with
3989/// 'auto' template parameters. The value specified is the template
3990/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00003991Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00003992Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
3993 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00003994 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00003995 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
3996 if (NonPlaceholder.isInvalid())
3997 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003998 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00003999 }
4000
Richard Smith87d263e2016-12-25 08:05:23 +00004001 if (!DependentDeductionDepth &&
4002 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4003 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004004 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004005 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004006 }
4007
Richard Smith87d263e2016-12-25 08:05:23 +00004008 // Find the depth of template parameter to synthesize.
4009 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4010
Richard Smith74aeef52013-04-26 16:15:35 +00004011 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4012 // Since 'decltype(auto)' can only occur at the top of the type, we
4013 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004014 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004015 if (AT->isDecltypeAuto()) {
4016 if (isa<InitListExpr>(Init)) {
4017 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4018 return DAR_FailedAlreadyDiagnosed;
4019 }
4020
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004021 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004022 if (Deduced.isNull())
4023 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004024 // FIXME: Support a non-canonical deduced type for 'auto'.
4025 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004026 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004027 if (Result.isNull())
4028 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004029 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004030 } else if (!getLangOpts().CPlusPlus) {
4031 if (isa<InitListExpr>(Init)) {
4032 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4033 return DAR_FailedAlreadyDiagnosed;
4034 }
Richard Smith74aeef52013-04-26 16:15:35 +00004035 }
4036 }
4037
Richard Smith30482bc2011-02-20 03:19:35 +00004038 SourceLocation Loc = Init->getExprLoc();
4039
4040 LocalInstantiationScope InstScope(*this);
4041
4042 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004043 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4044 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004045 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4046 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004047 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4048 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004049
Richard Smith87d263e2016-12-25 08:05:23 +00004050 QualType FuncParam =
4051 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4052 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004053 assert(!FuncParam.isNull() &&
4054 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004055
4056 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004057 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004058 Deduced.resize(1);
4059 QualType InitType = Init->getType();
4060 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004061
Richard Smith87d263e2016-12-25 08:05:23 +00004062 TemplateDeductionInfo Info(Loc, Depth);
4063
4064 // If deduction failed, don't diagnose if the initializer is dependent; it
4065 // might acquire a matching type in the instantiation.
4066 auto DeductionFailed = [&]() -> DeduceAutoResult {
4067 if (Init->isTypeDependent()) {
4068 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4069 assert(!Result.isNull() && "substituting DependentTy can't fail");
4070 return DAR_Succeeded;
4071 }
4072 return DAR_Failed;
4073 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004074
Richard Smith74801c82012-07-08 04:13:07 +00004075 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004076 if (InitList) {
4077 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004078 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4079 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004080 Info, Deduced, TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004081 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004082 }
4083 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004084 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4085 Diag(Loc, diag::err_auto_bitfield);
4086 return DAR_FailedAlreadyDiagnosed;
4087 }
4088
James Y Knight7a22b242015-08-06 20:26:32 +00004089 if (AdjustFunctionParmAndArgTypesForDeduction(
4090 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004091 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004092
James Y Knight7a22b242015-08-06 20:26:32 +00004093 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4094 FuncParam, InitType, Info, Deduced,
4095 TDF))
Richard Smith87d263e2016-12-25 08:05:23 +00004096 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004097 }
Richard Smith30482bc2011-02-20 03:19:35 +00004098
Richard Smith87d263e2016-12-25 08:05:23 +00004099 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004100 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004101 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004102
Eli Friedmane4310952012-11-06 23:56:42 +00004103 QualType DeducedType = Deduced[0].getAsType();
4104
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004105 if (InitList) {
4106 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4107 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004108 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004109 }
4110
Richard Smith061f1e22013-04-30 21:23:01 +00004111 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004112 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004113 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004114
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004115 // Check that the deduced argument type is compatible with the original
4116 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004117 if (!InitList && !Result.isNull() &&
4118 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004119 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004120 Result)) {
4121 Result = QualType();
Richard Smith87d263e2016-12-25 08:05:23 +00004122 return DeductionFailed();
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004123 }
4124
Sebastian Redl09edce02012-01-23 22:09:39 +00004125 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004126}
4127
Simon Pilgrim728134c2016-08-12 11:43:57 +00004128QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004129 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004130 if (TypeToReplaceAuto->isDependentType())
4131 TypeToReplaceAuto = QualType();
4132 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4133 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004134}
4135
Simon Pilgrim728134c2016-08-12 11:43:57 +00004136TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004137 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004138 if (TypeToReplaceAuto->isDependentType())
4139 TypeToReplaceAuto = QualType();
4140 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4141 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004142}
4143
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004144void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4145 if (isa<InitListExpr>(Init))
4146 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004147 VDecl->isInitCapture()
4148 ? diag::err_init_capture_deduction_failure_from_init_list
4149 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004150 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4151 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004152 Diag(VDecl->getLocation(),
4153 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4154 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004155 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4156 << Init->getSourceRange();
4157}
4158
Richard Smith2a7d4812013-05-04 07:00:32 +00004159bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4160 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004161 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004162
4163 if (FD->getTemplateInstantiationPattern())
4164 InstantiateFunctionDefinition(Loc, FD);
4165
Alp Toker314cc812014-01-25 16:55:45 +00004166 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004167 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4168 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4169 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4170 }
4171
4172 return StillUndeduced;
4173}
4174
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004175static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004176MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004177 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004178 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004179 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004180
4181/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004182static void
4183AddImplicitObjectParameterType(ASTContext &Context,
4184 CXXMethodDecl *Method,
4185 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004186 // C++11 [temp.func.order]p3:
4187 // [...] The new parameter is of type "reference to cv A," where cv are
4188 // the cv-qualifiers of the function template (if any) and A is
4189 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004190 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004191 // The standard doesn't say explicitly, but we pick the appropriate kind of
4192 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004193 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4194 ArgTy = Context.getQualifiedType(ArgTy,
4195 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004196 if (Method->getRefQualifier() == RQ_RValue)
4197 ArgTy = Context.getRValueReferenceType(ArgTy);
4198 else
4199 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004200 ArgTypes.push_back(ArgTy);
4201}
4202
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004203/// \brief Determine whether the function template \p FT1 is at least as
4204/// specialized as \p FT2.
4205static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004206 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004207 FunctionTemplateDecl *FT1,
4208 FunctionTemplateDecl *FT2,
4209 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004210 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004211 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004213 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4214 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004216 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4217 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004218 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004219 Deduced.resize(TemplateParams->size());
4220
4221 // C++0x [temp.deduct.partial]p3:
4222 // The types used to determine the ordering depend on the context in which
4223 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004224 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004225 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004226 switch (TPOC) {
4227 case TPOC_Call: {
4228 // - In the context of a function call, the function parameter types are
4229 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004230 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4231 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004232
Eli Friedman3b5774a2012-09-19 23:27:04 +00004233 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004234 // [...] If only one of the function templates is a non-static
4235 // member, that function template is considered to have a new
4236 // first parameter inserted in its function parameter list. The
4237 // new parameter is of type "reference to cv A," where cv are
4238 // the cv-qualifiers of the function template (if any) and A is
4239 // the class of which the function template is a member.
4240 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004241 // Note that we interpret this to mean "if one of the function
4242 // templates is a non-static member and the other is a non-member";
4243 // otherwise, the ordering rules for static functions against non-static
4244 // functions don't make any sense.
4245 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004246 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4247 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004248 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004249
Richard Smithe5b52202013-09-11 00:52:39 +00004250 unsigned NumComparedArguments = NumCallArguments1;
4251
4252 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004253 // Compare 'this' from Method1 against first parameter from Method2.
4254 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4255 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004256 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004257 // Compare 'this' from Method2 against first parameter from Method1.
4258 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004259 }
4260
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004261 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004262 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004263 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004264 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004265
Douglas Gregorb837ea42011-01-11 17:34:58 +00004266 // C++ [temp.func.order]p5:
4267 // The presence of unused ellipsis and default arguments has no effect on
4268 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004269 if (Args1.size() > NumComparedArguments)
4270 Args1.resize(NumComparedArguments);
4271 if (Args2.size() > NumComparedArguments)
4272 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004273 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4274 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004275 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004276 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004278 break;
4279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004281 case TPOC_Conversion:
4282 // - In the context of a call to a conversion operator, the return types
4283 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004284 if (DeduceTemplateArgumentsByTypeMatch(
4285 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4286 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004287 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004288 return false;
4289 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004291 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004292 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004293 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004294 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4295 FD2->getType(), FD1->getType(),
4296 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004297 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004298 return false;
4299 break;
4300 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004302 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004303 // In most cases, all template parameters must have values in order for
4304 // deduction to succeed, but for partial ordering purposes a template
4305 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004306 // types being used for partial ordering. [ Note: a template parameter used
4307 // in a non-deduced context is considered used. -end note]
4308 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4309 for (; ArgIdx != NumArgs; ++ArgIdx)
4310 if (Deduced[ArgIdx].isNull())
4311 break;
4312
4313 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004315 // as FT2.
4316 return true;
4317 }
4318
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004319 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004320 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004321 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004322 case TPOC_Call:
4323 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4324 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004325 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004326 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004327 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004329 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004330 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4331 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004332 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004334 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004335 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004336 TemplateParams->getDepth(),
4337 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004338 break;
4339 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004341 for (; ArgIdx != NumArgs; ++ArgIdx)
4342 // If this argument had no value deduced but was used in one of the types
4343 // used for partial ordering, then deduction fails.
4344 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4345 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004347 return true;
4348}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004349
Douglas Gregorcef1a032011-01-16 16:03:23 +00004350/// \brief Determine whether this a function template whose parameter-type-list
4351/// ends with a function parameter pack.
4352static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4353 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4354 unsigned NumParams = Function->getNumParams();
4355 if (NumParams == 0)
4356 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357
Douglas Gregorcef1a032011-01-16 16:03:23 +00004358 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4359 if (!Last->isParameterPack())
4360 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361
Douglas Gregorcef1a032011-01-16 16:03:23 +00004362 // Make sure that no previous parameter is a parameter pack.
4363 while (--NumParams > 0) {
4364 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4365 return false;
4366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367
Douglas Gregorcef1a032011-01-16 16:03:23 +00004368 return true;
4369}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370
Douglas Gregorbe999392009-09-15 16:23:51 +00004371/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004372/// to the rules of function template partial ordering (C++ [temp.func.order]).
4373///
4374/// \param FT1 the first function template
4375///
4376/// \param FT2 the second function template
4377///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004378/// \param TPOC the context in which we are performing partial ordering of
4379/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004380///
Richard Smithe5b52202013-09-11 00:52:39 +00004381/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4382/// only when \c TPOC is \c TPOC_Call.
4383///
4384/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4385/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004386///
Douglas Gregorbe999392009-09-15 16:23:51 +00004387/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004388/// template is more specialized, returns NULL.
4389FunctionTemplateDecl *
4390Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4391 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004392 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004393 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004394 unsigned NumCallArguments1,
4395 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004397 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004399 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004400
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004401 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004402 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004403
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004404 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004405 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004406
Douglas Gregorcef1a032011-01-16 16:03:23 +00004407 // FIXME: This mimics what GCC implements, but doesn't match up with the
4408 // proposed resolution for core issue 692. This area needs to be sorted out,
4409 // but for now we attempt to maintain compatibility.
4410 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4411 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4412 if (Variadic1 != Variadic2)
4413 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004414
Craig Topperc3ec1492014-05-26 06:22:03 +00004415 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004416}
Douglas Gregor9b146582009-07-08 20:55:45 +00004417
Douglas Gregor450f00842009-09-25 18:43:00 +00004418/// \brief Determine if the two templates are equivalent.
4419static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4420 if (T1 == T2)
4421 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422
Douglas Gregor450f00842009-09-25 18:43:00 +00004423 if (!T1 || !T2)
4424 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425
Douglas Gregor450f00842009-09-25 18:43:00 +00004426 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4427}
4428
4429/// \brief Retrieve the most specialized of the given function template
4430/// specializations.
4431///
John McCall58cc69d2010-01-27 01:50:18 +00004432/// \param SpecBegin the start iterator of the function template
4433/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004434///
John McCall58cc69d2010-01-27 01:50:18 +00004435/// \param SpecEnd the end iterator of the function template
4436/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004437///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004438/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004439/// diagnostic should occur.
4440///
4441/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4442/// no matching candidates.
4443///
4444/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4445/// occurs.
4446///
4447/// \param CandidateDiag partial diagnostic used for each function template
4448/// specialization that is a candidate in the ambiguous ordering. One parameter
4449/// in this diagnostic should be unbound, which will correspond to the string
4450/// describing the template arguments for the function template specialization.
4451///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004453/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004454UnresolvedSetIterator Sema::getMostSpecialized(
4455 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4456 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004457 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4458 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4459 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004460 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004461 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004462 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004463 FailedCandidates.NoteCandidates(*this, Loc);
4464 }
John McCall58cc69d2010-01-27 01:50:18 +00004465 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467
4468 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004469 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004470
Douglas Gregor450f00842009-09-25 18:43:00 +00004471 // Find the function template that is better than all of the templates it
4472 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004473 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004474 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004475 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004476 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004477 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4478 FunctionTemplateDecl *Challenger
4479 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004480 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004481 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004482 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004483 Challenger)) {
4484 Best = I;
4485 BestTemplate = Challenger;
4486 }
4487 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004488
Douglas Gregor450f00842009-09-25 18:43:00 +00004489 // Make sure that the "best" function template is more specialized than all
4490 // of the others.
4491 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004492 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4493 FunctionTemplateDecl *Challenger
4494 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004495 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004497 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004498 BestTemplate)) {
4499 Ambiguous = true;
4500 break;
4501 }
4502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregor450f00842009-09-25 18:43:00 +00004504 if (!Ambiguous) {
4505 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004506 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004508
Douglas Gregor450f00842009-09-25 18:43:00 +00004509 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004510 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004511 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004512
Richard Smithb875c432013-05-04 01:51:08 +00004513 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004514 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4515 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004516 const auto *FD = cast<FunctionDecl>(*I);
4517 PD << FD << getTemplateArgumentBindingsText(
4518 FD->getPrimaryTemplate()->getTemplateParameters(),
4519 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004520 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004521 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004522 Diag((*I)->getLocation(), PD);
4523 }
Richard Smithb875c432013-05-04 01:51:08 +00004524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
John McCall58cc69d2010-01-27 01:50:18 +00004526 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004527}
4528
Richard Smith0da6dc42016-12-24 16:40:51 +00004529/// Determine whether one partial specialization, P1, is at least as
4530/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004531///
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00004532/// \tparam PartialSpecializationDecl The kind of P2, which must be a
Richard Smith0da6dc42016-12-24 16:40:51 +00004533/// {Class,Var}TemplatePartialSpecializationDecl.
4534/// \param T1 The injected-class-name of P1 (faked for a variable template).
4535/// \param T2 The injected-class-name of P2 (faked for a variable template).
4536/// \param Loc The location at which the comparison is required.
4537template<typename PartialSpecializationDecl>
4538static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
4539 PartialSpecializationDecl *P2,
4540 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004541 // C++ [temp.class.order]p1:
4542 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543 // specialized as the second if, given the following rewrite to two
4544 // function templates, the first function template is at least as
4545 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004546 // templates (14.6.6.2):
4547 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548 // first partial specialization and has a single function parameter
4549 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004550 // arguments of the first partial specialization, and
4551 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552 // second partial specialization and has a single function parameter
4553 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004554 // arguments of the second partial specialization.
4555 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004556 // Rather than synthesize function templates, we merely perform the
4557 // equivalent partial ordering by performing deduction directly on
4558 // the template arguments of the class template partial
4559 // specializations. This computation is slightly simpler than the
4560 // general problem of function template partial ordering, because
4561 // class template partial specializations are more constrained. We
4562 // know that every template parameter is deducible from the class
4563 // template partial specialization's template arguments, for
4564 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004565 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004566 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004567
Richard Smith0da6dc42016-12-24 16:40:51 +00004568 // Determine whether P1 is at least as specialized as P2.
4569 Deduced.resize(P2->getTemplateParameters()->size());
4570 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4571 T2, T1, Info, Deduced, TDF_None,
4572 /*PartialOrdering=*/true))
4573 return false;
4574
4575 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4576 Deduced.end());
4577 Sema::InstantiatingTemplate Inst(S, Loc, P2, DeducedArgs, Info);
4578 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4579 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004580 S, P2, /*PartialOrdering=*/true,
4581 TemplateArgumentList(TemplateArgumentList::OnStack,
4582 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004583 Deduced, Info))
4584 return false;
4585
4586 return true;
4587}
4588
4589/// \brief Returns the more specialized class template partial specialization
4590/// according to the rules of partial ordering of class template partial
4591/// specializations (C++ [temp.class.order]).
4592///
4593/// \param PS1 the first class template partial specialization
4594///
4595/// \param PS2 the second class template partial specialization
4596///
4597/// \returns the more specialized class template partial specialization. If
4598/// neither partial specialization is more specialized, returns NULL.
4599ClassTemplatePartialSpecializationDecl *
4600Sema::getMoreSpecializedPartialSpecialization(
4601 ClassTemplatePartialSpecializationDecl *PS1,
4602 ClassTemplatePartialSpecializationDecl *PS2,
4603 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004604 QualType PT1 = PS1->getInjectedSpecializationType();
4605 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004606
Richard Smith0da6dc42016-12-24 16:40:51 +00004607 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Loc);
4608 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Loc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004609
4610 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004611 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004612
4613 return Better1 ? PS1 : PS2;
4614}
4615
Larisse Voufo39a1e502013-08-06 01:03:05 +00004616VarTemplatePartialSpecializationDecl *
4617Sema::getMoreSpecializedPartialSpecialization(
4618 VarTemplatePartialSpecializationDecl *PS1,
4619 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004620 // Pretend the variable template specializations are class template
4621 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004622 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004623 "the partial specializations being compared should specialize"
4624 " the same template.");
4625 TemplateName Name(PS1->getSpecializedTemplate());
4626 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4627 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004628 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004629 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004630 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004631
Richard Smith0da6dc42016-12-24 16:40:51 +00004632 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Loc);
4633 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004634
Douglas Gregorbe999392009-09-15 16:23:51 +00004635 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004636 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004637
Richard Smith0da6dc42016-12-24 16:40:51 +00004638 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004639}
4640
Mike Stump11289f42009-09-09 15:08:12 +00004641static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004642MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004643 const TemplateArgument &TemplateArg,
4644 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004645 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004646 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004647
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004648/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004649/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004650static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004651MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004652 const Expr *E,
4653 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004654 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004655 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004656 // We can deduce from a pack expansion.
4657 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4658 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004659
Richard Smith34349002012-07-09 03:07:20 +00004660 // Skip through any implicit casts we added while type-checking, and any
4661 // substitutions performed by template alias expansion.
4662 while (1) {
4663 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4664 E = ICE->getSubExpr();
4665 else if (const SubstNonTypeTemplateParmExpr *Subst =
4666 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4667 E = Subst->getReplacement();
4668 else
4669 break;
4670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671
4672 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004673 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004674 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004675 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004676 return;
4677
Mike Stump11289f42009-09-09 15:08:12 +00004678 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004679 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4680 if (!NTTP)
4681 return;
4682
Douglas Gregor21610382009-10-29 00:04:11 +00004683 if (NTTP->getDepth() == Depth)
4684 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004685
4686 // In C++1z mode, additional arguments may be deduced from the type of a
4687 // non-type argument.
4688 if (Ctx.getLangOpts().CPlusPlus1z)
4689 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004690}
4691
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004692/// \brief Mark the template parameters that are used by the given
4693/// nested name specifier.
4694static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004695MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004696 NestedNameSpecifier *NNS,
4697 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004698 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004699 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004700 if (!NNS)
4701 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004702
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004703 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004704 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004705 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004706 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004707}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004709/// \brief Mark the template parameters that are used by the given
4710/// template name.
4711static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004712MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004713 TemplateName Name,
4714 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004715 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004716 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004717 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4718 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004719 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4720 if (TTP->getDepth() == Depth)
4721 Used[TTP->getIndex()] = true;
4722 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004723 return;
4724 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004726 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004727 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004728 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004729 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004730 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004731 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004732}
4733
4734/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004735/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004736static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004737MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004738 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004739 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004740 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004741 if (T.isNull())
4742 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743
Douglas Gregor91772d12009-06-13 00:26:55 +00004744 // Non-dependent types have nothing deducible
4745 if (!T->isDependentType())
4746 return;
4747
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004748 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004749 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004750 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004751 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004752 cast<PointerType>(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::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004759 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004760 cast<BlockPointerType>(T)->getPointeeType(),
4761 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004762 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004763 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004764 break;
4765
4766 case Type::LValueReference:
4767 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004768 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004769 cast<ReferenceType>(T)->getPointeeType(),
4770 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004771 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004772 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004773 break;
4774
4775 case Type::MemberPointer: {
4776 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004777 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004778 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004779 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004780 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004781 break;
4782 }
4783
4784 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004785 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004786 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004787 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004788 // Fall through to check the element type
4789
4790 case Type::ConstantArray:
4791 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004792 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004793 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004794 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004795 break;
4796
4797 case Type::Vector:
4798 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004799 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004800 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004801 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004802 break;
4803
Douglas Gregor758a8692009-06-17 21:51:59 +00004804 case Type::DependentSizedExtVector: {
4805 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004806 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004807 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004808 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004809 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004810 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004811 break;
4812 }
4813
Douglas Gregor91772d12009-06-13 00:26:55 +00004814 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004815 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004816 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4817 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004818 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4819 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004820 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004821 break;
4822 }
4823
Douglas Gregor21610382009-10-29 00:04:11 +00004824 case Type::TemplateTypeParm: {
4825 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4826 if (TTP->getDepth() == Depth)
4827 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004828 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004829 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004830
Douglas Gregorfb322d82011-01-14 05:11:40 +00004831 case Type::SubstTemplateTypeParmPack: {
4832 const SubstTemplateTypeParmPackType *Subst
4833 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004834 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004835 QualType(Subst->getReplacedParameter(), 0),
4836 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004837 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004838 OnlyDeduced, Depth, Used);
4839 break;
4840 }
4841
John McCall2408e322010-04-27 00:57:59 +00004842 case Type::InjectedClassName:
4843 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4844 // fall through
4845
Douglas Gregor91772d12009-06-13 00:26:55 +00004846 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004847 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004848 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004849 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004850 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004851
Douglas Gregord0ad2942010-12-23 01:24:45 +00004852 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004853 // If the template argument list of P contains a pack expansion that is
4854 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004855 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00004857 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00004858 break;
4859
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004860 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004861 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004862 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004863 break;
4864 }
4865
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004866 case Type::Complex:
4867 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004868 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004869 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004870 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004871 break;
4872
Eli Friedman0dfb8892011-10-06 23:00:33 +00004873 case Type::Atomic:
4874 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004875 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004876 cast<AtomicType>(T)->getValueType(),
4877 OnlyDeduced, Depth, Used);
4878 break;
4879
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004880 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004881 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004882 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004883 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004884 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004885 break;
4886
John McCallc392f372010-06-11 00:33:02 +00004887 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004888 // C++14 [temp.deduct.type]p5:
4889 // The non-deduced contexts are:
4890 // -- The nested-name-specifier of a type that was specified using a
4891 // qualified-id
4892 //
4893 // C++14 [temp.deduct.type]p6:
4894 // When a type name is specified in a way that includes a non-deduced
4895 // context, all of the types that comprise that type name are also
4896 // non-deduced.
4897 if (OnlyDeduced)
4898 break;
4899
John McCallc392f372010-06-11 00:33:02 +00004900 const DependentTemplateSpecializationType *Spec
4901 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004902
Richard Smith50d5b972015-12-30 20:56:05 +00004903 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4904 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004905
John McCallc392f372010-06-11 00:33:02 +00004906 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004907 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004908 Used);
4909 break;
4910 }
4911
John McCallbd8d9bd2010-03-01 23:49:17 +00004912 case Type::TypeOf:
4913 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004914 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004915 cast<TypeOfType>(T)->getUnderlyingType(),
4916 OnlyDeduced, Depth, Used);
4917 break;
4918
4919 case Type::TypeOfExpr:
4920 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004921 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004922 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4923 OnlyDeduced, Depth, Used);
4924 break;
4925
4926 case Type::Decltype:
4927 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004928 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004929 cast<DecltypeType>(T)->getUnderlyingExpr(),
4930 OnlyDeduced, Depth, Used);
4931 break;
4932
Alexis Hunte852b102011-05-24 22:41:36 +00004933 case Type::UnaryTransform:
4934 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004935 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00004936 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00004937 OnlyDeduced, Depth, Used);
4938 break;
4939
Douglas Gregord2fa7662010-12-20 02:24:11 +00004940 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004941 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004942 cast<PackExpansionType>(T)->getPattern(),
4943 OnlyDeduced, Depth, Used);
4944 break;
4945
Richard Smith30482bc2011-02-20 03:19:35 +00004946 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004947 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004948 cast<AutoType>(T)->getDeducedType(),
4949 OnlyDeduced, Depth, Used);
4950
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004951 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004952 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004953 case Type::VariableArray:
4954 case Type::FunctionNoProto:
4955 case Type::Record:
4956 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004957 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004958 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004959 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004960 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00004961 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00004962#define TYPE(Class, Base)
4963#define ABSTRACT_TYPE(Class, Base)
4964#define DEPENDENT_TYPE(Class, Base)
4965#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4966#include "clang/AST/TypeNodes.def"
4967 break;
4968 }
4969}
4970
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004971/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004972/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004973static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004974MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004975 const TemplateArgument &TemplateArg,
4976 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004977 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004978 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004979 switch (TemplateArg.getKind()) {
4980 case TemplateArgument::Null:
4981 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004982 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004983 break;
Mike Stump11289f42009-09-09 15:08:12 +00004984
Eli Friedmanb826a002012-09-26 02:36:12 +00004985 case TemplateArgument::NullPtr:
4986 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4987 Depth, Used);
4988 break;
4989
Douglas Gregor91772d12009-06-13 00:26:55 +00004990 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004991 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004992 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004993 break;
4994
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004995 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004996 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004997 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004999 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005000 break;
5001
5002 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005003 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005004 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005005 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006
Anders Carlssonbc343912009-06-15 17:04:53 +00005007 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005008 for (const auto &P : TemplateArg.pack_elements())
5009 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005010 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005011 }
5012}
5013
James Dennett41725122012-06-22 10:16:05 +00005014/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005015/// template argument list.
5016///
5017/// \param TemplateArgs the template argument list from which template
5018/// parameters will be deduced.
5019///
James Dennett41725122012-06-22 10:16:05 +00005020/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005021/// to indicate when the corresponding template parameter will be
5022/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005023void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005024Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005025 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005026 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005027 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028 // If the template argument list of P contains a pack expansion that is not
5029 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005030 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005031 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005032 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005033 return;
5034
Douglas Gregor91772d12009-06-13 00:26:55 +00005035 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005036 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005037 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005038}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005039
5040/// \brief Marks all of the template parameters that will be deduced by a
5041/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005042void Sema::MarkDeducedTemplateParameters(
5043 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5044 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005046 = FunctionTemplate->getTemplateParameters();
5047 Deduced.clear();
5048 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005049
Douglas Gregorce23bae2009-09-18 23:21:38 +00005050 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5051 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005052 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005053 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005054}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005055
5056bool hasDeducibleTemplateParameters(Sema &S,
5057 FunctionTemplateDecl *FunctionTemplate,
5058 QualType T) {
5059 if (!T->isDependentType())
5060 return false;
5061
5062 TemplateParameterList *TemplateParams
5063 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005064 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005065 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005066 Deduced);
5067
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005068 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005069}