blob: 3b02624e5363d44edbd9b860bb1084e1872f073d [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.
117static NonTypeTemplateParmDecl *getDeducedParameterFromExpr(Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000118 // If we are within an alias template, the expression may have undergone
119 // any number of parameter substitutions already.
120 while (1) {
121 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
122 E = IC->getSubExpr();
123 else if (SubstNonTypeTemplateParmExpr *Subst =
124 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
125 E = Subst->getReplacement();
126 else
127 break;
128 }
Mike Stump11289f42009-09-09 15:08:12 +0000129
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000130 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
131 return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000132
Craig Topperc3ec1492014-05-26 06:22:03 +0000133 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000134}
135
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000136/// \brief Determine whether two declaration pointers refer to the same
137/// declaration.
138static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000139 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
140 X = NX->getUnderlyingDecl();
141 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
142 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000143
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000144 return X->getCanonicalDecl() == Y->getCanonicalDecl();
145}
146
147/// \brief Verify that the given, deduced template arguments are compatible.
148///
149/// \returns The deduced template argument, or a NULL template argument if
150/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000151static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000152checkDeducedTemplateArguments(ASTContext &Context,
153 const DeducedTemplateArgument &X,
154 const DeducedTemplateArgument &Y) {
155 // We have no deduction for one or both of the arguments; they're compatible.
156 if (X.isNull())
157 return Y;
158 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000159 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000160
Richard Smith593d6a12016-12-23 01:30:39 +0000161 // If we have two non-type template argument values deduced for the same
162 // parameter, they must both match the type of the parameter, and thus must
163 // match each other's type. As we're only keeping one of them, we must check
164 // for that now. The exception is that if either was deduced from an array
165 // bound, the type is permitted to differ.
166 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
167 QualType XType = X.getNonTypeTemplateArgumentType();
168 if (!XType.isNull()) {
169 QualType YType = Y.getNonTypeTemplateArgumentType();
170 if (YType.isNull() || !Context.hasSameType(XType, YType))
171 return DeducedTemplateArgument();
172 }
173 }
174
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000175 switch (X.getKind()) {
176 case TemplateArgument::Null:
177 llvm_unreachable("Non-deduced template arguments handled above");
178
179 case TemplateArgument::Type:
180 // If two template type arguments have the same type, they're compatible.
181 if (Y.getKind() == TemplateArgument::Type &&
182 Context.hasSameType(X.getAsType(), Y.getAsType()))
183 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000184
Richard Smith5f274382016-09-28 23:55:27 +0000185 // If one of the two arguments was deduced from an array bound, the other
186 // supersedes it.
187 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
188 return X.wasDeducedFromArrayBound() ? Y : X;
189
190 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000191 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000192
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000193 case TemplateArgument::Integral:
194 // If we deduced a constant in one case and either a dependent expression or
195 // declaration in another case, keep the integral constant.
196 // If both are integral constants with the same value, keep that value.
197 if (Y.getKind() == TemplateArgument::Expression ||
198 Y.getKind() == TemplateArgument::Declaration ||
199 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000200 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000201 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000202
203 // All other combinations are incompatible.
204 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000205
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000206 case TemplateArgument::Template:
207 if (Y.getKind() == TemplateArgument::Template &&
208 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
209 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000210
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000211 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000213
214 case TemplateArgument::TemplateExpansion:
215 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000216 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000217 Y.getAsTemplateOrTemplatePattern()))
218 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000220 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000222
Richard Smith593d6a12016-12-23 01:30:39 +0000223 case TemplateArgument::Expression: {
224 if (Y.getKind() != TemplateArgument::Expression)
225 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000226
Richard Smith593d6a12016-12-23 01:30:39 +0000227 // Compare the expressions for equality
228 llvm::FoldingSetNodeID ID1, ID2;
229 X.getAsExpr()->Profile(ID1, Context, true);
230 Y.getAsExpr()->Profile(ID2, Context, true);
231 if (ID1 == ID2)
232 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000233
Richard Smith593d6a12016-12-23 01:30:39 +0000234 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000235 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000238 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000239 assert(!X.wasDeducedFromArrayBound());
240
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000241 // If we deduced a declaration and a dependent expression, keep the
242 // declaration.
243 if (Y.getKind() == TemplateArgument::Expression)
244 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000245
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000246 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000247 // integral constant and whichever type did not come from an array
248 // bound.
249 if (Y.getKind() == TemplateArgument::Integral) {
250 if (Y.wasDeducedFromArrayBound())
251 return TemplateArgument(Context, Y.getAsIntegral(),
252 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000253 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000256 // If we deduced two declarations, make sure they they refer to the
257 // same declaration.
258 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000259 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000260 return X;
261
262 // All other combinations are incompatible.
263 return DeducedTemplateArgument();
264
265 case TemplateArgument::NullPtr:
266 // If we deduced a null pointer and a dependent expression, keep the
267 // null pointer.
268 if (Y.getKind() == TemplateArgument::Expression)
269 return X;
270
271 // If we deduced a null pointer and an integral constant, keep the
272 // integral constant.
273 if (Y.getKind() == TemplateArgument::Integral)
274 return Y;
275
Richard Smith593d6a12016-12-23 01:30:39 +0000276 // If we deduced two null pointers, they are the same.
277 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000278 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000279
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000280 // All other combinations are incompatible.
281 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000283 case TemplateArgument::Pack:
284 if (Y.getKind() != TemplateArgument::Pack ||
285 X.pack_size() != Y.pack_size())
286 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
288 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000289 XAEnd = X.pack_end(),
290 YA = Y.pack_begin();
291 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000292 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000293 if (checkDeducedTemplateArguments(Context,
294 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000295 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
296 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000297 return DeducedTemplateArgument();
298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000299
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000300 return X;
301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000302
David Blaikiee4d798f2012-01-20 21:50:17 +0000303 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000304}
305
Mike Stump11289f42009-09-09 15:08:12 +0000306/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000307/// from the given integral constant.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000308static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000309 Sema &S, TemplateParameterList *TemplateParams,
310 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000311 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
312 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000313 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000314 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000315
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000316 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
317 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000318 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000319 Deduced[NTTP->getIndex()],
320 NewDeduced);
321 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000322 Info.Param = NTTP;
323 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000324 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000325 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000326 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000328 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000329 return S.getLangOpts().CPlusPlus1z
330 ? DeduceTemplateArgumentsByTypeMatch(
331 S, TemplateParams, NTTP->getType(), ValueType, Info, Deduced,
332 TDF_ParamWithReferenceType | TDF_SkipNonDependent,
333 /*PartialOrdering=*/false,
334 /*ArrayBound=*/DeducedFromArrayBound)
335 : Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000336}
337
Mike Stump11289f42009-09-09 15:08:12 +0000338/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000339/// from the given null pointer template argument type.
340static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000341 Sema &S, TemplateParameterList *TemplateParams,
342 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000343 TemplateDeductionInfo &Info,
344 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
345 Expr *Value =
346 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
347 S.Context.NullPtrTy, NTTP->getLocation()),
348 NullPtrType, CK_NullToPointer)
349 .get();
350 DeducedTemplateArgument NewDeduced(Value);
351 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
352 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
353
354 if (Result.isNull()) {
355 Info.Param = NTTP;
356 Info.FirstArg = Deduced[NTTP->getIndex()];
357 Info.SecondArg = NewDeduced;
358 return Sema::TDK_Inconsistent;
359 }
360
361 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000362 return S.getLangOpts().CPlusPlus1z
363 ? DeduceTemplateArgumentsByTypeMatch(
364 S, TemplateParams, NTTP->getType(), Value->getType(), Info,
365 Deduced, TDF_ParamWithReferenceType | TDF_SkipNonDependent)
366 : Sema::TDK_Success;
Richard Smith38175a22016-09-28 22:08:38 +0000367}
368
369/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000370/// from the given type- or value-dependent expression.
371///
372/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000373static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000374DeduceNonTypeTemplateArgument(Sema &S,
Richard Smith5f274382016-09-28 23:55:27 +0000375 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000376 NonTypeTemplateParmDecl *NTTP,
377 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000378 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000379 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000380 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000381 "Cannot deduce non-type template argument with depth > 0");
382 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
383 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000384
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000385 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000386 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
387 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000388 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000389
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000390 if (Result.isNull()) {
391 Info.Param = NTTP;
392 Info.FirstArg = Deduced[NTTP->getIndex()];
393 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000396
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000397 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000398 return S.getLangOpts().CPlusPlus1z
399 ? DeduceTemplateArgumentsByTypeMatch(
400 S, TemplateParams, NTTP->getType(), Value->getType(), Info,
401 Deduced, TDF_ParamWithReferenceType | TDF_SkipNonDependent)
402 : Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000403}
404
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000405/// \brief Deduce the value of the given non-type template parameter
406/// from the given declaration.
407///
408/// \returns true if deduction succeeded, false otherwise.
409static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000410DeduceNonTypeTemplateArgument(Sema &S,
Richard Smith5f274382016-09-28 23:55:27 +0000411 TemplateParameterList *TemplateParams,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000412 NonTypeTemplateParmDecl *NTTP,
Richard Smith5f274382016-09-28 23:55:27 +0000413 ValueDecl *D, QualType T,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000414 TemplateDeductionInfo &Info,
415 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000416 assert(NTTP->getDepth() == 0 &&
417 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000418
Craig Topperc3ec1492014-05-26 06:22:03 +0000419 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000420 TemplateArgument New(D, T);
Eli Friedmanb826a002012-09-26 02:36:12 +0000421 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000422 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000423 Deduced[NTTP->getIndex()],
424 NewDeduced);
425 if (Result.isNull()) {
426 Info.Param = NTTP;
427 Info.FirstArg = Deduced[NTTP->getIndex()];
428 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000429 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000431
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000432 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000433 return S.getLangOpts().CPlusPlus1z
434 ? DeduceTemplateArgumentsByTypeMatch(
435 S, TemplateParams, NTTP->getType(), T, Info, Deduced,
436 TDF_ParamWithReferenceType | TDF_SkipNonDependent)
437 : Sema::TDK_Success;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000438}
439
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000440static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000441DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000442 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000443 TemplateName Param,
444 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000445 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000446 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000447 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000448 if (!ParamDecl) {
449 // The parameter type is dependent and is not a template template parameter,
450 // so there is nothing that we can deduce.
451 return Sema::TDK_Success;
452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453
Douglas Gregoradee3e32009-11-11 23:06:43 +0000454 if (TemplateTemplateParmDecl *TempParam
455 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000456 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000457 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000458 Deduced[TempParam->getIndex()],
459 NewDeduced);
460 if (Result.isNull()) {
461 Info.Param = TempParam;
462 Info.FirstArg = Deduced[TempParam->getIndex()];
463 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000464 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000465 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000466
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000467 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000469 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
Douglas Gregoradee3e32009-11-11 23:06:43 +0000471 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000472 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000473 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000474
Douglas Gregoradee3e32009-11-11 23:06:43 +0000475 // Mismatch of non-dependent template parameter to argument.
476 Info.FirstArg = TemplateArgument(Param);
477 Info.SecondArg = TemplateArgument(Arg);
478 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000479}
480
Mike Stump11289f42009-09-09 15:08:12 +0000481/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000482/// type (which is a template-id) with the template argument type.
483///
Chandler Carruthc1263112010-02-07 21:33:28 +0000484/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000485///
486/// \param TemplateParams the template parameters that we are deducing
487///
488/// \param Param the parameter type
489///
490/// \param Arg the argument type
491///
492/// \param Info information about the template argument deduction itself
493///
494/// \param Deduced the deduced template arguments
495///
496/// \returns the result of template argument deduction so far. Note that a
497/// "success" result means that template argument deduction has not yet failed,
498/// but it may still fail, later, for other reasons.
499static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000500DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000501 TemplateParameterList *TemplateParams,
502 const TemplateSpecializationType *Param,
503 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000504 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000505 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000506 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000507
Douglas Gregore81f3e72009-07-07 23:09:34 +0000508 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000509 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000510 = dyn_cast<TemplateSpecializationType>(Arg)) {
511 // Perform template argument deduction for the template name.
512 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000513 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000514 Param->getTemplateName(),
515 SpecArg->getTemplateName(),
516 Info, Deduced))
517 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000518
Mike Stump11289f42009-09-09 15:08:12 +0000519
Douglas Gregore81f3e72009-07-07 23:09:34 +0000520 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000521 // argument. Ignore any missing/extra arguments, since they could be
522 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000523 return DeduceTemplateArguments(S, TemplateParams,
524 Param->template_arguments(),
525 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000526 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000527 }
Mike Stump11289f42009-09-09 15:08:12 +0000528
Douglas Gregore81f3e72009-07-07 23:09:34 +0000529 // If the argument type is a class template specialization, we
530 // perform template argument deduction using its template
531 // arguments.
532 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000533 if (!RecordArg) {
534 Info.FirstArg = TemplateArgument(QualType(Param, 0));
535 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000536 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000537 }
Mike Stump11289f42009-09-09 15:08:12 +0000538
539 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000540 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000541 if (!SpecArg) {
542 Info.FirstArg = TemplateArgument(QualType(Param, 0));
543 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000544 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000545 }
Mike Stump11289f42009-09-09 15:08:12 +0000546
Douglas Gregore81f3e72009-07-07 23:09:34 +0000547 // Perform template argument deduction for the template name.
548 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000549 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000550 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000551 Param->getTemplateName(),
552 TemplateName(SpecArg->getSpecializedTemplate()),
553 Info, Deduced))
554 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000555
Douglas Gregor7baabef2010-12-22 18:17:10 +0000556 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000557 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
558 SpecArg->getTemplateArgs().asArray(), Info,
559 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000560}
561
John McCall08569062010-08-28 22:14:41 +0000562/// \brief Determines whether the given type is an opaque type that
563/// might be more qualified when instantiated.
564static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
565 switch (T->getTypeClass()) {
566 case Type::TypeOfExpr:
567 case Type::TypeOf:
568 case Type::DependentName:
569 case Type::Decltype:
570 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000571 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000572 return true;
573
574 case Type::ConstantArray:
575 case Type::IncompleteArray:
576 case Type::VariableArray:
577 case Type::DependentSizedArray:
578 return IsPossiblyOpaquelyQualifiedType(
579 cast<ArrayType>(T)->getElementType());
580
581 default:
582 return false;
583 }
584}
585
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000586/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000588getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000589 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
590 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000591
Douglas Gregor5499af42011-01-05 23:12:31 +0000592 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
593 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594
Douglas Gregor5499af42011-01-05 23:12:31 +0000595 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
596 return std::make_pair(TTP->getDepth(), TTP->getIndex());
597}
598
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000599/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000600static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000601getDepthAndIndex(UnexpandedParameterPack UPP) {
602 if (const TemplateTypeParmType *TTP
603 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
604 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000606 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
607}
608
Douglas Gregor5499af42011-01-05 23:12:31 +0000609/// \brief Helper function to build a TemplateParameter when we don't
610/// know its type statically.
611static TemplateParameter makeTemplateParameter(Decl *D) {
612 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
613 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000614 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000615 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor5499af42011-01-05 23:12:31 +0000617 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
618}
619
Richard Smith0a80d572014-05-29 01:12:14 +0000620/// A pack that we're currently deducing.
621struct clang::DeducedPack {
622 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000623
Richard Smith0a80d572014-05-29 01:12:14 +0000624 // The index of the pack.
625 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Richard Smith0a80d572014-05-29 01:12:14 +0000627 // The old value of the pack before we started deducing it.
628 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000629
Richard Smith0a80d572014-05-29 01:12:14 +0000630 // A deferred value of this pack from an inner deduction, that couldn't be
631 // deduced because this deduction hadn't happened yet.
632 DeducedTemplateArgument DeferredDeduction;
633
634 // The new value of the pack.
635 SmallVector<DeducedTemplateArgument, 4> New;
636
637 // The outer deduction for this pack, if any.
638 DeducedPack *Outer;
639};
640
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000641namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000642/// A scope in which we're performing pack deduction.
643class PackDeductionScope {
644public:
645 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
646 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
647 TemplateDeductionInfo &Info, TemplateArgument Pattern)
648 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
649 // Compute the set of template parameter indices that correspond to
650 // parameter packs expanded by the pack expansion.
651 {
652 llvm::SmallBitVector SawIndices(TemplateParams->size());
653 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
654 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
655 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
656 unsigned Depth, Index;
657 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
658 if (Depth == 0 && !SawIndices[Index]) {
659 SawIndices[Index] = true;
660
661 // Save the deduced template argument for the parameter pack expanded
662 // by this pack expansion, then clear out the deduction.
663 DeducedPack Pack(Index);
664 Pack.Saved = Deduced[Index];
665 Deduced[Index] = TemplateArgument();
666
667 Packs.push_back(Pack);
668 }
669 }
670 }
671 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
672
673 for (auto &Pack : Packs) {
674 if (Info.PendingDeducedPacks.size() > Pack.Index)
675 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
676 else
677 Info.PendingDeducedPacks.resize(Pack.Index + 1);
678 Info.PendingDeducedPacks[Pack.Index] = &Pack;
679
680 if (S.CurrentInstantiationScope) {
681 // If the template argument pack was explicitly specified, add that to
682 // the set of deduced arguments.
683 const TemplateArgument *ExplicitArgs;
684 unsigned NumExplicitArgs;
685 NamedDecl *PartiallySubstitutedPack =
686 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
687 &ExplicitArgs, &NumExplicitArgs);
688 if (PartiallySubstitutedPack &&
689 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
690 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
691 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000692 }
693 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000694
Richard Smith0a80d572014-05-29 01:12:14 +0000695 ~PackDeductionScope() {
696 for (auto &Pack : Packs)
697 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000698 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000699
Richard Smith0a80d572014-05-29 01:12:14 +0000700 /// Move to deducing the next element in each pack that is being deduced.
701 void nextPackElement() {
702 // Capture the deduced template arguments for each parameter pack expanded
703 // by this pack expansion, add them to the list of arguments we've deduced
704 // for that pack, then clear out the deduced argument.
705 for (auto &Pack : Packs) {
706 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
707 if (!DeducedArg.isNull()) {
708 Pack.New.push_back(DeducedArg);
709 DeducedArg = DeducedTemplateArgument();
710 }
711 }
712 }
713
714 /// \brief Finish template argument deduction for a set of argument packs,
715 /// producing the argument packs and checking for consistency with prior
716 /// deductions.
717 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
718 // Build argument packs for each of the parameter packs expanded by this
719 // pack expansion.
720 for (auto &Pack : Packs) {
721 // Put back the old value for this pack.
722 Deduced[Pack.Index] = Pack.Saved;
723
724 // Build or find a new value for this pack.
725 DeducedTemplateArgument NewPack;
726 if (HasAnyArguments && Pack.New.empty()) {
727 if (Pack.DeferredDeduction.isNull()) {
728 // We were not able to deduce anything for this parameter pack
729 // (because it only appeared in non-deduced contexts), so just
730 // restore the saved argument pack.
731 continue;
732 }
733
734 NewPack = Pack.DeferredDeduction;
735 Pack.DeferredDeduction = TemplateArgument();
736 } else if (Pack.New.empty()) {
737 // If we deduced an empty argument pack, create it now.
738 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
739 } else {
740 TemplateArgument *ArgumentPack =
741 new (S.Context) TemplateArgument[Pack.New.size()];
742 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
743 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000744 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000745 Pack.New[0].wasDeducedFromArrayBound());
746 }
747
748 // Pick where we're going to put the merged pack.
749 DeducedTemplateArgument *Loc;
750 if (Pack.Outer) {
751 if (Pack.Outer->DeferredDeduction.isNull()) {
752 // Defer checking this pack until we have a complete pack to compare
753 // it against.
754 Pack.Outer->DeferredDeduction = NewPack;
755 continue;
756 }
757 Loc = &Pack.Outer->DeferredDeduction;
758 } else {
759 Loc = &Deduced[Pack.Index];
760 }
761
762 // Check the new pack matches any previous value.
763 DeducedTemplateArgument OldPack = *Loc;
764 DeducedTemplateArgument Result =
765 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
766
767 // If we deferred a deduction of this pack, check that one now too.
768 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
769 OldPack = Result;
770 NewPack = Pack.DeferredDeduction;
771 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
772 }
773
774 if (Result.isNull()) {
775 Info.Param =
776 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
777 Info.FirstArg = OldPack;
778 Info.SecondArg = NewPack;
779 return Sema::TDK_Inconsistent;
780 }
781
782 *Loc = Result;
783 }
784
785 return Sema::TDK_Success;
786 }
787
788private:
789 Sema &S;
790 TemplateParameterList *TemplateParams;
791 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
792 TemplateDeductionInfo &Info;
793
794 SmallVector<DeducedPack, 2> Packs;
795};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000796} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000797
Douglas Gregor5499af42011-01-05 23:12:31 +0000798/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799/// types to the list of argument types, as in the parameter-type-lists of
800/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000801///
802/// \param S The semantic analysis object within which we are deducing
803///
804/// \param TemplateParams The template parameters that we are deducing
805///
806/// \param Params The list of parameter types
807///
808/// \param NumParams The number of types in \c Params
809///
810/// \param Args The list of argument types
811///
812/// \param NumArgs The number of types in \c Args
813///
814/// \param Info information about the template argument deduction itself
815///
816/// \param Deduced the deduced template arguments
817///
818/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
819/// how template argument deduction is performed.
820///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000821/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000822/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000823/// (C++0x [temp.deduct.partial]).
824///
Douglas Gregor5499af42011-01-05 23:12:31 +0000825/// \returns the result of template argument deduction so far. Note that a
826/// "success" result means that template argument deduction has not yet failed,
827/// but it may still fail, later, for other reasons.
828static Sema::TemplateDeductionResult
829DeduceTemplateArguments(Sema &S,
830 TemplateParameterList *TemplateParams,
831 const QualType *Params, unsigned NumParams,
832 const QualType *Args, unsigned NumArgs,
833 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000834 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000835 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000836 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000837 // Fast-path check to see if we have too many/too few arguments.
838 if (NumParams != NumArgs &&
839 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
840 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000841 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000842
Douglas Gregor5499af42011-01-05 23:12:31 +0000843 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844 // Similarly, if P has a form that contains (T), then each parameter type
845 // Pi of the respective parameter-type- list of P is compared with the
846 // corresponding parameter type Ai of the corresponding parameter-type-list
847 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000848 unsigned ArgIdx = 0, ParamIdx = 0;
849 for (; ParamIdx != NumParams; ++ParamIdx) {
850 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000851 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000852 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
853 if (!Expansion) {
854 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855
Douglas Gregor5499af42011-01-05 23:12:31 +0000856 // Make sure we have an argument.
857 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000858 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000859
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000860 if (isa<PackExpansionType>(Args[ArgIdx])) {
861 // C++0x [temp.deduct.type]p22:
862 // If the original function parameter associated with A is a function
863 // parameter pack and the function parameter associated with P is not
864 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000865 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor5499af42011-01-05 23:12:31 +0000868 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000869 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
870 Params[ParamIdx], Args[ArgIdx],
871 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000872 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000873 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000874
Douglas Gregor5499af42011-01-05 23:12:31 +0000875 ++ArgIdx;
876 continue;
877 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000879 // C++0x [temp.deduct.type]p5:
880 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000882 // parameter-declaration-clause.
883 if (ParamIdx + 1 < NumParams)
884 return Sema::TDK_Success;
885
Douglas Gregor5499af42011-01-05 23:12:31 +0000886 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000887 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000888 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000889 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000890 // comparison deduces template arguments for subsequent positions in the
891 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000892
Douglas Gregor5499af42011-01-05 23:12:31 +0000893 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000894 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000895
Douglas Gregor5499af42011-01-05 23:12:31 +0000896 bool HasAnyArguments = false;
897 for (; ArgIdx < NumArgs; ++ArgIdx) {
898 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000899
Douglas Gregor5499af42011-01-05 23:12:31 +0000900 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000902 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
903 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000904 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000905 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000906
Richard Smith0a80d572014-05-29 01:12:14 +0000907 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909
Douglas Gregor5499af42011-01-05 23:12:31 +0000910 // Build argument packs for each of the parameter packs expanded by this
911 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000912 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000914 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000915
Douglas Gregor5499af42011-01-05 23:12:31 +0000916 // Make sure we don't have any extra arguments.
917 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000918 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000919
Douglas Gregor5499af42011-01-05 23:12:31 +0000920 return Sema::TDK_Success;
921}
922
Douglas Gregor1d684c22011-04-28 00:56:09 +0000923/// \brief Determine whether the parameter has qualifiers that are either
924/// inconsistent with or a superset of the argument's qualifiers.
925static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
926 QualType ArgType) {
927 Qualifiers ParamQs = ParamType.getQualifiers();
928 Qualifiers ArgQs = ArgType.getQualifiers();
929
930 if (ParamQs == ArgQs)
931 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000932
Douglas Gregor1d684c22011-04-28 00:56:09 +0000933 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000934 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000935 ParamQs.hasObjCGCAttr())
936 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000937
Douglas Gregor1d684c22011-04-28 00:56:09 +0000938 // Mismatched (but not missing) address spaces.
939 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
940 ParamQs.hasAddressSpace())
941 return true;
942
John McCall31168b02011-06-15 23:02:42 +0000943 // Mismatched (but not missing) Objective-C lifetime qualifiers.
944 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
945 ParamQs.hasObjCLifetime())
946 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000947
Douglas Gregor1d684c22011-04-28 00:56:09 +0000948 // CVR qualifier superset.
949 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
950 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
951 == ParamQs.getCVRQualifiers());
952}
953
Douglas Gregor19a41f12013-04-17 08:45:07 +0000954/// \brief Compare types for equality with respect to possibly compatible
955/// function types (noreturn adjustment, implicit calling conventions). If any
956/// of parameter and argument is not a function, just perform type comparison.
957///
958/// \param Param the template parameter type.
959///
960/// \param Arg the argument type.
961bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
962 CanQualType Arg) {
963 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
964 *ArgFunction = Arg->getAs<FunctionType>();
965
966 // Just compare if not functions.
967 if (!ParamFunction || !ArgFunction)
968 return Param == Arg;
969
Richard Smith3c4f8d22016-10-16 17:54:23 +0000970 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +0000971 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +0000972 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +0000973 return Arg == Context.getCanonicalType(AdjustedParam);
974
975 // FIXME: Compatible calling conventions.
976
977 return Param == Arg;
978}
979
Douglas Gregorcceb9752009-06-26 18:27:22 +0000980/// \brief Deduce the template arguments by comparing the parameter type and
981/// the argument type (C++ [temp.deduct.type]).
982///
Chandler Carruthc1263112010-02-07 21:33:28 +0000983/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000984///
985/// \param TemplateParams the template parameters that we are deducing
986///
987/// \param ParamIn the parameter type
988///
989/// \param ArgIn the argument type
990///
991/// \param Info information about the template argument deduction itself
992///
993/// \param Deduced the deduced template arguments
994///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000995/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000996/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000997///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000998/// \param PartialOrdering Whether we're performing template argument deduction
999/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1000///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001001/// \returns the result of template argument deduction so far. Note that a
1002/// "success" result means that template argument deduction has not yet failed,
1003/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001004static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001005DeduceTemplateArgumentsByTypeMatch(Sema &S,
1006 TemplateParameterList *TemplateParams,
1007 QualType ParamIn, QualType ArgIn,
1008 TemplateDeductionInfo &Info,
1009 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1010 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001011 bool PartialOrdering,
1012 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001013 // We only want to look at the canonical types, since typedefs and
1014 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001015 QualType Param = S.Context.getCanonicalType(ParamIn);
1016 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001017
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001018 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001020 if (const PackExpansionType *ArgExpansion
1021 = dyn_cast<PackExpansionType>(Arg))
1022 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001023
Douglas Gregorb837ea42011-01-11 17:34:58 +00001024 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001025 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026 // Before the partial ordering is done, certain transformations are
1027 // performed on the types used for partial ordering:
1028 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001029 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1030 if (ParamRef)
1031 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001032
Douglas Gregorb837ea42011-01-11 17:34:58 +00001033 // - If A is a reference type, A is replaced by the type referred to.
1034 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1035 if (ArgRef)
1036 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037
Richard Smithed563c22015-02-20 04:45:22 +00001038 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1039 // C++11 [temp.deduct.partial]p9:
1040 // If, for a given type, deduction succeeds in both directions (i.e.,
1041 // the types are identical after the transformations above) and both
1042 // P and A were reference types [...]:
1043 // - if [one type] was an lvalue reference and [the other type] was
1044 // not, [the other type] is not considered to be at least as
1045 // specialized as [the first type]
1046 // - if [one type] is more cv-qualified than [the other type],
1047 // [the other type] is not considered to be at least as specialized
1048 // as [the first type]
1049 // Objective-C ARC adds:
1050 // - [one type] has non-trivial lifetime, [the other type] has
1051 // __unsafe_unretained lifetime, and the types are otherwise
1052 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001053 //
Richard Smithed563c22015-02-20 04:45:22 +00001054 // A is "considered to be at least as specialized" as P iff deduction
1055 // succeeds, so we model this as a deduction failure. Note that
1056 // [the first type] is P and [the other type] is A here; the standard
1057 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001058 Qualifiers ParamQuals = Param.getQualifiers();
1059 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001060 if ((ParamRef->isLValueReferenceType() &&
1061 !ArgRef->isLValueReferenceType()) ||
1062 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1063 (ParamQuals.hasNonTrivialObjCLifetime() &&
1064 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1065 ParamQuals.withoutObjCLifetime() ==
1066 ArgQuals.withoutObjCLifetime())) {
1067 Info.FirstArg = TemplateArgument(ParamIn);
1068 Info.SecondArg = TemplateArgument(ArgIn);
1069 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001070 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001071 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072
Richard Smithed563c22015-02-20 04:45:22 +00001073 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001074 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001075 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001076 // version of P.
1077 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001078 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001079 // version of A.
1080 Arg = Arg.getUnqualifiedType();
1081 } else {
1082 // C++0x [temp.deduct.call]p4 bullet 1:
1083 // - If the original P is a reference type, the deduced A (i.e., the type
1084 // referred to by the reference) can be more cv-qualified than the
1085 // transformed A.
1086 if (TDF & TDF_ParamWithReferenceType) {
1087 Qualifiers Quals;
1088 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1089 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001090 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001091 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001093
Douglas Gregor85f240c2011-01-25 17:19:08 +00001094 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1095 // C++0x [temp.deduct.type]p10:
1096 // If P and A are function types that originated from deduction when
1097 // taking the address of a function template (14.8.2.2) or when deducing
1098 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001099 // Ai are parameters of the top-level parameter-type-list of P and A,
1100 // respectively, Pi is adjusted if it is an rvalue reference to a
1101 // cv-unqualified template parameter and Ai is an lvalue reference, in
1102 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001103 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1104 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001105 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001106 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107
Douglas Gregor85f240c2011-01-25 17:19:08 +00001108 if (const RValueReferenceType *ParamRef
1109 = Param->getAs<RValueReferenceType>()) {
1110 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1111 !ParamRef->getPointeeType().getQualifiers())
1112 if (Arg->isLValueReferenceType())
1113 Param = ParamRef->getPointeeType();
1114 }
1115 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001117
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001118 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001119 // A template type argument T, a template template argument TT or a
1120 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001121 // the following forms:
1122 //
1123 // T
1124 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001125 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001126 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001127 // Just skip any attempts to deduce from a placeholder type.
1128 if (Arg->isPlaceholderType())
1129 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001130
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001131 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001132 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001133
Douglas Gregor60454822009-07-22 20:02:25 +00001134 // If the argument type is an array type, move the qualifiers up to the
1135 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001136 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001137 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001138 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001139 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001140 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001141 RecanonicalizeArg = true;
1142 }
1143 }
Mike Stump11289f42009-09-09 15:08:12 +00001144
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001145 // The argument type can not be less qualified than the parameter
1146 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001147 if (!(TDF & TDF_IgnoreQualifiers) &&
1148 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001149 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001150 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001151 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001152 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001153 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001154
1155 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001156 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001157 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001158
Douglas Gregor1d684c22011-04-28 00:56:09 +00001159 // Remove any qualifiers on the parameter from the deduced type.
1160 // We checked the qualifiers for consistency above.
1161 Qualifiers DeducedQs = DeducedType.getQualifiers();
1162 Qualifiers ParamQs = Param.getQualifiers();
1163 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1164 if (ParamQs.hasObjCGCAttr())
1165 DeducedQs.removeObjCGCAttr();
1166 if (ParamQs.hasAddressSpace())
1167 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001168 if (ParamQs.hasObjCLifetime())
1169 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001170
Douglas Gregore46db902011-06-17 22:11:49 +00001171 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001172 // If template deduction would produce a lifetime qualifier on a type
1173 // that is not a lifetime type, template argument deduction fails.
1174 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1175 !DeducedType->isDependentType()) {
1176 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1177 Info.FirstArg = TemplateArgument(Param);
1178 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001179 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001180 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001181
Douglas Gregora4f2b432011-07-26 14:53:44 +00001182 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001183 // If template deduction would produce an argument type with lifetime type
1184 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001185 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001186 DeducedType->isObjCLifetimeType() &&
1187 !DeducedQs.hasObjCLifetime())
1188 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001189
Douglas Gregor1d684c22011-04-28 00:56:09 +00001190 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1191 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001192
Douglas Gregord6605db2009-07-22 21:30:48 +00001193 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001194 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001195
Richard Smith5f274382016-09-28 23:55:27 +00001196 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001197 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001198 Deduced[Index],
1199 NewDeduced);
1200 if (Result.isNull()) {
1201 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1202 Info.FirstArg = Deduced[Index];
1203 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001204 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001206
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001207 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001208 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001209 }
1210
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001211 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001212 Info.FirstArg = TemplateArgument(ParamIn);
1213 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001214
Douglas Gregorfb322d82011-01-14 05:11:40 +00001215 // If the parameter is an already-substituted template parameter
1216 // pack, do nothing: we don't know which of its arguments to look
1217 // at, so we have to wait until all of the parameter packs in this
1218 // expansion have arguments.
1219 if (isa<SubstTemplateTypeParmPackType>(Param))
1220 return Sema::TDK_Success;
1221
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001222 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001223 CanQualType CanParam = S.Context.getCanonicalType(Param);
1224 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001225 if (!(TDF & TDF_IgnoreQualifiers)) {
1226 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001227 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001228 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001229 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001230 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001231 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001232 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001233
Douglas Gregor194ea692012-03-11 03:29:50 +00001234 // If the parameter type is not dependent, there is nothing to deduce.
1235 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001236 if (!(TDF & TDF_SkipNonDependent)) {
1237 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1238 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1239 Param != Arg;
1240 if (NonDeduced) {
1241 return Sema::TDK_NonDeducedMismatch;
1242 }
1243 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001244 return Sema::TDK_Success;
1245 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001246 } else if (!Param->isDependentType()) {
1247 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1248 ArgUnqualType = CanArg.getUnqualifiedType();
1249 bool Success = (TDF & TDF_InOverloadResolution)?
1250 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1251 ArgUnqualType) :
1252 ParamUnqualType == ArgUnqualType;
1253 if (Success)
1254 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001255 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001256
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001257 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001258 // Non-canonical types cannot appear here.
1259#define NON_CANONICAL_TYPE(Class, Base) \
1260 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1261#define TYPE(Class, Base)
1262#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001263
Douglas Gregor39c02722011-06-15 16:02:29 +00001264 case Type::TemplateTypeParm:
1265 case Type::SubstTemplateTypeParmPack:
1266 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001267
1268 // These types cannot be dependent, so simply check whether the types are
1269 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001270 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001271 case Type::VariableArray:
1272 case Type::Vector:
1273 case Type::FunctionNoProto:
1274 case Type::Record:
1275 case Type::Enum:
1276 case Type::ObjCObject:
1277 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001278 case Type::ObjCObjectPointer: {
1279 if (TDF & TDF_SkipNonDependent)
1280 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001281
Douglas Gregor194ea692012-03-11 03:29:50 +00001282 if (TDF & TDF_IgnoreQualifiers) {
1283 Param = Param.getUnqualifiedType();
1284 Arg = Arg.getUnqualifiedType();
1285 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001286
Douglas Gregor194ea692012-03-11 03:29:50 +00001287 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1288 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001289
1290 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001291 case Type::Complex:
1292 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001293 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1294 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001295 ComplexArg->getElementType(),
1296 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001297
1298 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001299
1300 // _Atomic T [extension]
1301 case Type::Atomic:
1302 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001303 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001304 cast<AtomicType>(Param)->getValueType(),
1305 AtomicArg->getValueType(),
1306 Info, Deduced, TDF);
1307
1308 return Sema::TDK_NonDeducedMismatch;
1309
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001310 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001311 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001312 QualType PointeeType;
1313 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1314 PointeeType = PointerArg->getPointeeType();
1315 } else if (const ObjCObjectPointerType *PointerArg
1316 = Arg->getAs<ObjCObjectPointerType>()) {
1317 PointeeType = PointerArg->getPointeeType();
1318 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001319 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001320 }
Mike Stump11289f42009-09-09 15:08:12 +00001321
Douglas Gregorfc516c92009-06-26 23:27:24 +00001322 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001323 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1324 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001325 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001326 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001329 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001330 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001331 const LValueReferenceType *ReferenceArg =
1332 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001333 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001334 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001336 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001337 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001338 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001339 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001340
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001341 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001342 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001343 const RValueReferenceType *ReferenceArg =
1344 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001345 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001346 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001347
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001348 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1349 cast<RValueReferenceType>(Param)->getPointeeType(),
1350 ReferenceArg->getPointeeType(),
1351 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001354 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001355 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001356 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001357 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001358 if (!IncompleteArrayArg)
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;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001362 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1363 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1364 IncompleteArrayArg->getElementType(),
1365 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001366 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001367
1368 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001369 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001370 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001371 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001372 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001373 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001374
1375 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001376 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001377 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001378 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001379
John McCallf7332682010-08-19 00:20:19 +00001380 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001381 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1382 ConstantArrayParm->getElementType(),
1383 ConstantArrayArg->getElementType(),
1384 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001385 }
1386
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001387 // type [i]
1388 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001389 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001390 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001391 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001392
John McCallf7332682010-08-19 00:20:19 +00001393 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1394
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001395 // Check the element type of the arrays
1396 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001397 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001398 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001399 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1400 DependentArrayParm->getElementType(),
1401 ArrayArg->getElementType(),
1402 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001403 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001404
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001405 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001406 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001407 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1408 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001409 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001410
1411 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001412 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001413 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001414 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001415 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001416 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1417 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001418 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001419 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001420 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001421 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001422 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001423 if (const DependentSizedArrayType *DependentArrayArg
1424 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001425 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001426 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001427 DependentArrayArg->getSizeExpr(),
1428 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001429
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001430 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001431 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001432 }
Mike Stump11289f42009-09-09 15:08:12 +00001433
1434 // type(*)(T)
1435 // T(*)()
1436 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001437 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001438 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001439 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001440 dyn_cast<FunctionProtoType>(Arg);
1441 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001442 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001443
1444 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001445 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001446
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001447 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001448 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001449 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001450 != FunctionProtoArg->getRefQualifier() ||
1451 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001452 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001453
Anders Carlsson2128ec72009-06-08 15:19:08 +00001454 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001455 if (Sema::TemplateDeductionResult Result =
1456 DeduceTemplateArgumentsByTypeMatch(
1457 S, TemplateParams, FunctionProtoParam->getReturnType(),
1458 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001459 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001460
Alp Toker9cacbab2014-01-20 20:26:09 +00001461 return DeduceTemplateArguments(
1462 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1463 FunctionProtoParam->getNumParams(),
1464 FunctionProtoArg->param_type_begin(),
1465 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001466 }
Mike Stump11289f42009-09-09 15:08:12 +00001467
John McCalle78aac42010-03-10 03:28:59 +00001468 case Type::InjectedClassName: {
1469 // Treat a template's injected-class-name as if the template
1470 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001471 Param = cast<InjectedClassNameType>(Param)
1472 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001473 assert(isa<TemplateSpecializationType>(Param) &&
1474 "injected class name is not a template specialization type");
1475 // fall through
1476 }
1477
Douglas Gregor705c9002009-06-26 20:57:09 +00001478 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001479 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001480 // TT<T>
1481 // TT<i>
1482 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001483 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001484 const TemplateSpecializationType *SpecParam =
1485 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001486
Richard Smith9b296e32016-04-25 19:09:05 +00001487 // When Arg cannot be a derived class, we can just try to deduce template
1488 // arguments from the template-id.
1489 const RecordType *RecordT = Arg->getAs<RecordType>();
1490 if (!(TDF & TDF_DerivedClass) || !RecordT)
1491 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1492 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001493
Richard Smith9b296e32016-04-25 19:09:05 +00001494 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1495 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001496
Richard Smith9b296e32016-04-25 19:09:05 +00001497 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1498 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001499
Richard Smith9b296e32016-04-25 19:09:05 +00001500 if (Result == Sema::TDK_Success)
1501 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001502
Richard Smith9b296e32016-04-25 19:09:05 +00001503 // We cannot inspect base classes as part of deduction when the type
1504 // is incomplete, so either instantiate any templates necessary to
1505 // complete the type, or skip over it if it cannot be completed.
1506 if (!S.isCompleteType(Info.getLocation(), Arg))
1507 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001508
Richard Smith9b296e32016-04-25 19:09:05 +00001509 // C++14 [temp.deduct.call] p4b3:
1510 // If P is a class and P has the form simple-template-id, then the
1511 // transformed A can be a derived class of the deduced A. Likewise if
1512 // P is a pointer to a class of the form simple-template-id, the
1513 // transformed A can be a pointer to a derived class pointed to by the
1514 // deduced A.
1515 //
1516 // These alternatives are considered only if type deduction would
1517 // otherwise fail. If they yield more than one possible deduced A, the
1518 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001519
Faisal Vali683b0742016-05-19 02:28:21 +00001520 // Reset the incorrectly deduced argument from above.
1521 Deduced = DeducedOrig;
1522
1523 // Use data recursion to crawl through the list of base classes.
1524 // Visited contains the set of nodes we have already visited, while
1525 // ToVisit is our stack of records that we still need to visit.
1526 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1527 SmallVector<const RecordType *, 8> ToVisit;
1528 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001529 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001530 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001531 while (!ToVisit.empty()) {
1532 // Retrieve the next class in the inheritance hierarchy.
1533 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001534
Faisal Vali683b0742016-05-19 02:28:21 +00001535 // If we have already seen this type, skip it.
1536 if (!Visited.insert(NextT).second)
1537 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001538
Faisal Vali683b0742016-05-19 02:28:21 +00001539 // If this is a base class, try to perform template argument
1540 // deduction from it.
1541 if (NextT != RecordT) {
1542 TemplateDeductionInfo BaseInfo(Info.getLocation());
1543 Sema::TemplateDeductionResult BaseResult =
1544 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1545 QualType(NextT, 0), BaseInfo, Deduced);
1546
1547 // If template argument deduction for this base was successful,
1548 // note that we had some success. Otherwise, ignore any deductions
1549 // from this base class.
1550 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001551 // If we've already seen some success, then deduction fails due to
1552 // an ambiguity (temp.deduct.call p5).
1553 if (Successful)
1554 return Sema::TDK_MiscellaneousDeductionFailure;
1555
Faisal Vali683b0742016-05-19 02:28:21 +00001556 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001557 std::swap(SuccessfulDeduced, Deduced);
1558
Faisal Vali683b0742016-05-19 02:28:21 +00001559 Info.Param = BaseInfo.Param;
1560 Info.FirstArg = BaseInfo.FirstArg;
1561 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001562 }
1563
1564 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001565 }
Mike Stump11289f42009-09-09 15:08:12 +00001566
Faisal Vali683b0742016-05-19 02:28:21 +00001567 // Visit base classes
1568 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1569 for (const auto &Base : Next->bases()) {
1570 assert(Base.getType()->isRecordType() &&
1571 "Base class that isn't a record?");
1572 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1573 }
1574 }
Mike Stump11289f42009-09-09 15:08:12 +00001575
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001576 if (Successful) {
1577 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001578 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001579 }
Richard Smith9b296e32016-04-25 19:09:05 +00001580
Douglas Gregore81f3e72009-07-07 23:09:34 +00001581 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001582 }
1583
Douglas Gregor637d9982009-06-10 23:47:09 +00001584 // T type::*
1585 // T T::*
1586 // T (type::*)()
1587 // type (T::*)()
1588 // type (type::*)(T)
1589 // type (T::*)(T)
1590 // T (type::*)(T)
1591 // T (T::*)()
1592 // T (T::*)(T)
1593 case Type::MemberPointer: {
1594 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1595 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1596 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001597 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001598
David Majnemera381cda2015-11-30 20:34:28 +00001599 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1600 if (ParamPointeeType->isFunctionType())
1601 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1602 /*IsCtorOrDtor=*/false, Info.getLocation());
1603 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1604 if (ArgPointeeType->isFunctionType())
1605 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1606 /*IsCtorOrDtor=*/false, Info.getLocation());
1607
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001608 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001609 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001610 ParamPointeeType,
1611 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001612 Info, Deduced,
1613 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001614 return Result;
1615
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001616 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1617 QualType(MemPtrParam->getClass(), 0),
1618 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001619 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001620 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001621 }
1622
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001623 // (clang extension)
1624 //
Mike Stump11289f42009-09-09 15:08:12 +00001625 // type(^)(T)
1626 // T(^)()
1627 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001628 case Type::BlockPointer: {
1629 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1630 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001631
Anders Carlssona767eee2009-06-12 16:23:10 +00001632 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001633 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001634
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001635 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1636 BlockPtrParam->getPointeeType(),
1637 BlockPtrArg->getPointeeType(),
1638 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001639 }
1640
Douglas Gregor39c02722011-06-15 16:02:29 +00001641 // (clang extension)
1642 //
1643 // T __attribute__(((ext_vector_type(<integral constant>))))
1644 case Type::ExtVector: {
1645 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1646 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1647 // Make sure that the vectors have the same number of elements.
1648 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1649 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001650
Douglas Gregor39c02722011-06-15 16:02:29 +00001651 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001652 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1653 VectorParam->getElementType(),
1654 VectorArg->getElementType(),
1655 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001656 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001657
1658 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001659 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1660 // We can't check the number of elements, since the argument has a
1661 // dependent number of elements. This can only occur during partial
1662 // ordering.
1663
1664 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001665 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1666 VectorParam->getElementType(),
1667 VectorArg->getElementType(),
1668 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001669 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001670
Douglas Gregor39c02722011-06-15 16:02:29 +00001671 return Sema::TDK_NonDeducedMismatch;
1672 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001673
Douglas Gregor39c02722011-06-15 16:02:29 +00001674 // (clang extension)
1675 //
1676 // T __attribute__(((ext_vector_type(N))))
1677 case Type::DependentSizedExtVector: {
1678 const DependentSizedExtVectorType *VectorParam
1679 = cast<DependentSizedExtVectorType>(Param);
1680
1681 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1682 // Perform deduction on the element types.
1683 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001684 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1685 VectorParam->getElementType(),
1686 VectorArg->getElementType(),
1687 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001688 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001689
Douglas Gregor39c02722011-06-15 16:02:29 +00001690 // Perform deduction on the vector size, if we can.
1691 NonTypeTemplateParmDecl *NTTP
1692 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1693 if (!NTTP)
1694 return Sema::TDK_Success;
1695
1696 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1697 ArgSize = VectorArg->getNumElements();
Richard Smith5f274382016-09-28 23:55:27 +00001698 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith593d6a12016-12-23 01:30:39 +00001699 S.Context.IntTy, false, Info,
1700 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001701 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001702
1703 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001704 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1705 // Perform deduction on the element types.
1706 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001707 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1708 VectorParam->getElementType(),
1709 VectorArg->getElementType(),
1710 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001711 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001712
Douglas Gregor39c02722011-06-15 16:02:29 +00001713 // Perform deduction on the vector size, if we can.
1714 NonTypeTemplateParmDecl *NTTP
1715 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1716 if (!NTTP)
1717 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001718
Richard Smith5f274382016-09-28 23:55:27 +00001719 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1720 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001721 Info, Deduced);
1722 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001723
Douglas Gregor39c02722011-06-15 16:02:29 +00001724 return Sema::TDK_NonDeducedMismatch;
1725 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001726
Douglas Gregor637d9982009-06-10 23:47:09 +00001727 case Type::TypeOfExpr:
1728 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001729 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001730 case Type::UnresolvedUsing:
1731 case Type::Decltype:
1732 case Type::UnaryTransform:
1733 case Type::Auto:
1734 case Type::DependentTemplateSpecialization:
1735 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001736 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001737 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001738 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001739 }
1740
David Blaikiee4d798f2012-01-20 21:50:17 +00001741 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001742}
1743
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001744static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001745DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001746 TemplateParameterList *TemplateParams,
1747 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001748 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001749 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001750 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001751 // If the template argument is a pack expansion, perform template argument
1752 // deduction against the pattern of that expansion. This only occurs during
1753 // partial ordering.
1754 if (Arg.isPackExpansion())
1755 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001756
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001757 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001758 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001759 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001760
1761 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001762 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001763 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1764 Param.getAsType(),
1765 Arg.getAsType(),
1766 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001767 Info.FirstArg = Param;
1768 Info.SecondArg = Arg;
1769 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001770
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001771 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001772 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001773 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001774 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001775 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001776 Info.FirstArg = Param;
1777 Info.SecondArg = Arg;
1778 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001779
1780 case TemplateArgument::TemplateExpansion:
1781 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001782
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001783 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001784 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001785 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001786 return Sema::TDK_Success;
1787
1788 Info.FirstArg = Param;
1789 Info.SecondArg = Arg;
1790 return Sema::TDK_NonDeducedMismatch;
1791
1792 case TemplateArgument::NullPtr:
1793 if (Arg.getKind() == TemplateArgument::NullPtr &&
1794 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001795 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001796
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001797 Info.FirstArg = Param;
1798 Info.SecondArg = Arg;
1799 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001800
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001801 case TemplateArgument::Integral:
1802 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001803 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001804 return Sema::TDK_Success;
1805
1806 Info.FirstArg = Param;
1807 Info.SecondArg = Arg;
1808 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001809 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001810
1811 if (Arg.getKind() == TemplateArgument::Expression) {
1812 Info.FirstArg = Param;
1813 Info.SecondArg = Arg;
1814 return Sema::TDK_NonDeducedMismatch;
1815 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001816
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001817 Info.FirstArg = Param;
1818 Info.SecondArg = Arg;
1819 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001820
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001821 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001822 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001823 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1824 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001825 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001826 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001827 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001828 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001829 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001830 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001831 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1832 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001833 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001834 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001835 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1836 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001837 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001838 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1839 Arg.getAsDecl(),
1840 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001841 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001842
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001843 Info.FirstArg = Param;
1844 Info.SecondArg = Arg;
1845 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001846 }
Mike Stump11289f42009-09-09 15:08:12 +00001847
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001848 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001849 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001850 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001851 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001852 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001853 }
Mike Stump11289f42009-09-09 15:08:12 +00001854
David Blaikiee4d798f2012-01-20 21:50:17 +00001855 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001856}
1857
Douglas Gregor7baabef2010-12-22 18:17:10 +00001858/// \brief Determine whether there is a template argument to be used for
1859/// deduction.
1860///
1861/// This routine "expands" argument packs in-place, overriding its input
1862/// parameters so that \c Args[ArgIdx] will be the available template argument.
1863///
1864/// \returns true if there is another template argument (which will be at
1865/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001866static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1867 unsigned &ArgIdx) {
1868 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001869 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001870
Douglas Gregor7baabef2010-12-22 18:17:10 +00001871 const TemplateArgument &Arg = Args[ArgIdx];
1872 if (Arg.getKind() != TemplateArgument::Pack)
1873 return true;
1874
Richard Smith0bda5b52016-12-23 23:46:56 +00001875 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1876 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001877 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001878 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001879}
1880
Douglas Gregord0ad2942010-12-23 01:24:45 +00001881/// \brief Determine whether the given set of template arguments has a pack
1882/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001883static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1884 bool FoundPackExpansion = false;
1885 for (const auto &A : Args) {
1886 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001887 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001888
1889 if (A.getKind() == TemplateArgument::Pack)
1890 return hasPackExpansionBeforeEnd(A.pack_elements());
1891
1892 if (A.isPackExpansion())
1893 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001895
Douglas Gregord0ad2942010-12-23 01:24:45 +00001896 return false;
1897}
1898
Douglas Gregor7baabef2010-12-22 18:17:10 +00001899static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001900DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001901 ArrayRef<TemplateArgument> Params,
1902 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001903 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001904 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1905 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001906 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001907 // If the template argument list of P contains a pack expansion that is not
1908 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001909 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001910 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001911 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001912
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001913 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914 // If P has a form that contains <T> or <i>, then each argument Pi of the
1915 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001916 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001917 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001918 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001919 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001920 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001921
Douglas Gregor7baabef2010-12-22 18:17:10 +00001922 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001923 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001924 return NumberOfArgumentsMustMatch ? Sema::TDK_TooFewArguments
1925 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001927 if (Args[ArgIdx].isPackExpansion()) {
1928 // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1929 // but applied to pack expansions that are template arguments.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001930 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001932
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001933 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001934 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001935 = DeduceTemplateArguments(S, TemplateParams,
1936 Params[ParamIdx], Args[ArgIdx],
1937 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938 return Result;
1939
Douglas Gregor7baabef2010-12-22 18:17:10 +00001940 // Move to the next argument.
1941 ++ArgIdx;
1942 continue;
1943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001945 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001947 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001948 // If Pi is a pack expansion, then the pattern of Pi is compared with
1949 // each remaining argument in the template argument list of A. Each
1950 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001951 // template parameter packs expanded by Pi.
1952 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001954 // FIXME: If there are no remaining arguments, we can bail out early
1955 // and set any deduced parameter packs to an empty argument pack.
1956 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957
Richard Smith0a80d572014-05-29 01:12:14 +00001958 // Prepare to deduce the packs within the pattern.
1959 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001960
1961 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001963 // template argument (the inner SmallVectors).
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001964 bool HasAnyArguments = false;
Richard Smith0bda5b52016-12-23 23:46:56 +00001965 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001966 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001968 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001969 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001970 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1971 Info, Deduced))
1972 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001973
Richard Smith0a80d572014-05-29 01:12:14 +00001974 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001975 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001977 // Build argument packs for each of the parameter packs expanded by this
1978 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00001979 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Douglas Gregor7baabef2010-12-22 18:17:10 +00001983 return Sema::TDK_Success;
1984}
1985
Mike Stump11289f42009-09-09 15:08:12 +00001986static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001987DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001988 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001989 const TemplateArgumentList &ParamList,
1990 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00001991 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001992 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00001993 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
1994 ArgList.asArray(), Info, Deduced, false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001995}
1996
Douglas Gregor705c9002009-06-26 20:57:09 +00001997/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00001998static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00001999 const TemplateArgument &X,
2000 const TemplateArgument &Y) {
2001 if (X.getKind() != Y.getKind())
2002 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002003
Douglas Gregor705c9002009-06-26 20:57:09 +00002004 switch (X.getKind()) {
2005 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002006 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002007
Douglas Gregor705c9002009-06-26 20:57:09 +00002008 case TemplateArgument::Type:
2009 return Context.getCanonicalType(X.getAsType()) ==
2010 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002011
Douglas Gregor705c9002009-06-26 20:57:09 +00002012 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002013 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002014
2015 case TemplateArgument::NullPtr:
2016 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002017
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002018 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002019 case TemplateArgument::TemplateExpansion:
2020 return Context.getCanonicalTemplateName(
2021 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2022 Context.getCanonicalTemplateName(
2023 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024
Douglas Gregor705c9002009-06-26 20:57:09 +00002025 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002026 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00002027
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002028 case TemplateArgument::Expression: {
2029 llvm::FoldingSetNodeID XID, YID;
2030 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002032 return XID == YID;
2033 }
Mike Stump11289f42009-09-09 15:08:12 +00002034
Douglas Gregor705c9002009-06-26 20:57:09 +00002035 case TemplateArgument::Pack:
2036 if (X.pack_size() != Y.pack_size())
2037 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002038
2039 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2040 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002041 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002042 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00002043 if (!isSameTemplateArg(Context, *XP, *YP))
2044 return false;
2045
2046 return true;
2047 }
2048
David Blaikiee4d798f2012-01-20 21:50:17 +00002049 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002050}
2051
Douglas Gregorca4686d2011-01-04 23:35:54 +00002052/// \brief Allocate a TemplateArgumentLoc where all locations have
2053/// been initialized to the given location.
2054///
James Dennett634962f2012-06-14 21:40:34 +00002055/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002056/// location information for.
2057///
2058/// \param NTTPType For a declaration template argument, the type of
2059/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002060/// argument. Can be null if no type sugar is available to add to the
2061/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002062///
2063/// \param Loc The source location to use for the resulting template
2064/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002065TemplateArgumentLoc
2066Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2067 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002068 switch (Arg.getKind()) {
2069 case TemplateArgument::Null:
2070 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071
Douglas Gregorca4686d2011-01-04 23:35:54 +00002072 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002073 return TemplateArgumentLoc(
2074 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002075
Douglas Gregorca4686d2011-01-04 23:35:54 +00002076 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002077 if (NTTPType.isNull())
2078 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002079 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2080 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002081 return TemplateArgumentLoc(TemplateArgument(E), E);
2082 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083
Eli Friedmanb826a002012-09-26 02:36:12 +00002084 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002085 if (NTTPType.isNull())
2086 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002087 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2088 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002089 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2090 E);
2091 }
2092
Douglas Gregorca4686d2011-01-04 23:35:54 +00002093 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002094 Expr *E =
2095 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002096 return TemplateArgumentLoc(TemplateArgument(E), E);
2097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098
Douglas Gregor9d802122011-03-02 17:09:35 +00002099 case TemplateArgument::Template:
2100 case TemplateArgument::TemplateExpansion: {
2101 NestedNameSpecifierLocBuilder Builder;
2102 TemplateName Template = Arg.getAsTemplate();
2103 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002104 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002105 else if (QualifiedTemplateName *QTN =
2106 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002107 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002108
Douglas Gregor9d802122011-03-02 17:09:35 +00002109 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002110 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002111 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002112
2113 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002114 Loc, Loc);
2115 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002116
Douglas Gregorca4686d2011-01-04 23:35:54 +00002117 case TemplateArgument::Expression:
2118 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002119
Douglas Gregorca4686d2011-01-04 23:35:54 +00002120 case TemplateArgument::Pack:
2121 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002123
David Blaikiee4d798f2012-01-20 21:50:17 +00002124 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002125}
2126
2127
2128/// \brief Convert the given deduced template argument and add it to the set of
2129/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002130static bool
2131ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2132 DeducedTemplateArgument Arg,
2133 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002134 TemplateDeductionInfo &Info,
2135 bool InFunctionTemplate,
2136 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002137 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2138 unsigned ArgumentPackIndex) {
2139 // Convert the deduced template argument into a template
2140 // argument that we can check, almost as if the user had written
2141 // the template argument explicitly.
2142 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002143 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002144
2145 // Check the template argument, converting it as necessary.
2146 return S.CheckTemplateArgument(
2147 Param, ArgLoc, Template, Template->getLocation(),
2148 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2149 InFunctionTemplate
2150 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2151 : Sema::CTAK_Deduced)
2152 : Sema::CTAK_Specified);
2153 };
2154
Douglas Gregorca4686d2011-01-04 23:35:54 +00002155 if (Arg.getKind() == TemplateArgument::Pack) {
2156 // This is a template argument pack, so check each of its arguments against
2157 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002158 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002159 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002160 // When converting the deduced template argument, append it to the
2161 // general output list. We need to do this so that the template argument
2162 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002163 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002164 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002165 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2166 "deduced nested pack");
2167 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002168 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002169
Douglas Gregor51bc5712011-01-05 20:52:18 +00002170 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002171 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002172 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173
Richard Smithdf18ee92016-02-03 20:40:30 +00002174 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002175 // itself, in case that substitution fails.
2176 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002177 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002178 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002179 MultiLevelTemplateArgumentList Args(TemplateArgs);
2180
2181 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2182 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2183 NTTP, Output,
2184 Template->getSourceRange());
2185 if (Inst.isInvalid() ||
2186 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2187 NTTP->getDeclName()).isNull())
2188 return true;
2189 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2190 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2191 TTP, Output,
2192 Template->getSourceRange());
2193 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2194 return true;
2195 }
2196 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002197 }
Richard Smith37acb792016-02-03 20:15:01 +00002198
Douglas Gregorca4686d2011-01-04 23:35:54 +00002199 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002200 Output.push_back(
2201 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002202 return false;
2203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002204
Richard Smith37acb792016-02-03 20:15:01 +00002205 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002206}
2207
Richard Smith1f5be4d2016-12-21 01:10:31 +00002208// FIXME: This should not be a template, but
2209// ClassTemplatePartialSpecializationDecl sadly does not derive from
2210// TemplateDecl.
2211template<typename TemplateDeclT>
2212static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2213 Sema &S, TemplateDeclT *Template,
2214 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2215 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2216 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2217 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2218 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2219
2220 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2221 NamedDecl *Param = TemplateParams->getParam(I);
2222
2223 if (!Deduced[I].isNull()) {
2224 if (I < NumAlreadyConverted) {
2225 // We have already fully type-checked and converted this
2226 // argument, because it was explicitly-specified. Just record the
2227 // presence of this argument.
2228 Builder.push_back(Deduced[I]);
2229 // We may have had explicitly-specified template arguments for a
2230 // template parameter pack (that may or may not have been extended
2231 // via additional deduced arguments).
2232 if (Param->isParameterPack() && CurrentInstantiationScope) {
2233 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2234 Param) {
2235 // Forget the partially-substituted pack; its substitution is now
2236 // complete.
2237 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2238 }
2239 }
2240 continue;
2241 }
2242
2243 // We have deduced this argument, so it still needs to be
2244 // checked and converted.
2245 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2246 isa<FunctionTemplateDecl>(Template),
2247 Builder)) {
2248 Info.Param = makeTemplateParameter(Param);
2249 // FIXME: These template arguments are temporary. Free them!
2250 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2251 return Sema::TDK_SubstitutionFailure;
2252 }
2253
2254 continue;
2255 }
2256
2257 // C++0x [temp.arg.explicit]p3:
2258 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2259 // be deduced to an empty sequence of template arguments.
2260 // FIXME: Where did the word "trailing" come from?
2261 if (Param->isTemplateParameterPack()) {
2262 // We may have had explicitly-specified template arguments for this
2263 // template parameter pack. If so, our empty deduction extends the
2264 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2265 const TemplateArgument *ExplicitArgs;
2266 unsigned NumExplicitArgs;
2267 if (CurrentInstantiationScope &&
2268 CurrentInstantiationScope->getPartiallySubstitutedPack(
2269 &ExplicitArgs, &NumExplicitArgs) == Param) {
2270 Builder.push_back(TemplateArgument(
2271 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2272
2273 // Forget the partially-substituted pack; its substitution is now
2274 // complete.
2275 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2276 } else {
2277 // Go through the motions of checking the empty argument pack against
2278 // the parameter pack.
2279 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2280 if (ConvertDeducedTemplateArgument(
2281 S, Param, DeducedPack, Template, Info,
2282 isa<FunctionTemplateDecl>(Template), Builder)) {
2283 Info.Param = makeTemplateParameter(Param);
2284 // FIXME: These template arguments are temporary. Free them!
2285 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2286 return Sema::TDK_SubstitutionFailure;
2287 }
2288 }
2289 continue;
2290 }
2291
2292 // Substitute into the default template argument, if available.
2293 bool HasDefaultArg = false;
2294 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2295 if (!TD) {
2296 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2297 return Sema::TDK_Incomplete;
2298 }
2299
2300 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2301 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2302 HasDefaultArg);
2303
2304 // If there was no default argument, deduction is incomplete.
2305 if (DefArg.getArgument().isNull()) {
2306 Info.Param = makeTemplateParameter(
2307 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2308 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2309 if (PartialOverloading) break;
2310
2311 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2312 : Sema::TDK_Incomplete;
2313 }
2314
2315 // Check whether we can actually use the default argument.
2316 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2317 TD->getSourceRange().getEnd(), 0, Builder,
2318 Sema::CTAK_Specified)) {
2319 Info.Param = makeTemplateParameter(
2320 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2321 // FIXME: These template arguments are temporary. Free them!
2322 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2323 return Sema::TDK_SubstitutionFailure;
2324 }
2325
2326 // If we get here, we successfully used the default template argument.
2327 }
2328
2329 return Sema::TDK_Success;
2330}
2331
Richard Smith0da6dc42016-12-24 16:40:51 +00002332DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2333 if (auto *DC = dyn_cast<DeclContext>(D))
2334 return DC;
2335 return D->getDeclContext();
2336}
2337
2338template<typename T> struct IsPartialSpecialization {
2339 static constexpr bool value = false;
2340};
2341template<>
2342struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2343 static constexpr bool value = true;
2344};
2345template<>
2346struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2347 static constexpr bool value = true;
2348};
2349
2350/// Complete template argument deduction for a partial specialization.
2351template <typename T>
2352static typename std::enable_if<IsPartialSpecialization<T>::value,
2353 Sema::TemplateDeductionResult>::type
2354FinishTemplateArgumentDeduction(
2355 Sema &S, T *Partial, const TemplateArgumentList &TemplateArgs,
2356 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2357 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002358 // Unevaluated SFINAE context.
2359 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002360 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002361
Richard Smith0da6dc42016-12-24 16:40:51 +00002362 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002363
2364 // C++ [temp.deduct.type]p2:
2365 // [...] or if any template argument remains neither deduced nor
2366 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002367 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002368 if (auto Result = ConvertDeducedTemplateArguments(S, Partial, Deduced,
2369 Info, Builder))
2370 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002371
Douglas Gregor684268d2010-04-29 06:21:43 +00002372 // Form the template argument list from the deduced template arguments.
2373 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002374 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002375
Douglas Gregor684268d2010-04-29 06:21:43 +00002376 Info.reset(DeducedArgumentList);
2377
2378 // Substitute the deduced template arguments into the template
2379 // arguments of the class template partial specialization, and
2380 // verify that the instantiated template arguments are both valid
2381 // and are equivalent to the template arguments originally provided
2382 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002383 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002384 auto *Template = Partial->getSpecializedTemplate();
2385 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2386 Partial->getTemplateArgsAsWritten();
2387 const TemplateArgumentLoc *PartialTemplateArgs =
2388 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002389
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002390 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2391 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002392
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002393 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002394 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2395 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2396 if (ParamIdx >= Partial->getTemplateParameters()->size())
2397 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2398
Richard Smith0da6dc42016-12-24 16:40:51 +00002399 Decl *Param = const_cast<NamedDecl *>(
2400 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002401 Info.Param = makeTemplateParameter(Param);
2402 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2403 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002404 }
2405
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002406 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002407 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2408 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002409 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002410
Richard Smith0da6dc42016-12-24 16:40:51 +00002411 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002412 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002413 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002414 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002415 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002416 Info.FirstArg = TemplateArgs[I];
2417 Info.SecondArg = InstArg;
2418 return Sema::TDK_NonDeducedMismatch;
2419 }
2420 }
2421
2422 if (Trap.hasErrorOccurred())
2423 return Sema::TDK_SubstitutionFailure;
2424
2425 return Sema::TDK_Success;
2426}
2427
Douglas Gregor170bc422009-06-12 22:31:52 +00002428/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002429/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002430/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002431Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002432Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002433 const TemplateArgumentList &TemplateArgs,
2434 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002435 if (Partial->isInvalidDecl())
2436 return TDK_Invalid;
2437
Douglas Gregor170bc422009-06-12 22:31:52 +00002438 // C++ [temp.class.spec.match]p2:
2439 // A partial specialization matches a given actual template
2440 // argument list if the template arguments of the partial
2441 // specialization can be deduced from the actual template argument
2442 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002443
2444 // Unevaluated SFINAE context.
2445 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002446 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002447
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002448 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002449 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002450 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002451 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002452 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002453 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002454 TemplateArgs, Info, Deduced))
2455 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002456
Richard Smith80934652012-07-16 01:09:10 +00002457 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002458 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2459 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002460 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002461 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002462
Douglas Gregore1416332009-06-14 08:02:22 +00002463 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002464 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002465
2466 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002467 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002468}
Douglas Gregor91772d12009-06-13 00:26:55 +00002469
Larisse Voufo39a1e502013-08-06 01:03:05 +00002470/// \brief Perform template argument deduction to determine whether
2471/// the given template arguments match the given variable template
2472/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002473Sema::TemplateDeductionResult
2474Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2475 const TemplateArgumentList &TemplateArgs,
2476 TemplateDeductionInfo &Info) {
2477 if (Partial->isInvalidDecl())
2478 return TDK_Invalid;
2479
2480 // C++ [temp.class.spec.match]p2:
2481 // A partial specialization matches a given actual template
2482 // argument list if the template arguments of the partial
2483 // specialization can be deduced from the actual template argument
2484 // list (14.8.2).
2485
2486 // Unevaluated SFINAE context.
2487 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2488 SFINAETrap Trap(*this);
2489
2490 SmallVector<DeducedTemplateArgument, 4> Deduced;
2491 Deduced.resize(Partial->getTemplateParameters()->size());
2492 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2493 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2494 TemplateArgs, Info, Deduced))
2495 return Result;
2496
2497 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002498 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2499 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002500 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002501 return TDK_InstantiationDepth;
2502
2503 if (Trap.hasErrorOccurred())
2504 return Sema::TDK_SubstitutionFailure;
2505
2506 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2507 Deduced, Info);
2508}
2509
Douglas Gregorfc516c92009-06-26 23:27:24 +00002510/// \brief Determine whether the given type T is a simple-template-id type.
2511static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002512 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002513 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002514 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002515
Douglas Gregorfc516c92009-06-26 23:27:24 +00002516 return false;
2517}
Douglas Gregor9b146582009-07-08 20:55:45 +00002518
2519/// \brief Substitute the explicitly-provided template arguments into the
2520/// given function template according to C++ [temp.arg.explicit].
2521///
2522/// \param FunctionTemplate the function template into which the explicit
2523/// template arguments will be substituted.
2524///
James Dennett634962f2012-06-14 21:40:34 +00002525/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002526/// arguments.
2527///
Mike Stump11289f42009-09-09 15:08:12 +00002528/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002529/// with the converted and checked explicit template arguments.
2530///
Mike Stump11289f42009-09-09 15:08:12 +00002531/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002532/// parameters.
2533///
2534/// \param FunctionType if non-NULL, the result type of the function template
2535/// will also be instantiated and the pointed-to value will be updated with
2536/// the instantiated function type.
2537///
2538/// \param Info if substitution fails for any reason, this object will be
2539/// populated with more information about the failure.
2540///
2541/// \returns TDK_Success if substitution was successful, or some failure
2542/// condition.
2543Sema::TemplateDeductionResult
2544Sema::SubstituteExplicitTemplateArguments(
2545 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002546 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002547 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2548 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002549 QualType *FunctionType,
2550 TemplateDeductionInfo &Info) {
2551 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2552 TemplateParameterList *TemplateParams
2553 = FunctionTemplate->getTemplateParameters();
2554
John McCall6b51f282009-11-23 01:53:49 +00002555 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002556 // No arguments to substitute; just copy over the parameter types and
2557 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002558 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002559 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002560
Douglas Gregor9b146582009-07-08 20:55:45 +00002561 if (FunctionType)
2562 *FunctionType = Function->getType();
2563 return TDK_Success;
2564 }
Mike Stump11289f42009-09-09 15:08:12 +00002565
Eli Friedman77dcc722012-02-08 03:07:05 +00002566 // Unevaluated SFINAE context.
2567 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002568 SFINAETrap Trap(*this);
2569
Douglas Gregor9b146582009-07-08 20:55:45 +00002570 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002571 // Template arguments that are present shall be specified in the
2572 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002573 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002574 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002575 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002576
2577 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002578 // explicitly-specified template arguments against this function template,
2579 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002580 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002581 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2582 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002583 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2584 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002585 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002586 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002587
Douglas Gregor9b146582009-07-08 20:55:45 +00002588 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002589 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002590 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002591 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002592 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002593 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002594 if (Index >= TemplateParams->size())
2595 Index = TemplateParams->size() - 1;
2596 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002597 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002598 }
Mike Stump11289f42009-09-09 15:08:12 +00002599
Douglas Gregor9b146582009-07-08 20:55:45 +00002600 // Form the template argument list from the explicitly-specified
2601 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002602 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002603 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002604 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002605
John McCall036855a2010-10-12 19:40:14 +00002606 // Template argument deduction and the final substitution should be
2607 // done in the context of the templated declaration. Explicit
2608 // argument substitution, on the other hand, needs to happen in the
2609 // calling context.
2610 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2611
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002612 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002613 // note that the template argument pack is partially substituted and record
2614 // the explicit template arguments. They'll be used as part of deduction
2615 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002616 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2617 const TemplateArgument &Arg = Builder[I];
2618 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002619 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002620 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002621 Arg.pack_begin(),
2622 Arg.pack_size());
2623 break;
2624 }
2625 }
2626
Richard Smith5e580292012-02-10 09:58:53 +00002627 const FunctionProtoType *Proto
2628 = Function->getType()->getAs<FunctionProtoType>();
2629 assert(Proto && "Function template does not have a prototype?");
2630
Richard Smith70b13042015-01-09 01:19:56 +00002631 // Isolate our substituted parameters from our caller.
2632 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2633
John McCallc8e321d2016-03-01 02:09:25 +00002634 ExtParameterInfoBuilder ExtParamInfos;
2635
Douglas Gregor9b146582009-07-08 20:55:45 +00002636 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002637 // explicitly-specified template arguments. If the function has a trailing
2638 // return type, substitute it after the arguments to ensure we substitute
2639 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002640 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002641 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002642 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002643 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002644 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002645 return TDK_SubstitutionFailure;
2646 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002647
Richard Smith5e580292012-02-10 09:58:53 +00002648 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002649 QualType ResultType;
2650 {
2651 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002652 // If a declaration declares a member function or member function
2653 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002654 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002655 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002656 // declarator.
2657 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002658 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002659 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2660 ThisContext = Method->getParent();
2661 ThisTypeQuals = Method->getTypeQualifiers();
2662 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002663
Douglas Gregor3024f072012-04-16 07:05:22 +00002664 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002665 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002666
2667 ResultType =
2668 SubstType(Proto->getReturnType(),
2669 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2670 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002671 if (ResultType.isNull() || Trap.hasErrorOccurred())
2672 return TDK_SubstitutionFailure;
2673 }
John McCallc8e321d2016-03-01 02:09:25 +00002674
Richard Smith5e580292012-02-10 09:58:53 +00002675 // Instantiate the types of each of the function parameters given the
2676 // explicitly-specified template arguments if we didn't do so earlier.
2677 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002678 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002679 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002680 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002681 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002682 return TDK_SubstitutionFailure;
2683
Douglas Gregor9b146582009-07-08 20:55:45 +00002684 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002685 auto EPI = Proto->getExtProtoInfo();
2686 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002687 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002688 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002689 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002690 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002691 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2692 return TDK_SubstitutionFailure;
2693 }
Mike Stump11289f42009-09-09 15:08:12 +00002694
Douglas Gregor9b146582009-07-08 20:55:45 +00002695 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002696 // Trailing template arguments that can be deduced (14.8.2) may be
2697 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002698 // template arguments can be deduced, they may all be omitted; in this
2699 // case, the empty template argument list <> itself may also be omitted.
2700 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002701 // Take all of the explicitly-specified arguments and put them into
2702 // the set of deduced template arguments. Explicitly-specified
2703 // parameter packs, however, will be set to NULL since the deduction
2704 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002705 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002706 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2707 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2708 if (Arg.getKind() == TemplateArgument::Pack)
2709 Deduced.push_back(DeducedTemplateArgument());
2710 else
2711 Deduced.push_back(Arg);
2712 }
Mike Stump11289f42009-09-09 15:08:12 +00002713
Douglas Gregor9b146582009-07-08 20:55:45 +00002714 return TDK_Success;
2715}
2716
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002717/// \brief Check whether the deduced argument type for a call to a function
2718/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002719static bool
2720CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002721 QualType DeducedA) {
2722 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002723
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002724 QualType A = OriginalArg.OriginalArgType;
2725 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002726
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002727 // Check for type equality (top-level cv-qualifiers are ignored).
2728 if (Context.hasSameUnqualifiedType(A, DeducedA))
2729 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002730
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002731 // Strip off references on the argument types; they aren't needed for
2732 // the following checks.
2733 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2734 DeducedA = DeducedARef->getPointeeType();
2735 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2736 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002737
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002738 // C++ [temp.deduct.call]p4:
2739 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002740 // - If the original P is a reference type, the deduced A (i.e., the
2741 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002742 // the transformed A.
2743 if (const ReferenceType *OriginalParamRef
2744 = OriginalParamType->getAs<ReferenceType>()) {
2745 // We don't want to keep the reference around any more.
2746 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002747
Richard Smith1be59c52016-10-22 01:32:19 +00002748 // FIXME: Resolve core issue (no number yet): if the original P is a
2749 // reference type and the transformed A is function type "noexcept F",
2750 // the deduced A can be F.
2751 QualType Tmp;
2752 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2753 return false;
2754
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002755 Qualifiers AQuals = A.getQualifiers();
2756 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002757
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002758 // Under Objective-C++ ARC, the deduced type may have implicitly
2759 // been given strong or (when dealing with a const reference)
2760 // unsafe_unretained lifetime. If so, update the original
2761 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002762 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002763 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2764 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2765 (DeducedAQuals.hasConst() &&
2766 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2767 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002768 }
2769
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002770 if (AQuals == DeducedAQuals) {
2771 // Qualifiers match; there's nothing to do.
2772 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002773 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002774 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002775 // Qualifiers are compatible, so have the argument type adopt the
2776 // deduced argument type's qualifiers as if we had performed the
2777 // qualification conversion.
2778 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2779 }
2780 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002781
2782 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002783 // type that can be converted to the deduced A via a function pointer
2784 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002785 //
Richard Smith1be59c52016-10-22 01:32:19 +00002786 // Also allow conversions which merely strip __attribute__((noreturn)) from
2787 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002788 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002789 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002790 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002791 (S.IsQualificationConversion(A, DeducedA, false,
2792 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002793 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002794 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002795
Simon Pilgrim728134c2016-08-12 11:43:57 +00002796 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002797 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002798 // [...] Likewise, if P is a pointer to a class of the form
2799 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002800 // derived class pointed to by the deduced A.
2801 if (const PointerType *OriginalParamPtr
2802 = OriginalParamType->getAs<PointerType>()) {
2803 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2804 if (const PointerType *APtr = A->getAs<PointerType>()) {
2805 if (A->getPointeeType()->isRecordType()) {
2806 OriginalParamType = OriginalParamPtr->getPointeeType();
2807 DeducedA = DeducedAPtr->getPointeeType();
2808 A = APtr->getPointeeType();
2809 }
2810 }
2811 }
2812 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002813
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002814 if (Context.hasSameUnqualifiedType(A, DeducedA))
2815 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002816
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002817 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002818 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002819 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002820
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002821 return true;
2822}
2823
Mike Stump11289f42009-09-09 15:08:12 +00002824/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002825/// checking the deduced template arguments for completeness and forming
2826/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002827///
2828/// \param OriginalCallArgs If non-NULL, the original call arguments against
2829/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002830Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002831Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002832 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002833 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002834 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002835 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002836 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2837 bool PartialOverloading) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002838 // Unevaluated SFINAE context.
2839 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002840 SFINAETrap Trap(*this);
2841
Douglas Gregor9b146582009-07-08 20:55:45 +00002842 // Enter a new template instantiation context while we instantiate the
2843 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002844 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002845 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2846 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002847 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2848 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002849 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002850 return TDK_InstantiationDepth;
2851
John McCalle23b8712010-04-29 01:18:58 +00002852 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002853
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002854 // C++ [temp.deduct.type]p2:
2855 // [...] or if any template argument remains neither deduced nor
2856 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002857 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002858 if (auto Result = ConvertDeducedTemplateArguments(
2859 *this, FunctionTemplate, Deduced, Info, Builder,
2860 CurrentInstantiationScope, NumExplicitlySpecified,
2861 PartialOverloading))
2862 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002863
2864 // Form the template argument list from the deduced template arguments.
2865 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002866 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002867 Info.reset(DeducedArgumentList);
2868
Mike Stump11289f42009-09-09 15:08:12 +00002869 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002870 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002871 DeclContext *Owner = FunctionTemplate->getDeclContext();
2872 if (FunctionTemplate->getFriendObjectKind())
2873 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002874 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002875 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002876 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002877 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002878 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002879
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002880 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002881 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002882
Mike Stump11289f42009-09-09 15:08:12 +00002883 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002884 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002885 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2886 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002887 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002888
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002889 // There may have been an error that did not prevent us from constructing a
2890 // declaration. Mark the declaration invalid and return with a substitution
2891 // failure.
2892 if (Trap.hasErrorOccurred()) {
2893 Specialization->setInvalidDecl(true);
2894 return TDK_SubstitutionFailure;
2895 }
2896
Douglas Gregore65aacb2011-06-16 16:50:48 +00002897 if (OriginalCallArgs) {
2898 // C++ [temp.deduct.call]p4:
2899 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002900 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002901 // is transformed as described above). [...]
2902 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2903 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002904 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002905
Douglas Gregore65aacb2011-06-16 16:50:48 +00002906 if (ParamIdx >= Specialization->getNumParams())
2907 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002908
Douglas Gregore65aacb2011-06-16 16:50:48 +00002909 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002910 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2911 Info.FirstArg = TemplateArgument(DeducedA);
2912 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2913 Info.CallArgIndex = OriginalArg.ArgIdx;
2914 return TDK_DeducedMismatch;
2915 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00002916 }
2917 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002918
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002919 // If we suppressed any diagnostics while performing template argument
2920 // deduction, and if we haven't already instantiated this declaration,
2921 // keep track of these diagnostics. They'll be emitted if this specialization
2922 // is actually used.
2923 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00002924 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002925 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2926 if (Pos == SuppressedDiagnostics.end())
2927 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2928 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002930
Mike Stump11289f42009-09-09 15:08:12 +00002931 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00002932}
2933
John McCall8d08b9b2010-08-27 09:08:28 +00002934/// Gets the type of a function for template-argument-deducton
2935/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00002936static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00002937 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002938 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002939 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00002940 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00002941 return QualType();
2942
John McCallc1f69982010-02-02 02:21:27 +00002943 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00002944 if (Method->isInstance()) {
2945 // An instance method that's referenced in a form that doesn't
2946 // look like a member pointer is just invalid.
2947 if (!R.HasFormOfMemberPointer) return QualType();
2948
Richard Smith2a7d4812013-05-04 07:00:32 +00002949 return S.Context.getMemberPointerType(Fn->getType(),
2950 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00002951 }
2952
2953 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00002954 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00002955}
2956
2957/// Apply the deduction rules for overload sets.
2958///
2959/// \return the null type if this argument should be treated as an
2960/// undeduced context
2961static QualType
2962ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002963 Expr *Arg, QualType ParamType,
2964 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965
John McCall8d08b9b2010-08-27 09:08:28 +00002966 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00002967
John McCall8d08b9b2010-08-27 09:08:28 +00002968 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00002969
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00002970 // C++0x [temp.deduct.call]p4
2971 unsigned TDF = 0;
2972 if (ParamWasReference)
2973 TDF |= TDF_ParamWithReferenceType;
2974 if (R.IsAddressOfOperand)
2975 TDF |= TDF_IgnoreQualifiers;
2976
John McCallc1f69982010-02-02 02:21:27 +00002977 // C++0x [temp.deduct.call]p6:
2978 // When P is a function type, pointer to function type, or pointer
2979 // to member function type:
2980
2981 if (!ParamType->isFunctionType() &&
2982 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002983 !ParamType->isMemberFunctionPointerType()) {
2984 if (Ovl->hasExplicitTemplateArgs()) {
2985 // But we can still look for an explicit specialization.
2986 if (FunctionDecl *ExplicitSpec
2987 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00002988 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002989 }
John McCallc1f69982010-02-02 02:21:27 +00002990
George Burgess IVcc2f3552016-03-19 21:51:45 +00002991 DeclAccessPair DAP;
2992 if (FunctionDecl *Viable =
2993 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
2994 return GetTypeOfFunction(S, R, Viable);
2995
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002996 return QualType();
2997 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002998
Douglas Gregor8409ccd2012-03-12 21:09:16 +00002999 // Gather the explicit template arguments, if any.
3000 TemplateArgumentListInfo ExplicitTemplateArgs;
3001 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003002 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003003 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003004 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3005 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003006 NamedDecl *D = (*I)->getUnderlyingDecl();
3007
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003008 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3009 // - If the argument is an overload set containing one or more
3010 // function templates, the parameter is treated as a
3011 // non-deduced context.
3012 if (!Ovl->hasExplicitTemplateArgs())
3013 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003014
3015 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003016 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003017 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003018 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3019 Specialization, Info))
3020 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003021
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003022 D = Specialization;
3023 }
John McCallc1f69982010-02-02 02:21:27 +00003024
3025 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003026 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003027 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003028
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003029 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003031 ArgType->isFunctionType())
3032 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003033
John McCallc1f69982010-02-02 02:21:27 +00003034 // - If the argument is an overload set (not containing function
3035 // templates), trial argument deduction is attempted using each
3036 // of the members of the set. If deduction succeeds for only one
3037 // of the overload set members, that member is used as the
3038 // argument value for the deduction. If deduction succeeds for
3039 // more than one member of the overload set the parameter is
3040 // treated as a non-deduced context.
3041
3042 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3043 // Type deduction is done independently for each P/A pair, and
3044 // the deduced template argument values are then combined.
3045 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003046 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003047 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003048 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003049 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003050 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3051 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003052 if (Result) continue;
3053 if (!Match.isNull()) return QualType();
3054 Match = ArgType;
3055 }
3056
3057 return Match;
3058}
3059
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003060/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003061/// described in C++ [temp.deduct.call].
3062///
3063/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003064/// argument deduction based on this P/A pair because the argument is an
3065/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003066static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3067 TemplateParameterList *TemplateParams,
3068 QualType &ParamType,
3069 QualType &ArgType,
3070 Expr *Arg,
3071 unsigned &TDF) {
3072 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003073 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003074 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003075 if (ParamType.hasQualifiers())
3076 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003077
3078 // [...] If P is a reference type, the type referred to by P is
3079 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003080 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003081 if (ParamRefType)
3082 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003083
Nathan Sidwell96090022015-01-16 15:20:14 +00003084 // Overload sets usually make this parameter an undeduced context,
3085 // but there are sometimes special circumstances. Typically
3086 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003087 if (ArgType == S.Context.OverloadTy) {
3088 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3089 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003090 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003091 if (ArgType.isNull())
3092 return true;
3093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003094
Douglas Gregor7825bf32011-01-06 22:09:01 +00003095 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003096 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003097 if (ArgType->isIncompleteArrayType()) {
3098 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003099 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003100 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003101
Douglas Gregor7825bf32011-01-06 22:09:01 +00003102 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003103 // If P is an rvalue reference to a cv-unqualified template
3104 // parameter and the argument is an lvalue, the type "lvalue
3105 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003106 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003107 !ParamType.getQualifiers() &&
3108 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003109 Arg->isLValue())
3110 ArgType = S.Context.getLValueReferenceType(ArgType);
3111 } else {
3112 // C++ [temp.deduct.call]p2:
3113 // If P is not a reference type:
3114 // - If A is an array type, the pointer type produced by the
3115 // array-to-pointer standard conversion (4.2) is used in place of
3116 // A for type deduction; otherwise,
3117 if (ArgType->isArrayType())
3118 ArgType = S.Context.getArrayDecayedType(ArgType);
3119 // - If A is a function type, the pointer type produced by the
3120 // function-to-pointer standard conversion (4.3) is used in place
3121 // of A for type deduction; otherwise,
3122 else if (ArgType->isFunctionType())
3123 ArgType = S.Context.getPointerType(ArgType);
3124 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003125 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003126 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003127 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003128 }
3129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003130
Douglas Gregor7825bf32011-01-06 22:09:01 +00003131 // C++0x [temp.deduct.call]p4:
3132 // In general, the deduction process attempts to find template argument
3133 // values that will make the deduced A identical to A (after the type A
3134 // is transformed as described above). [...]
3135 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003136
Douglas Gregor7825bf32011-01-06 22:09:01 +00003137 // - If the original P is a reference type, the deduced A (i.e., the
3138 // type referred to by the reference) can be more cv-qualified than
3139 // the transformed A.
3140 if (ParamRefType)
3141 TDF |= TDF_ParamWithReferenceType;
3142 // - The transformed A can be another pointer or pointer to member
3143 // type that can be converted to the deduced A via a qualification
3144 // conversion (4.4).
3145 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3146 ArgType->isObjCObjectPointerType())
3147 TDF |= TDF_IgnoreQualifiers;
3148 // - If P is a class and P has the form simple-template-id, then the
3149 // transformed A can be a derived class of the deduced A. Likewise,
3150 // if P is a pointer to a class of the form simple-template-id, the
3151 // transformed A can be a pointer to a derived class pointed to by
3152 // the deduced A.
3153 if (isSimpleTemplateIdType(ParamType) ||
3154 (isa<PointerType>(ParamType) &&
3155 isSimpleTemplateIdType(
3156 ParamType->getAs<PointerType>()->getPointeeType())))
3157 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158
Douglas Gregor7825bf32011-01-06 22:09:01 +00003159 return false;
3160}
3161
Nico Weberc153d242014-07-28 00:02:09 +00003162static bool
3163hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3164 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003165
Hubert Tong3280b332015-06-25 00:25:49 +00003166static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3167 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3168 Expr *Arg, TemplateDeductionInfo &Info,
3169 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3170
3171/// \brief Attempt template argument deduction from an initializer list
3172/// deemed to be an argument in a function call.
3173static bool
3174DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3175 QualType AdjustedParamType, InitListExpr *ILE,
3176 TemplateDeductionInfo &Info,
3177 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3178 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003179
3180 // [temp.deduct.call] p1 (post CWG-1591)
3181 // If removing references and cv-qualifiers from P gives
3182 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3183 // non-empty initializer list (8.5.4), then deduction is performed instead for
3184 // each element of the initializer list, taking P0 as a function template
3185 // parameter type and the initializer element as its argument, and in the
3186 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3187 // length of the initializer list. Otherwise, an initializer list argument
3188 // causes the parameter to be considered a non-deduced context
3189
3190 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3191
3192 const bool IsDependentSizedArray =
3193 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3194
Faisal Validd76cc12015-12-10 12:29:11 +00003195 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003196
3197 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3198 S.isStdInitializerList(AdjustedParamType, &ElTy);
3199
3200 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003201 return false;
3202
3203 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003204 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3205 // deduce against the 'T' in T[N].
3206 if (ElTy.isNull()) {
3207 assert(!IsSTDList);
3208 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003209 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003210 // Deduction only needs to be done for dependent types.
3211 if (ElTy->isDependentType()) {
3212 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003213 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3214 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003215 return true;
3216 }
3217 }
3218 if (IsDependentSizedArray) {
3219 const DependentSizedArrayType *ArrTy =
3220 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3221 // Determine the array bound is something we can deduce.
3222 if (NonTypeTemplateParmDecl *NTTP =
3223 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3224 // We can perform template argument deduction for the given non-type
3225 // template parameter.
3226 assert(NTTP->getDepth() == 0 &&
3227 "Cannot deduce non-type template argument at depth > 0");
3228 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3229 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003230
Faisal Valif6dfdb32015-12-10 05:36:39 +00003231 Result = DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +00003232 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
Faisal Valif6dfdb32015-12-10 05:36:39 +00003233 /*ArrayBound=*/true, Info, Deduced);
3234 }
3235 }
Hubert Tong3280b332015-06-25 00:25:49 +00003236 return true;
3237}
3238
Sebastian Redl19181662012-03-15 21:40:51 +00003239/// \brief Perform template argument deduction by matching a parameter type
3240/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003241/// an initializer list that was originally matched against a parameter
3242/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003243static Sema::TemplateDeductionResult
3244DeduceTemplateArgumentByListElement(Sema &S,
3245 TemplateParameterList *TemplateParams,
3246 QualType ParamType, Expr *Arg,
3247 TemplateDeductionInfo &Info,
3248 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3249 unsigned TDF) {
3250 // Handle the case where an init list contains another init list as the
3251 // element.
3252 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003253 Sema::TemplateDeductionResult Result;
3254 if (!DeduceFromInitializerList(S, TemplateParams,
3255 ParamType.getNonReferenceType(), ILE, Info,
3256 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003257 return Sema::TDK_Success; // Just ignore this expression.
3258
Hubert Tong3280b332015-06-25 00:25:49 +00003259 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003260 }
3261
3262 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003263 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003264 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003265 ArgType, Arg, TDF)) {
3266 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003267 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003268 }
Sebastian Redl19181662012-03-15 21:40:51 +00003269 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003270 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003271}
3272
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003273/// \brief Perform template argument deduction from a function call
3274/// (C++ [temp.deduct.call]).
3275///
3276/// \param FunctionTemplate the function template for which we are performing
3277/// template argument deduction.
3278///
James Dennett18348b62012-06-22 08:52:37 +00003279/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003280/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003281///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003282/// \param Args the function call arguments
3283///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003284/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003285/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003286/// template argument deduction.
3287///
3288/// \param Info the argument will be updated to provide additional information
3289/// about template argument deduction.
3290///
3291/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003292Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3293 FunctionTemplateDecl *FunctionTemplate,
3294 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003295 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3296 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003297 if (FunctionTemplate->isInvalidDecl())
3298 return TDK_Invalid;
3299
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003300 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003301 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003302
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003303 // C++ [temp.deduct.call]p1:
3304 // Template argument deduction is done by comparing each function template
3305 // parameter type (call it P) with the type of the corresponding argument
3306 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003307 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003308 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003309 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003310 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003311 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003312 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003313 if (Proto->isTemplateVariadic())
3314 /* Do nothing */;
3315 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003316 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003317 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003318 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003319 }
Mike Stump11289f42009-09-09 15:08:12 +00003320
Douglas Gregor89026b52009-06-30 23:57:56 +00003321 // The types of the parameters from which we will perform template argument
3322 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003323 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003324 TemplateParameterList *TemplateParams
3325 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003326 SmallVector<DeducedTemplateArgument, 4> Deduced;
3327 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003328 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003329 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003330 TemplateDeductionResult Result =
3331 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003332 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003333 Deduced,
3334 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003335 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003336 Info);
3337 if (Result)
3338 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003339
3340 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003341 } else {
3342 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003343 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003344 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3345 }
Mike Stump11289f42009-09-09 15:08:12 +00003346
Douglas Gregor89026b52009-06-30 23:57:56 +00003347 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003348 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003349 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003350 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003351 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3352 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003353 QualType OrigParamType = ParamTypes[ParamIdx];
3354 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003355
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003357 = dyn_cast<PackExpansionType>(ParamType);
3358 if (!ParamExpansion) {
3359 // Simple case: matching a function parameter to a function argument.
3360 if (ArgIdx >= CheckArgs)
3361 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362
Douglas Gregor7825bf32011-01-06 22:09:01 +00003363 Expr *Arg = Args[ArgIdx++];
3364 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003365
Douglas Gregor7825bf32011-01-06 22:09:01 +00003366 unsigned TDF = 0;
3367 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3368 ParamType, ArgType, Arg,
3369 TDF))
3370 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371
Douglas Gregor0c83c812011-10-09 22:06:46 +00003372 // If we have nothing to deduce, we're done.
3373 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3374 continue;
3375
Sebastian Redl43144e72012-01-17 22:49:58 +00003376 // If the argument is an initializer list ...
3377 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003378 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003379 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003380 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3381 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003382 continue;
3383
Hubert Tong3280b332015-06-25 00:25:49 +00003384 if (Result)
3385 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003386 // Don't track the argument type, since an initializer list has none.
3387 continue;
3388 }
3389
Douglas Gregore65aacb2011-06-16 16:50:48 +00003390 // Keep track of the argument type and corresponding parameter index,
3391 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003392 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003393 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003394
Douglas Gregor7825bf32011-01-06 22:09:01 +00003395 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003396 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3397 ParamType, ArgType,
3398 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003399 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003400
Douglas Gregor7825bf32011-01-06 22:09:01 +00003401 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403
Douglas Gregor7825bf32011-01-06 22:09:01 +00003404 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405 // For a function parameter pack that occurs at the end of the
3406 // parameter-declaration-list, the type A of each remaining argument of
3407 // the call is compared with the type P of the declarator-id of the
3408 // function parameter pack. Each comparison deduces template arguments
3409 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003410 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003412 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003413 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003414 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415
Douglas Gregor7825bf32011-01-06 22:09:01 +00003416 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003417 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3418 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Douglas Gregor7825bf32011-01-06 22:09:01 +00003420 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003421 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003422 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423
Douglas Gregore65aacb2011-06-16 16:50:48 +00003424 QualType OrigParamType = ParamPattern;
3425 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003426 Expr *Arg = Args[ArgIdx];
3427 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003428
Douglas Gregor7825bf32011-01-06 22:09:01 +00003429 unsigned TDF = 0;
3430 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3431 ParamType, ArgType, Arg,
3432 TDF)) {
3433 // We can't actually perform any deduction for this argument, so stop
3434 // deduction at this point.
3435 ++ArgIdx;
3436 break;
3437 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
Sebastian Redl43144e72012-01-17 22:49:58 +00003439 // As above, initializer lists need special handling.
3440 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003441 TemplateDeductionResult Result;
3442 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3443 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003444 ++ArgIdx;
3445 break;
3446 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003447
Hubert Tong3280b332015-06-25 00:25:49 +00003448 if (Result)
3449 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003450 } else {
3451
3452 // Keep track of the argument type and corresponding argument index,
3453 // so we can check for compatibility between the deduced A and A.
3454 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003455 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003456 ArgType));
3457
3458 if (TemplateDeductionResult Result
3459 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3460 ParamType, ArgType, Info,
3461 Deduced, TDF))
3462 return Result;
3463 }
Mike Stump11289f42009-09-09 15:08:12 +00003464
Richard Smith0a80d572014-05-29 01:12:14 +00003465 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467
Douglas Gregor7825bf32011-01-06 22:09:01 +00003468 // Build argument packs for each of the parameter packs expanded by this
3469 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003470 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003471 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003472
Douglas Gregor7825bf32011-01-06 22:09:01 +00003473 // After we've matching against a parameter pack, we're done.
3474 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003475 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003476
Mike Stump11289f42009-09-09 15:08:12 +00003477 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003478 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003479 Info, &OriginalCallArgs,
3480 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003481}
3482
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003483QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003484 QualType FunctionType,
3485 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003486 if (ArgFunctionType.isNull())
3487 return ArgFunctionType;
3488
3489 const FunctionProtoType *FunctionTypeP =
3490 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003491 const FunctionProtoType *ArgFunctionTypeP =
3492 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003493
3494 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3495 bool Rebuild = false;
3496
3497 CallingConv CC = FunctionTypeP->getCallConv();
3498 if (EPI.ExtInfo.getCC() != CC) {
3499 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3500 Rebuild = true;
3501 }
3502
3503 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3504 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3505 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3506 Rebuild = true;
3507 }
3508
3509 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3510 ArgFunctionTypeP->hasExceptionSpec())) {
3511 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3512 Rebuild = true;
3513 }
3514
3515 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003516 return ArgFunctionType;
3517
Richard Smithbaa47832016-12-01 02:11:49 +00003518 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3519 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003520}
3521
Douglas Gregor9b146582009-07-08 20:55:45 +00003522/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003523/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3524/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003525///
3526/// \param FunctionTemplate the function template for which we are performing
3527/// template argument deduction.
3528///
James Dennett18348b62012-06-22 08:52:37 +00003529/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003530/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003531///
3532/// \param ArgFunctionType the function type that will be used as the
3533/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003534/// function template's function type. This type may be NULL, if there is no
3535/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003536///
3537/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003538/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003539/// template argument deduction.
3540///
3541/// \param Info the argument will be updated to provide additional information
3542/// about template argument deduction.
3543///
Richard Smithbaa47832016-12-01 02:11:49 +00003544/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3545/// the address of a function template per [temp.deduct.funcaddr] and
3546/// [over.over]. If \c false, we are looking up a function template
3547/// specialization based on its signature, per [temp.deduct.decl].
3548///
Douglas Gregor9b146582009-07-08 20:55:45 +00003549/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003550Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3551 FunctionTemplateDecl *FunctionTemplate,
3552 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3553 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3554 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003555 if (FunctionTemplate->isInvalidDecl())
3556 return TDK_Invalid;
3557
Douglas Gregor9b146582009-07-08 20:55:45 +00003558 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3559 TemplateParameterList *TemplateParams
3560 = FunctionTemplate->getTemplateParameters();
3561 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003562
3563 // When taking the address of a function, we require convertibility of
3564 // the resulting function type. Otherwise, we allow arbitrary mismatches
3565 // of calling convention, noreturn, and noexcept.
3566 if (!IsAddressOfFunction)
3567 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3568 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003569
Douglas Gregor9b146582009-07-08 20:55:45 +00003570 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003571 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003572 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003573 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003574 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003575 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003576 if (TemplateDeductionResult Result
3577 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003578 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003579 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003580 &FunctionType, Info))
3581 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003582
3583 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003584 }
3585
Eli Friedman77dcc722012-02-08 03:07:05 +00003586 // Unevaluated SFINAE context.
3587 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003588 SFINAETrap Trap(*this);
3589
John McCallc1f69982010-02-02 02:21:27 +00003590 Deduced.resize(TemplateParams->size());
3591
Richard Smith2a7d4812013-05-04 07:00:32 +00003592 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003593 // type so that we treat it as a non-deduced context in what follows. If we
3594 // are looking up by signature, the signature type should also have a deduced
3595 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003596 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003597 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003598 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003599 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003600 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003601 }
3602
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003603 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003604 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003605 if (IsAddressOfFunction)
3606 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003607 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003608 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003609 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003610 FunctionType, ArgFunctionType,
3611 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003612 return Result;
3613 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003614
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003616 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3617 NumExplicitlySpecified,
3618 Specialization, Info))
3619 return Result;
3620
Richard Smith2a7d4812013-05-04 07:00:32 +00003621 // If the function has a deduced return type, deduce it now, so we can check
3622 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003623 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003624 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003625 DeduceReturnType(Specialization, Info.getLocation(), false))
3626 return TDK_MiscellaneousDeductionFailure;
3627
Richard Smith9095e5b2016-11-01 01:31:23 +00003628 // If the function has a dependent exception specification, resolve it now,
3629 // so we can check that the exception specification matches.
3630 auto *SpecializationFPT =
3631 Specialization->getType()->castAs<FunctionProtoType>();
3632 if (getLangOpts().CPlusPlus1z &&
3633 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3634 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3635 return TDK_MiscellaneousDeductionFailure;
3636
Richard Smithbaa47832016-12-01 02:11:49 +00003637 // Adjust the exception specification of the argument again to match the
3638 // substituted and resolved type we just formed. (Calling convention and
3639 // noreturn can't be dependent, so we don't actually need this for them
3640 // right now.)
3641 QualType SpecializationType = Specialization->getType();
3642 if (!IsAddressOfFunction)
3643 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3644 /*AdjustExceptionSpec*/true);
3645
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003646 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003647 // specialization with respect to arguments of compatible pointer to function
3648 // types, template argument deduction fails.
3649 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003650 if (IsAddressOfFunction &&
3651 !isSameOrCompatibleFunctionType(
3652 Context.getCanonicalType(SpecializationType),
3653 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003654 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003655
3656 if (!IsAddressOfFunction &&
3657 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003658 return TDK_MiscellaneousDeductionFailure;
3659 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003660
3661 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003662}
3663
Simon Pilgrim728134c2016-08-12 11:43:57 +00003664/// \brief Given a function declaration (e.g. a generic lambda conversion
3665/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003666/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3667/// to replace 'auto' with and not the actual result type you want
3668/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003669static inline void
3670SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003671 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003672 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003673 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003674 assert(AutoResultType->getContainedAutoType());
3675 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003676 TypeToReplaceAutoWith);
3677 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3678}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003679
Simon Pilgrim728134c2016-08-12 11:43:57 +00003680/// \brief Given a specialized conversion operator of a generic lambda
3681/// create the corresponding specializations of the call operator and
3682/// the static-invoker. If the return type of the call operator is auto,
3683/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003684/// return type of the destination function ptr.
3685
Simon Pilgrim728134c2016-08-12 11:43:57 +00003686static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003687SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3688 CXXConversionDecl *ConversionSpecialized,
3689 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3690 QualType ReturnTypeOfDestFunctionPtr,
3691 TemplateDeductionInfo &TDInfo,
3692 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003693
Faisal Vali2b3a3012013-10-24 23:40:02 +00003694 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003695 assert(LambdaClass && LambdaClass->isGenericLambda());
3696
Faisal Vali2b3a3012013-10-24 23:40:02 +00003697 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003698 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003699 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003700 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003701
3702 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003703 CallOpGeneric->getDescribedFunctionTemplate();
3704
Craig Topperc3ec1492014-05-26 06:22:03 +00003705 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003706 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003707 // generic lambda's call operator.
3708 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003709 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3710 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003711 0, CallOpSpecialized, TDInfo))
3712 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003713
Faisal Vali2b3a3012013-10-24 23:40:02 +00003714 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003715 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3716 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003717 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003718 CallOpSpecialized->getPointOfInstantiation(),
3719 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003720
Faisal Vali2b3a3012013-10-24 23:40:02 +00003721 // Check to see if the return type of the destination ptr-to-function
3722 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003723 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003724 ReturnTypeOfDestFunctionPtr))
3725 return Sema::TDK_NonDeducedMismatch;
3726 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003727 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003728 // specialized our corresponding call operator, we are ready to
3729 // specialize the static invoker with the deduced arguments of our
3730 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003731 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003732 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3733 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3734
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003735#ifndef NDEBUG
3736 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3737#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003738 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003739 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003740 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003741 "If the call operator succeeded so should the invoker!");
3742 // Set the result type to match the corresponding call operator
3743 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003744 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3745 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003746 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003747 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003748 // to substitute into the 'auto' of the invoker and conversion
3749 // function.
3750 // For e.g.
3751 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3752 // We don't want to subst 'int*' into 'auto' to get int**.
3753
Alp Toker314cc812014-01-25 16:55:45 +00003754 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3755 ->getContainedAutoType()
3756 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003757 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3758 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003759 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003760 TypeToReplaceAutoWith, S);
3761 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003762
Faisal Vali2b3a3012013-10-24 23:40:02 +00003763 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003764 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003765 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003766 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003767 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3768 getType().getTypePtr()->castAs<FunctionProtoType>();
3769 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3770 EPI.TypeQuals = 0;
3771 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003772 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003773 return Sema::TDK_Success;
3774}
Douglas Gregor05155d82009-08-21 23:19:43 +00003775/// \brief Deduce template arguments for a templated conversion
3776/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3777/// conversion function template specialization.
3778Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003779Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003780 QualType ToType,
3781 CXXConversionDecl *&Specialization,
3782 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003783 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003784 return TDK_Invalid;
3785
Faisal Vali2b3a3012013-10-24 23:40:02 +00003786 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003787 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3788
Faisal Vali2b3a3012013-10-24 23:40:02 +00003789 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003790
3791 // Canonicalize the types for deduction.
3792 QualType P = Context.getCanonicalType(FromType);
3793 QualType A = Context.getCanonicalType(ToType);
3794
Douglas Gregord99609a2011-03-06 09:03:20 +00003795 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003796 // If P is a reference type, the type referred to by P is used for
3797 // type deduction.
3798 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3799 P = PRef->getPointeeType();
3800
Douglas Gregord99609a2011-03-06 09:03:20 +00003801 // C++0x [temp.deduct.conv]p4:
3802 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003803 // for type deduction.
3804 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003805 A = ARef->getPointeeType().getUnqualifiedType();
3806 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003807 //
Mike Stump11289f42009-09-09 15:08:12 +00003808 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003809 else {
3810 assert(!A->isReferenceType() && "Reference types were handled above");
3811
3812 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003813 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003814 // of P for type deduction; otherwise,
3815 if (P->isArrayType())
3816 P = Context.getArrayDecayedType(P);
3817 // - If P is a function type, the pointer type produced by the
3818 // function-to-pointer standard conversion (4.3) is used in
3819 // place of P for type deduction; otherwise,
3820 else if (P->isFunctionType())
3821 P = Context.getPointerType(P);
3822 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003823 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003824 else
3825 P = P.getUnqualifiedType();
3826
Douglas Gregord99609a2011-03-06 09:03:20 +00003827 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003828 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003829 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003830 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003831 A = A.getUnqualifiedType();
3832 }
3833
Eli Friedman77dcc722012-02-08 03:07:05 +00003834 // Unevaluated SFINAE context.
3835 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003836 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003837
3838 // C++ [temp.deduct.conv]p1:
3839 // Template argument deduction is done by comparing the return
3840 // type of the template conversion function (call it P) with the
3841 // type that is required as the result of the conversion (call it
3842 // A) as described in 14.8.2.4.
3843 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003844 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003845 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003846 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003847
3848 // C++0x [temp.deduct.conv]p4:
3849 // In general, the deduction process attempts to find template
3850 // argument values that will make the deduced A identical to
3851 // A. However, there are two cases that allow a difference:
3852 unsigned TDF = 0;
3853 // - If the original A is a reference type, A can be more
3854 // cv-qualified than the deduced A (i.e., the type referred to
3855 // by the reference)
3856 if (ToType->isReferenceType())
3857 TDF |= TDF_ParamWithReferenceType;
3858 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003859 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003860 // conversion.
3861 //
3862 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3863 // both P and A are pointers or member pointers. In this case, we
3864 // just ignore cv-qualifiers completely).
3865 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003866 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003867 TDF |= TDF_IgnoreQualifiers;
3868 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003869 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3870 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003871 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003872
3873 // Create an Instantiation Scope for finalizing the operator.
3874 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003875 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003876 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003877 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003878 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003879 ConversionSpecialized, Info);
3880 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3881
3882 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003883 // to a ptr-to-function, use the deduced arguments from the conversion
3884 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003885 // e.g., int (*fp)(int) = [](auto a) { return a; };
3886 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003887
Faisal Vali2b3a3012013-10-24 23:40:02 +00003888 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003889 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003890 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003891 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003892 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003893 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003894 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003895 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3896
Simon Pilgrim728134c2016-08-12 11:43:57 +00003897 // Create the corresponding specializations of the call operator and
3898 // the static-invoker; and if the return type is auto,
3899 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003900 // DestFunctionPtrReturnType.
3901 // For instance:
3902 // auto L = [](auto a) { return f(a); };
3903 // int (*fp)(int) = L;
3904 // char (*fp2)(int) = L; <-- Not OK.
3905
3906 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003907 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003908 Info, *this);
3909 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003910 return Result;
3911}
3912
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003913/// \brief Deduce template arguments for a function template when there is
3914/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3915///
3916/// \param FunctionTemplate the function template for which we are performing
3917/// template argument deduction.
3918///
James Dennett18348b62012-06-22 08:52:37 +00003919/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003920/// arguments.
3921///
3922/// \param Specialization if template argument deduction was successful,
3923/// this will be set to the function template specialization produced by
3924/// template argument deduction.
3925///
3926/// \param Info the argument will be updated to provide additional information
3927/// about template argument deduction.
3928///
Richard Smithbaa47832016-12-01 02:11:49 +00003929/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3930/// the address of a function template in a context where we do not have a
3931/// target type, per [over.over]. If \c false, we are looking up a function
3932/// template specialization based on its signature, which only happens when
3933/// deducing a function parameter type from an argument that is a template-id
3934/// naming a function template specialization.
3935///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003936/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003937Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3938 FunctionTemplateDecl *FunctionTemplate,
3939 TemplateArgumentListInfo *ExplicitTemplateArgs,
3940 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3941 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003942 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003943 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00003944 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003945}
3946
Richard Smith30482bc2011-02-20 03:19:35 +00003947namespace {
3948 /// Substitute the 'auto' type specifier within a type for a given replacement
3949 /// type.
3950 class SubstituteAutoTransform :
3951 public TreeTransform<SubstituteAutoTransform> {
3952 QualType Replacement;
3953 public:
Nico Weberc153d242014-07-28 00:02:09 +00003954 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3955 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3956 Replacement(Replacement) {}
3957
Richard Smith30482bc2011-02-20 03:19:35 +00003958 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3959 // If we're building the type pattern to deduce against, don't wrap the
3960 // substituted type in an AutoType. Certain template deduction rules
3961 // apply only when a template type parameter appears directly (and not if
3962 // the parameter is found through desugaring). For instance:
3963 // auto &&lref = lvalue;
3964 // must transform into "rvalue reference to T" not "rvalue reference to
3965 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003966 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003967 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003968 TemplateTypeParmTypeLoc NewTL =
3969 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00003970 NewTL.setNameLoc(TL.getNameLoc());
3971 return Result;
3972 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00003973 bool Dependent =
3974 !Replacement.isNull() && Replacement->isDependentType();
3975 QualType Result =
3976 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00003977 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00003978 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00003979 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3980 NewTL.setNameLoc(TL.getNameLoc());
3981 return Result;
3982 }
3983 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00003984
3985 ExprResult TransformLambdaExpr(LambdaExpr *E) {
3986 // Lambdas never need to be transformed.
3987 return E;
3988 }
Richard Smith061f1e22013-04-30 21:23:01 +00003989
Richard Smith2a7d4812013-05-04 07:00:32 +00003990 QualType Apply(TypeLoc TL) {
3991 // Create some scratch storage for the transformed type locations.
3992 // FIXME: We're just going to throw this information away. Don't build it.
3993 TypeLocBuilder TLB;
3994 TLB.reserve(TL.getFullDataSize());
3995 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00003996 }
Richard Smith30482bc2011-02-20 03:19:35 +00003997 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003998}
Richard Smith30482bc2011-02-20 03:19:35 +00003999
Richard Smith2a7d4812013-05-04 07:00:32 +00004000Sema::DeduceAutoResult
4001Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
4002 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
4003}
4004
Richard Smith061f1e22013-04-30 21:23:01 +00004005/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004006///
4007/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004008/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004009/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004010/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00004011Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00004012Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00004013 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004014 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4015 if (NonPlaceholder.isInvalid())
4016 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004017 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004018 }
4019
Richard Smith2a7d4812013-05-04 07:00:32 +00004020 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004021 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004022 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004023 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004024 }
4025
Richard Smith74aeef52013-04-26 16:15:35 +00004026 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4027 // Since 'decltype(auto)' can only occur at the top of the type, we
4028 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004029 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004030 if (AT->isDecltypeAuto()) {
4031 if (isa<InitListExpr>(Init)) {
4032 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4033 return DAR_FailedAlreadyDiagnosed;
4034 }
4035
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004036 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004037 if (Deduced.isNull())
4038 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004039 // FIXME: Support a non-canonical deduced type for 'auto'.
4040 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004041 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004042 if (Result.isNull())
4043 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004044 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004045 } else if (!getLangOpts().CPlusPlus) {
4046 if (isa<InitListExpr>(Init)) {
4047 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4048 return DAR_FailedAlreadyDiagnosed;
4049 }
Richard Smith74aeef52013-04-26 16:15:35 +00004050 }
4051 }
4052
Richard Smith30482bc2011-02-20 03:19:35 +00004053 SourceLocation Loc = Init->getExprLoc();
4054
4055 LocalInstantiationScope InstScope(*this);
4056
4057 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004058 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004059 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4060 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004061 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4062 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004063 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4064 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004065
Richard Smith061f1e22013-04-30 21:23:01 +00004066 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4067 assert(!FuncParam.isNull() &&
4068 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004069
4070 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004071 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004072 Deduced.resize(1);
4073 QualType InitType = Init->getType();
4074 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004075
Craig Toppere6706e42012-09-19 02:26:47 +00004076 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004077
Richard Smith74801c82012-07-08 04:13:07 +00004078 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004079 if (InitList) {
4080 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004081 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4082 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004083 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004084 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004085 }
4086 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004087 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4088 Diag(Loc, diag::err_auto_bitfield);
4089 return DAR_FailedAlreadyDiagnosed;
4090 }
4091
James Y Knight7a22b242015-08-06 20:26:32 +00004092 if (AdjustFunctionParmAndArgTypesForDeduction(
4093 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004094 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004095
James Y Knight7a22b242015-08-06 20:26:32 +00004096 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4097 FuncParam, InitType, Info, Deduced,
4098 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004099 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004100 }
Richard Smith30482bc2011-02-20 03:19:35 +00004101
Eli Friedmane4310952012-11-06 23:56:42 +00004102 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004103 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004104
Eli Friedmane4310952012-11-06 23:56:42 +00004105 QualType DeducedType = Deduced[0].getAsType();
4106
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004107 if (InitList) {
4108 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4109 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004110 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004111 }
4112
Richard Smith061f1e22013-04-30 21:23:01 +00004113 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004114 if (Result.isNull())
4115 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004116
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004117 // Check that the deduced argument type is compatible with the original
4118 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004119 if (!InitList && !Result.isNull() &&
4120 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004121 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004122 Result)) {
4123 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004124 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004125 }
4126
Sebastian Redl09edce02012-01-23 22:09:39 +00004127 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004128}
4129
Simon Pilgrim728134c2016-08-12 11:43:57 +00004130QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004131 QualType TypeToReplaceAuto) {
4132 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4133 TransformType(TypeWithAuto);
4134}
4135
Simon Pilgrim728134c2016-08-12 11:43:57 +00004136TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004137 QualType TypeToReplaceAuto) {
4138 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4139 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004140}
4141
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004142void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4143 if (isa<InitListExpr>(Init))
4144 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004145 VDecl->isInitCapture()
4146 ? diag::err_init_capture_deduction_failure_from_init_list
4147 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004148 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4149 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004150 Diag(VDecl->getLocation(),
4151 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4152 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004153 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4154 << Init->getSourceRange();
4155}
4156
Richard Smith2a7d4812013-05-04 07:00:32 +00004157bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4158 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004159 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004160
4161 if (FD->getTemplateInstantiationPattern())
4162 InstantiateFunctionDefinition(Loc, FD);
4163
Alp Toker314cc812014-01-25 16:55:45 +00004164 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004165 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4166 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4167 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4168 }
4169
4170 return StillUndeduced;
4171}
4172
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004173static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004174MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004175 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004176 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004177 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178
4179/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004180static void
4181AddImplicitObjectParameterType(ASTContext &Context,
4182 CXXMethodDecl *Method,
4183 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004184 // C++11 [temp.func.order]p3:
4185 // [...] The new parameter is of type "reference to cv A," where cv are
4186 // the cv-qualifiers of the function template (if any) and A is
4187 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004188 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004189 // The standard doesn't say explicitly, but we pick the appropriate kind of
4190 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004191 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4192 ArgTy = Context.getQualifiedType(ArgTy,
4193 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004194 if (Method->getRefQualifier() == RQ_RValue)
4195 ArgTy = Context.getRValueReferenceType(ArgTy);
4196 else
4197 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004198 ArgTypes.push_back(ArgTy);
4199}
4200
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004201/// \brief Determine whether the function template \p FT1 is at least as
4202/// specialized as \p FT2.
4203static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004204 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004205 FunctionTemplateDecl *FT1,
4206 FunctionTemplateDecl *FT2,
4207 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004208 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004209 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004211 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4212 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004213
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004214 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4215 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004216 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004217 Deduced.resize(TemplateParams->size());
4218
4219 // C++0x [temp.deduct.partial]p3:
4220 // The types used to determine the ordering depend on the context in which
4221 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004222 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004223 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004224 switch (TPOC) {
4225 case TPOC_Call: {
4226 // - In the context of a function call, the function parameter types are
4227 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004228 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4229 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004230
Eli Friedman3b5774a2012-09-19 23:27:04 +00004231 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004232 // [...] If only one of the function templates is a non-static
4233 // member, that function template is considered to have a new
4234 // first parameter inserted in its function parameter list. The
4235 // new parameter is of type "reference to cv A," where cv are
4236 // the cv-qualifiers of the function template (if any) and A is
4237 // the class of which the function template is a member.
4238 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004239 // Note that we interpret this to mean "if one of the function
4240 // templates is a non-static member and the other is a non-member";
4241 // otherwise, the ordering rules for static functions against non-static
4242 // functions don't make any sense.
4243 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004244 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4245 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004246 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004247
Richard Smithe5b52202013-09-11 00:52:39 +00004248 unsigned NumComparedArguments = NumCallArguments1;
4249
4250 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004251 // Compare 'this' from Method1 against first parameter from Method2.
4252 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4253 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004254 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004255 // Compare 'this' from Method2 against first parameter from Method1.
4256 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004257 }
4258
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004259 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004260 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004261 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004262 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263
Douglas Gregorb837ea42011-01-11 17:34:58 +00004264 // C++ [temp.func.order]p5:
4265 // The presence of unused ellipsis and default arguments has no effect on
4266 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004267 if (Args1.size() > NumComparedArguments)
4268 Args1.resize(NumComparedArguments);
4269 if (Args2.size() > NumComparedArguments)
4270 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004271 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4272 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004273 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004274 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004276 break;
4277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004279 case TPOC_Conversion:
4280 // - In the context of a call to a conversion operator, the return types
4281 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004282 if (DeduceTemplateArgumentsByTypeMatch(
4283 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4284 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004285 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004286 return false;
4287 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004288
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004289 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004290 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004291 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004292 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4293 FD2->getType(), FD1->getType(),
4294 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004295 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004296 return false;
4297 break;
4298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004300 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301 // In most cases, all template parameters must have values in order for
4302 // deduction to succeed, but for partial ordering purposes a template
4303 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004304 // types being used for partial ordering. [ Note: a template parameter used
4305 // in a non-deduced context is considered used. -end note]
4306 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4307 for (; ArgIdx != NumArgs; ++ArgIdx)
4308 if (Deduced[ArgIdx].isNull())
4309 break;
4310
4311 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004313 // as FT2.
4314 return true;
4315 }
4316
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004317 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004318 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004319 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004320 case TPOC_Call:
4321 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4322 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004323 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004324 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004325 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004327 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004328 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4329 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004330 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004332 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004333 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004334 TemplateParams->getDepth(),
4335 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004336 break;
4337 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004339 for (; ArgIdx != NumArgs; ++ArgIdx)
4340 // If this argument had no value deduced but was used in one of the types
4341 // used for partial ordering, then deduction fails.
4342 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4343 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004345 return true;
4346}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004347
Douglas Gregorcef1a032011-01-16 16:03:23 +00004348/// \brief Determine whether this a function template whose parameter-type-list
4349/// ends with a function parameter pack.
4350static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4351 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4352 unsigned NumParams = Function->getNumParams();
4353 if (NumParams == 0)
4354 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355
Douglas Gregorcef1a032011-01-16 16:03:23 +00004356 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4357 if (!Last->isParameterPack())
4358 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359
Douglas Gregorcef1a032011-01-16 16:03:23 +00004360 // Make sure that no previous parameter is a parameter pack.
4361 while (--NumParams > 0) {
4362 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4363 return false;
4364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365
Douglas Gregorcef1a032011-01-16 16:03:23 +00004366 return true;
4367}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004368
Douglas Gregorbe999392009-09-15 16:23:51 +00004369/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004370/// to the rules of function template partial ordering (C++ [temp.func.order]).
4371///
4372/// \param FT1 the first function template
4373///
4374/// \param FT2 the second function template
4375///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004376/// \param TPOC the context in which we are performing partial ordering of
4377/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004378///
Richard Smithe5b52202013-09-11 00:52:39 +00004379/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4380/// only when \c TPOC is \c TPOC_Call.
4381///
4382/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4383/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004384///
Douglas Gregorbe999392009-09-15 16:23:51 +00004385/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004386/// template is more specialized, returns NULL.
4387FunctionTemplateDecl *
4388Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4389 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004390 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004391 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004392 unsigned NumCallArguments1,
4393 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004395 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004397 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004398
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004399 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004400 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004402 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004403 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004404
Douglas Gregorcef1a032011-01-16 16:03:23 +00004405 // FIXME: This mimics what GCC implements, but doesn't match up with the
4406 // proposed resolution for core issue 692. This area needs to be sorted out,
4407 // but for now we attempt to maintain compatibility.
4408 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4409 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4410 if (Variadic1 != Variadic2)
4411 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412
Craig Topperc3ec1492014-05-26 06:22:03 +00004413 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004414}
Douglas Gregor9b146582009-07-08 20:55:45 +00004415
Douglas Gregor450f00842009-09-25 18:43:00 +00004416/// \brief Determine if the two templates are equivalent.
4417static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4418 if (T1 == T2)
4419 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420
Douglas Gregor450f00842009-09-25 18:43:00 +00004421 if (!T1 || !T2)
4422 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregor450f00842009-09-25 18:43:00 +00004424 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4425}
4426
4427/// \brief Retrieve the most specialized of the given function template
4428/// specializations.
4429///
John McCall58cc69d2010-01-27 01:50:18 +00004430/// \param SpecBegin the start iterator of the function template
4431/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004432///
John McCall58cc69d2010-01-27 01:50:18 +00004433/// \param SpecEnd the end iterator of the function template
4434/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004435///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004437/// diagnostic should occur.
4438///
4439/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4440/// no matching candidates.
4441///
4442/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4443/// occurs.
4444///
4445/// \param CandidateDiag partial diagnostic used for each function template
4446/// specialization that is a candidate in the ambiguous ordering. One parameter
4447/// in this diagnostic should be unbound, which will correspond to the string
4448/// describing the template arguments for the function template specialization.
4449///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004451/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004452UnresolvedSetIterator Sema::getMostSpecialized(
4453 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4454 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004455 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4456 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4457 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004458 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004459 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004460 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004461 FailedCandidates.NoteCandidates(*this, Loc);
4462 }
John McCall58cc69d2010-01-27 01:50:18 +00004463 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004464 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004465
4466 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004467 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Douglas Gregor450f00842009-09-25 18:43:00 +00004469 // Find the function template that is better than all of the templates it
4470 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004471 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004472 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004473 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004474 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004475 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4476 FunctionTemplateDecl *Challenger
4477 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004478 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004479 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004480 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004481 Challenger)) {
4482 Best = I;
4483 BestTemplate = Challenger;
4484 }
4485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004486
Douglas Gregor450f00842009-09-25 18:43:00 +00004487 // Make sure that the "best" function template is more specialized than all
4488 // of the others.
4489 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004490 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4491 FunctionTemplateDecl *Challenger
4492 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004493 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004494 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004495 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004496 BestTemplate)) {
4497 Ambiguous = true;
4498 break;
4499 }
4500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501
Douglas Gregor450f00842009-09-25 18:43:00 +00004502 if (!Ambiguous) {
4503 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004504 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
Douglas Gregor450f00842009-09-25 18:43:00 +00004507 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004508 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004509 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510
Richard Smithb875c432013-05-04 01:51:08 +00004511 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004512 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4513 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004514 const auto *FD = cast<FunctionDecl>(*I);
4515 PD << FD << getTemplateArgumentBindingsText(
4516 FD->getPrimaryTemplate()->getTemplateParameters(),
4517 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004518 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004519 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004520 Diag((*I)->getLocation(), PD);
4521 }
Richard Smithb875c432013-05-04 01:51:08 +00004522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004523
John McCall58cc69d2010-01-27 01:50:18 +00004524 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004525}
4526
Richard Smith0da6dc42016-12-24 16:40:51 +00004527/// Determine whether one partial specialization, P1, is at least as
4528/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004529///
Richard Smith0da6dc42016-12-24 16:40:51 +00004530/// \param PartialSpecializationDecl The kind of P2, which must be a
4531/// {Class,Var}TemplatePartialSpecializationDecl.
4532/// \param T1 The injected-class-name of P1 (faked for a variable template).
4533/// \param T2 The injected-class-name of P2 (faked for a variable template).
4534/// \param Loc The location at which the comparison is required.
4535template<typename PartialSpecializationDecl>
4536static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
4537 PartialSpecializationDecl *P2,
4538 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004539 // C++ [temp.class.order]p1:
4540 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541 // specialized as the second if, given the following rewrite to two
4542 // function templates, the first function template is at least as
4543 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004544 // templates (14.6.6.2):
4545 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546 // first partial specialization and has a single function parameter
4547 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004548 // arguments of the first partial specialization, and
4549 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550 // second partial specialization and has a single function parameter
4551 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004552 // arguments of the second partial specialization.
4553 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004554 // Rather than synthesize function templates, we merely perform the
4555 // equivalent partial ordering by performing deduction directly on
4556 // the template arguments of the class template partial
4557 // specializations. This computation is slightly simpler than the
4558 // general problem of function template partial ordering, because
4559 // class template partial specializations are more constrained. We
4560 // know that every template parameter is deducible from the class
4561 // template partial specialization's template arguments, for
4562 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004563 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004564 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004565
Richard Smith0da6dc42016-12-24 16:40:51 +00004566 // Determine whether P1 is at least as specialized as P2.
4567 Deduced.resize(P2->getTemplateParameters()->size());
4568 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4569 T2, T1, Info, Deduced, TDF_None,
4570 /*PartialOrdering=*/true))
4571 return false;
4572
4573 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4574 Deduced.end());
4575 Sema::InstantiatingTemplate Inst(S, Loc, P2, DeducedArgs, Info);
4576 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4577 if (FinishTemplateArgumentDeduction(
4578 S, P2, TemplateArgumentList(TemplateArgumentList::OnStack,
4579 TST1->template_arguments()),
4580 Deduced, Info))
4581 return false;
4582
4583 return true;
4584}
4585
4586/// \brief Returns the more specialized class template partial specialization
4587/// according to the rules of partial ordering of class template partial
4588/// specializations (C++ [temp.class.order]).
4589///
4590/// \param PS1 the first class template partial specialization
4591///
4592/// \param PS2 the second class template partial specialization
4593///
4594/// \returns the more specialized class template partial specialization. If
4595/// neither partial specialization is more specialized, returns NULL.
4596ClassTemplatePartialSpecializationDecl *
4597Sema::getMoreSpecializedPartialSpecialization(
4598 ClassTemplatePartialSpecializationDecl *PS1,
4599 ClassTemplatePartialSpecializationDecl *PS2,
4600 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004601 QualType PT1 = PS1->getInjectedSpecializationType();
4602 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004603
Richard Smith0da6dc42016-12-24 16:40:51 +00004604 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Loc);
4605 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Loc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004606
4607 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004608 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004609
4610 return Better1 ? PS1 : PS2;
4611}
4612
Larisse Voufo39a1e502013-08-06 01:03:05 +00004613VarTemplatePartialSpecializationDecl *
4614Sema::getMoreSpecializedPartialSpecialization(
4615 VarTemplatePartialSpecializationDecl *PS1,
4616 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004617 // Pretend the variable template specializations are class template
4618 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004619 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004620 "the partial specializations being compared should specialize"
4621 " the same template.");
4622 TemplateName Name(PS1->getSpecializedTemplate());
4623 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4624 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004625 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004626 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004627 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004628
Richard Smith0da6dc42016-12-24 16:40:51 +00004629 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Loc);
4630 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004631
Douglas Gregorbe999392009-09-15 16:23:51 +00004632 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004633 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004634
Richard Smith0da6dc42016-12-24 16:40:51 +00004635 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004636}
4637
Mike Stump11289f42009-09-09 15:08:12 +00004638static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004639MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004640 const TemplateArgument &TemplateArg,
4641 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004642 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004643 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004644
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004645/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004646/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004647static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004648MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004649 const Expr *E,
4650 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004651 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004652 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004653 // We can deduce from a pack expansion.
4654 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4655 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004656
Richard Smith34349002012-07-09 03:07:20 +00004657 // Skip through any implicit casts we added while type-checking, and any
4658 // substitutions performed by template alias expansion.
4659 while (1) {
4660 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4661 E = ICE->getSubExpr();
4662 else if (const SubstNonTypeTemplateParmExpr *Subst =
4663 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4664 E = Subst->getReplacement();
4665 else
4666 break;
4667 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668
4669 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004670 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004671 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004672 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004673 return;
4674
Mike Stump11289f42009-09-09 15:08:12 +00004675 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004676 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4677 if (!NTTP)
4678 return;
4679
Douglas Gregor21610382009-10-29 00:04:11 +00004680 if (NTTP->getDepth() == Depth)
4681 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004682
4683 // In C++1z mode, additional arguments may be deduced from the type of a
4684 // non-type argument.
4685 if (Ctx.getLangOpts().CPlusPlus1z)
4686 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004687}
4688
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004689/// \brief Mark the template parameters that are used by the given
4690/// nested name specifier.
4691static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004692MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004693 NestedNameSpecifier *NNS,
4694 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004695 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004696 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004697 if (!NNS)
4698 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004699
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004700 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004701 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004702 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004703 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004704}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004705
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004706/// \brief Mark the template parameters that are used by the given
4707/// template name.
4708static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004709MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004710 TemplateName Name,
4711 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004712 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004713 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004714 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4715 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004716 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4717 if (TTP->getDepth() == Depth)
4718 Used[TTP->getIndex()] = true;
4719 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004720 return;
4721 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004723 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004724 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004725 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004726 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004727 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004728 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004729}
4730
4731/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004732/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004733static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004734MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004735 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004736 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004737 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004738 if (T.isNull())
4739 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004740
Douglas Gregor91772d12009-06-13 00:26:55 +00004741 // Non-dependent types have nothing deducible
4742 if (!T->isDependentType())
4743 return;
4744
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004745 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004746 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004747 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004748 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004749 cast<PointerType>(T)->getPointeeType(),
4750 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004751 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004752 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004753 break;
4754
4755 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004756 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004757 cast<BlockPointerType>(T)->getPointeeType(),
4758 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004759 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004760 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004761 break;
4762
4763 case Type::LValueReference:
4764 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004765 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004766 cast<ReferenceType>(T)->getPointeeType(),
4767 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004768 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004769 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004770 break;
4771
4772 case Type::MemberPointer: {
4773 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004774 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004775 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004776 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004777 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004778 break;
4779 }
4780
4781 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004782 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004783 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004784 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004785 // Fall through to check the element type
4786
4787 case Type::ConstantArray:
4788 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004789 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004790 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004791 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004792 break;
4793
4794 case Type::Vector:
4795 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004796 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004797 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004798 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004799 break;
4800
Douglas Gregor758a8692009-06-17 21:51:59 +00004801 case Type::DependentSizedExtVector: {
4802 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004803 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004804 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004805 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004806 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004807 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004808 break;
4809 }
4810
Douglas Gregor91772d12009-06-13 00:26:55 +00004811 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004812 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004813 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4814 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004815 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4816 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004817 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004818 break;
4819 }
4820
Douglas Gregor21610382009-10-29 00:04:11 +00004821 case Type::TemplateTypeParm: {
4822 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4823 if (TTP->getDepth() == Depth)
4824 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004825 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004826 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004827
Douglas Gregorfb322d82011-01-14 05:11:40 +00004828 case Type::SubstTemplateTypeParmPack: {
4829 const SubstTemplateTypeParmPackType *Subst
4830 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004831 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004832 QualType(Subst->getReplacedParameter(), 0),
4833 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004834 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004835 OnlyDeduced, Depth, Used);
4836 break;
4837 }
4838
John McCall2408e322010-04-27 00:57:59 +00004839 case Type::InjectedClassName:
4840 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4841 // fall through
4842
Douglas Gregor91772d12009-06-13 00:26:55 +00004843 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004844 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004845 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004846 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004847 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848
Douglas Gregord0ad2942010-12-23 01:24:45 +00004849 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004850 // If the template argument list of P contains a pack expansion that is
4851 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004852 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004853 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00004854 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00004855 break;
4856
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004857 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004858 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004859 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004860 break;
4861 }
4862
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004863 case Type::Complex:
4864 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004865 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004866 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004867 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004868 break;
4869
Eli Friedman0dfb8892011-10-06 23:00:33 +00004870 case Type::Atomic:
4871 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004872 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004873 cast<AtomicType>(T)->getValueType(),
4874 OnlyDeduced, Depth, Used);
4875 break;
4876
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004877 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004878 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004879 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004880 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004881 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004882 break;
4883
John McCallc392f372010-06-11 00:33:02 +00004884 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004885 // C++14 [temp.deduct.type]p5:
4886 // The non-deduced contexts are:
4887 // -- The nested-name-specifier of a type that was specified using a
4888 // qualified-id
4889 //
4890 // C++14 [temp.deduct.type]p6:
4891 // When a type name is specified in a way that includes a non-deduced
4892 // context, all of the types that comprise that type name are also
4893 // non-deduced.
4894 if (OnlyDeduced)
4895 break;
4896
John McCallc392f372010-06-11 00:33:02 +00004897 const DependentTemplateSpecializationType *Spec
4898 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004899
Richard Smith50d5b972015-12-30 20:56:05 +00004900 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4901 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004902
John McCallc392f372010-06-11 00:33:02 +00004903 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004904 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004905 Used);
4906 break;
4907 }
4908
John McCallbd8d9bd2010-03-01 23:49:17 +00004909 case Type::TypeOf:
4910 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004911 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004912 cast<TypeOfType>(T)->getUnderlyingType(),
4913 OnlyDeduced, Depth, Used);
4914 break;
4915
4916 case Type::TypeOfExpr:
4917 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004918 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004919 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4920 OnlyDeduced, Depth, Used);
4921 break;
4922
4923 case Type::Decltype:
4924 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004925 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004926 cast<DecltypeType>(T)->getUnderlyingExpr(),
4927 OnlyDeduced, Depth, Used);
4928 break;
4929
Alexis Hunte852b102011-05-24 22:41:36 +00004930 case Type::UnaryTransform:
4931 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004932 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00004933 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00004934 OnlyDeduced, Depth, Used);
4935 break;
4936
Douglas Gregord2fa7662010-12-20 02:24:11 +00004937 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004938 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004939 cast<PackExpansionType>(T)->getPattern(),
4940 OnlyDeduced, Depth, Used);
4941 break;
4942
Richard Smith30482bc2011-02-20 03:19:35 +00004943 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004944 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00004945 cast<AutoType>(T)->getDeducedType(),
4946 OnlyDeduced, Depth, Used);
4947
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004948 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00004949 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00004950 case Type::VariableArray:
4951 case Type::FunctionNoProto:
4952 case Type::Record:
4953 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00004954 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00004955 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00004956 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00004957 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00004958 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00004959#define TYPE(Class, Base)
4960#define ABSTRACT_TYPE(Class, Base)
4961#define DEPENDENT_TYPE(Class, Base)
4962#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4963#include "clang/AST/TypeNodes.def"
4964 break;
4965 }
4966}
4967
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004968/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00004969/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00004970static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004971MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004972 const TemplateArgument &TemplateArg,
4973 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004974 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004975 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004976 switch (TemplateArg.getKind()) {
4977 case TemplateArgument::Null:
4978 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004979 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00004980 break;
Mike Stump11289f42009-09-09 15:08:12 +00004981
Eli Friedmanb826a002012-09-26 02:36:12 +00004982 case TemplateArgument::NullPtr:
4983 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4984 Depth, Used);
4985 break;
4986
Douglas Gregor91772d12009-06-13 00:26:55 +00004987 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004988 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004989 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004990 break;
4991
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004992 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004993 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004994 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004995 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004996 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004997 break;
4998
4999 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005000 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005001 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005002 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005003
Anders Carlssonbc343912009-06-15 17:04:53 +00005004 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005005 for (const auto &P : TemplateArg.pack_elements())
5006 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005007 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005008 }
5009}
5010
James Dennett41725122012-06-22 10:16:05 +00005011/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005012/// template argument list.
5013///
5014/// \param TemplateArgs the template argument list from which template
5015/// parameters will be deduced.
5016///
James Dennett41725122012-06-22 10:16:05 +00005017/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005018/// to indicate when the corresponding template parameter will be
5019/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005020void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005021Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005022 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005023 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005024 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025 // If the template argument list of P contains a pack expansion that is not
5026 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005027 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005029 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005030 return;
5031
Douglas Gregor91772d12009-06-13 00:26:55 +00005032 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005033 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005034 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005035}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005036
5037/// \brief Marks all of the template parameters that will be deduced by a
5038/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005039void Sema::MarkDeducedTemplateParameters(
5040 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5041 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005042 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005043 = FunctionTemplate->getTemplateParameters();
5044 Deduced.clear();
5045 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005046
Douglas Gregorce23bae2009-09-18 23:21:38 +00005047 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5048 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005049 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005050 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005051}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005052
5053bool hasDeducibleTemplateParameters(Sema &S,
5054 FunctionTemplateDecl *FunctionTemplate,
5055 QualType T) {
5056 if (!T->isDependentType())
5057 return false;
5058
5059 TemplateParameterList *TemplateParams
5060 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005061 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005062 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005063 Deduced);
5064
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005065 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005066}