blob: 4f76a029dcd6b365847a21b503e28127b249ff94 [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,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000108 const TemplateArgument *Params, unsigned NumParams,
109 const TemplateArgument *Args, unsigned NumArgs,
110 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
161 switch (X.getKind()) {
162 case TemplateArgument::Null:
163 llvm_unreachable("Non-deduced template arguments handled above");
164
165 case TemplateArgument::Type:
166 // If two template type arguments have the same type, they're compatible.
167 if (Y.getKind() == TemplateArgument::Type &&
168 Context.hasSameType(X.getAsType(), Y.getAsType()))
169 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000170
Richard Smith5f274382016-09-28 23:55:27 +0000171 // If one of the two arguments was deduced from an array bound, the other
172 // supersedes it.
173 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
174 return X.wasDeducedFromArrayBound() ? Y : X;
175
176 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000177 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000178
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000179 case TemplateArgument::Integral:
180 // If we deduced a constant in one case and either a dependent expression or
181 // declaration in another case, keep the integral constant.
182 // If both are integral constants with the same value, keep that value.
183 if (Y.getKind() == TemplateArgument::Expression ||
184 Y.getKind() == TemplateArgument::Declaration ||
185 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000186 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000187 return DeducedTemplateArgument(X,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000188 X.wasDeducedFromArrayBound() &&
189 Y.wasDeducedFromArrayBound());
190
191 // All other combinations are incompatible.
192 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000193
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000194 case TemplateArgument::Template:
195 if (Y.getKind() == TemplateArgument::Template &&
196 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
197 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000198
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000199 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000200 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000201
202 case TemplateArgument::TemplateExpansion:
203 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000204 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000205 Y.getAsTemplateOrTemplatePattern()))
206 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000207
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000208 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000209 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000210
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000211 case TemplateArgument::Expression:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212 // If we deduced a dependent expression in one case and either an integral
213 // constant or a declaration in another case, keep the integral constant
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000214 // or declaration.
215 if (Y.getKind() == TemplateArgument::Integral ||
216 Y.getKind() == TemplateArgument::Declaration)
217 return DeducedTemplateArgument(Y, X.wasDeducedFromArrayBound() &&
218 Y.wasDeducedFromArrayBound());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000219
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000220 if (Y.getKind() == TemplateArgument::Expression) {
221 // Compare the expressions for equality
222 llvm::FoldingSetNodeID ID1, ID2;
223 X.getAsExpr()->Profile(ID1, Context, true);
224 Y.getAsExpr()->Profile(ID2, Context, true);
225 if (ID1 == ID2)
226 return X;
227 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000228
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000229 // All other combinations are incompatible.
230 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000231
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000232 case TemplateArgument::Declaration:
233 // If we deduced a declaration and a dependent expression, keep the
234 // declaration.
235 if (Y.getKind() == TemplateArgument::Expression)
236 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000237
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000238 // If we deduced a declaration and an integral constant, keep the
239 // integral constant.
240 if (Y.getKind() == TemplateArgument::Integral)
241 return Y;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000242
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000243 // If we deduced two declarations, make sure they they refer to the
244 // same declaration.
245 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000246 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000247 return X;
248
249 // All other combinations are incompatible.
250 return DeducedTemplateArgument();
251
252 case TemplateArgument::NullPtr:
253 // If we deduced a null pointer and a dependent expression, keep the
254 // null pointer.
255 if (Y.getKind() == TemplateArgument::Expression)
256 return X;
257
258 // If we deduced a null pointer and an integral constant, keep the
259 // integral constant.
260 if (Y.getKind() == TemplateArgument::Integral)
261 return Y;
262
263 // If we deduced two null pointers, make sure they have the same type.
264 if (Y.getKind() == TemplateArgument::NullPtr &&
265 Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000266 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000267
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000268 // All other combinations are incompatible.
269 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000270
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000271 case TemplateArgument::Pack:
272 if (Y.getKind() != TemplateArgument::Pack ||
273 X.pack_size() != Y.pack_size())
274 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000275
276 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000277 XAEnd = X.pack_end(),
278 YA = Y.pack_begin();
279 XA != XAEnd; ++XA, ++YA) {
Richard Smith0a80d572014-05-29 01:12:14 +0000280 // FIXME: Do we need to merge the results together here?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000281 if (checkDeducedTemplateArguments(Context,
282 DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
Douglas Gregorf491ee22011-01-05 21:00:53 +0000283 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()))
284 .isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000285 return DeducedTemplateArgument();
286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000288 return X;
289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000290
David Blaikiee4d798f2012-01-20 21:50:17 +0000291 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000292}
293
Mike Stump11289f42009-09-09 15:08:12 +0000294/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000295/// from the given integral constant.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000296static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000297 Sema &S, TemplateParameterList *TemplateParams,
298 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000299 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
300 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000301 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000302 "Cannot deduce non-type template argument with depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +0000303
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000304 DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
305 DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000306 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 Deduced[NTTP->getIndex()],
308 NewDeduced);
309 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000310 Info.Param = NTTP;
311 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000312 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000313 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000314 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000315
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000316 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000317 return S.getLangOpts().CPlusPlus1z
318 ? DeduceTemplateArgumentsByTypeMatch(
319 S, TemplateParams, NTTP->getType(), ValueType, Info, Deduced,
320 TDF_ParamWithReferenceType | TDF_SkipNonDependent,
321 /*PartialOrdering=*/false,
322 /*ArrayBound=*/DeducedFromArrayBound)
323 : Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000324}
325
Mike Stump11289f42009-09-09 15:08:12 +0000326/// \brief Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000327/// from the given null pointer template argument type.
328static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000329 Sema &S, TemplateParameterList *TemplateParams,
330 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000331 TemplateDeductionInfo &Info,
332 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
333 Expr *Value =
334 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
335 S.Context.NullPtrTy, NTTP->getLocation()),
336 NullPtrType, CK_NullToPointer)
337 .get();
338 DeducedTemplateArgument NewDeduced(Value);
339 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
340 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
341
342 if (Result.isNull()) {
343 Info.Param = NTTP;
344 Info.FirstArg = Deduced[NTTP->getIndex()];
345 Info.SecondArg = NewDeduced;
346 return Sema::TDK_Inconsistent;
347 }
348
349 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000350 return S.getLangOpts().CPlusPlus1z
351 ? DeduceTemplateArgumentsByTypeMatch(
352 S, TemplateParams, NTTP->getType(), Value->getType(), Info,
353 Deduced, TDF_ParamWithReferenceType | TDF_SkipNonDependent)
354 : Sema::TDK_Success;
Richard Smith38175a22016-09-28 22:08:38 +0000355}
356
357/// \brief Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000358/// from the given type- or value-dependent expression.
359///
360/// \returns true if deduction succeeded, false otherwise.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000361static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000362DeduceNonTypeTemplateArgument(Sema &S,
Richard Smith5f274382016-09-28 23:55:27 +0000363 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000364 NonTypeTemplateParmDecl *NTTP,
365 Expr *Value,
John McCall19c1bfd2010-08-25 05:32:35 +0000366 TemplateDeductionInfo &Info,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000367 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Mike Stump11289f42009-09-09 15:08:12 +0000368 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000369 "Cannot deduce non-type template argument with depth > 0");
370 assert((Value->isTypeDependent() || Value->isValueDependent()) &&
371 "Expression template argument must be type- or value-dependent.");
Mike Stump11289f42009-09-09 15:08:12 +0000372
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000373 DeducedTemplateArgument NewDeduced(Value);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000374 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
375 Deduced[NTTP->getIndex()],
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000376 NewDeduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000378 if (Result.isNull()) {
379 Info.Param = NTTP;
380 Info.FirstArg = Deduced[NTTP->getIndex()];
381 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382 return Sema::TDK_Inconsistent;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000385 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000386 return S.getLangOpts().CPlusPlus1z
387 ? DeduceTemplateArgumentsByTypeMatch(
388 S, TemplateParams, NTTP->getType(), Value->getType(), Info,
389 Deduced, TDF_ParamWithReferenceType | TDF_SkipNonDependent)
390 : Sema::TDK_Success;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000391}
392
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000393/// \brief Deduce the value of the given non-type template parameter
394/// from the given declaration.
395///
396/// \returns true if deduction succeeded, false otherwise.
397static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000398DeduceNonTypeTemplateArgument(Sema &S,
Richard Smith5f274382016-09-28 23:55:27 +0000399 TemplateParameterList *TemplateParams,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000400 NonTypeTemplateParmDecl *NTTP,
Richard Smith5f274382016-09-28 23:55:27 +0000401 ValueDecl *D, QualType T,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000402 TemplateDeductionInfo &Info,
403 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000404 assert(NTTP->getDepth() == 0 &&
405 "Cannot deduce non-type template argument with depth > 0");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000406
Craig Topperc3ec1492014-05-26 06:22:03 +0000407 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
David Blaikie0f62c8d2014-10-16 04:21:25 +0000408 TemplateArgument New(D, NTTP->getType());
Eli Friedmanb826a002012-09-26 02:36:12 +0000409 DeducedTemplateArgument NewDeduced(New);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000411 Deduced[NTTP->getIndex()],
412 NewDeduced);
413 if (Result.isNull()) {
414 Info.Param = NTTP;
415 Info.FirstArg = Deduced[NTTP->getIndex()];
416 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417 return Sema::TDK_Inconsistent;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000419
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000420 Deduced[NTTP->getIndex()] = Result;
Richard Smith5f274382016-09-28 23:55:27 +0000421 return S.getLangOpts().CPlusPlus1z
422 ? DeduceTemplateArgumentsByTypeMatch(
423 S, TemplateParams, NTTP->getType(), T, Info, Deduced,
424 TDF_ParamWithReferenceType | TDF_SkipNonDependent)
425 : Sema::TDK_Success;
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000426}
427
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000428static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000429DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000430 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000431 TemplateName Param,
432 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000433 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000434 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000435 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000436 if (!ParamDecl) {
437 // The parameter type is dependent and is not a template template parameter,
438 // so there is nothing that we can deduce.
439 return Sema::TDK_Success;
440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
Douglas Gregoradee3e32009-11-11 23:06:43 +0000442 if (TemplateTemplateParmDecl *TempParam
443 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000444 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000446 Deduced[TempParam->getIndex()],
447 NewDeduced);
448 if (Result.isNull()) {
449 Info.Param = TempParam;
450 Info.FirstArg = Deduced[TempParam->getIndex()];
451 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000452 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000454
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000455 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000456 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000458
Douglas Gregoradee3e32009-11-11 23:06:43 +0000459 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000460 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000461 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
Douglas Gregoradee3e32009-11-11 23:06:43 +0000463 // Mismatch of non-dependent template parameter to argument.
464 Info.FirstArg = TemplateArgument(Param);
465 Info.SecondArg = TemplateArgument(Arg);
466 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000467}
468
Mike Stump11289f42009-09-09 15:08:12 +0000469/// \brief Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000470/// type (which is a template-id) with the template argument type.
471///
Chandler Carruthc1263112010-02-07 21:33:28 +0000472/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000473///
474/// \param TemplateParams the template parameters that we are deducing
475///
476/// \param Param the parameter type
477///
478/// \param Arg the argument type
479///
480/// \param Info information about the template argument deduction itself
481///
482/// \param Deduced the deduced template arguments
483///
484/// \returns the result of template argument deduction so far. Note that a
485/// "success" result means that template argument deduction has not yet failed,
486/// but it may still fail, later, for other reasons.
487static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000488DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000489 TemplateParameterList *TemplateParams,
490 const TemplateSpecializationType *Param,
491 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000492 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000493 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000494 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000495
Douglas Gregore81f3e72009-07-07 23:09:34 +0000496 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000497 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000498 = dyn_cast<TemplateSpecializationType>(Arg)) {
499 // Perform template argument deduction for the template name.
500 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000501 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000502 Param->getTemplateName(),
503 SpecArg->getTemplateName(),
504 Info, Deduced))
505 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000506
Mike Stump11289f42009-09-09 15:08:12 +0000507
Douglas Gregore81f3e72009-07-07 23:09:34 +0000508 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000509 // argument. Ignore any missing/extra arguments, since they could be
510 // filled in by default arguments.
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000511 return DeduceTemplateArguments(S, TemplateParams, Param->getArgs(),
512 Param->getNumArgs(), SpecArg->getArgs(),
513 SpecArg->getNumArgs(), Info, Deduced,
514 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Douglas Gregore81f3e72009-07-07 23:09:34 +0000517 // If the argument type is a class template specialization, we
518 // perform template argument deduction using its template
519 // arguments.
520 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000521 if (!RecordArg) {
522 Info.FirstArg = TemplateArgument(QualType(Param, 0));
523 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000524 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000525 }
Mike Stump11289f42009-09-09 15:08:12 +0000526
527 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000528 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 if (!SpecArg) {
530 Info.FirstArg = TemplateArgument(QualType(Param, 0));
531 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000532 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000533 }
Mike Stump11289f42009-09-09 15:08:12 +0000534
Douglas Gregore81f3e72009-07-07 23:09:34 +0000535 // Perform template argument deduction for the template name.
536 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000537 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000538 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000539 Param->getTemplateName(),
540 TemplateName(SpecArg->getSpecializedTemplate()),
541 Info, Deduced))
542 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000543
Douglas Gregor7baabef2010-12-22 18:17:10 +0000544 // Perform template argument deduction for the template arguments.
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000545 return DeduceTemplateArguments(
546 S, TemplateParams, Param->getArgs(), Param->getNumArgs(),
547 SpecArg->getTemplateArgs().data(), SpecArg->getTemplateArgs().size(),
548 Info, Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000549}
550
John McCall08569062010-08-28 22:14:41 +0000551/// \brief Determines whether the given type is an opaque type that
552/// might be more qualified when instantiated.
553static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
554 switch (T->getTypeClass()) {
555 case Type::TypeOfExpr:
556 case Type::TypeOf:
557 case Type::DependentName:
558 case Type::Decltype:
559 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000560 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000561 return true;
562
563 case Type::ConstantArray:
564 case Type::IncompleteArray:
565 case Type::VariableArray:
566 case Type::DependentSizedArray:
567 return IsPossiblyOpaquelyQualifiedType(
568 cast<ArrayType>(T)->getElementType());
569
570 default:
571 return false;
572 }
573}
574
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000575/// \brief Retrieve the depth and index of a template parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000576static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000577getDepthAndIndex(NamedDecl *ND) {
Douglas Gregor5499af42011-01-05 23:12:31 +0000578 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
579 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580
Douglas Gregor5499af42011-01-05 23:12:31 +0000581 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
582 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor5499af42011-01-05 23:12:31 +0000584 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
585 return std::make_pair(TTP->getDepth(), TTP->getIndex());
586}
587
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000588/// \brief Retrieve the depth and index of an unexpanded parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589static std::pair<unsigned, unsigned>
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000590getDepthAndIndex(UnexpandedParameterPack UPP) {
591 if (const TemplateTypeParmType *TTP
592 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
593 return std::make_pair(TTP->getDepth(), TTP->getIndex());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000594
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000595 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
596}
597
Douglas Gregor5499af42011-01-05 23:12:31 +0000598/// \brief Helper function to build a TemplateParameter when we don't
599/// know its type statically.
600static TemplateParameter makeTemplateParameter(Decl *D) {
601 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
602 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000603 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000604 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000605
Douglas Gregor5499af42011-01-05 23:12:31 +0000606 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
607}
608
Richard Smith0a80d572014-05-29 01:12:14 +0000609/// A pack that we're currently deducing.
610struct clang::DeducedPack {
611 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
Craig Topper0a4e1f52013-07-08 04:44:01 +0000612
Richard Smith0a80d572014-05-29 01:12:14 +0000613 // The index of the pack.
614 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000615
Richard Smith0a80d572014-05-29 01:12:14 +0000616 // The old value of the pack before we started deducing it.
617 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000618
Richard Smith0a80d572014-05-29 01:12:14 +0000619 // A deferred value of this pack from an inner deduction, that couldn't be
620 // deduced because this deduction hadn't happened yet.
621 DeducedTemplateArgument DeferredDeduction;
622
623 // The new value of the pack.
624 SmallVector<DeducedTemplateArgument, 4> New;
625
626 // The outer deduction for this pack, if any.
627 DeducedPack *Outer;
628};
629
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000630namespace {
Richard Smith0a80d572014-05-29 01:12:14 +0000631/// A scope in which we're performing pack deduction.
632class PackDeductionScope {
633public:
634 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
635 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
636 TemplateDeductionInfo &Info, TemplateArgument Pattern)
637 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
638 // Compute the set of template parameter indices that correspond to
639 // parameter packs expanded by the pack expansion.
640 {
641 llvm::SmallBitVector SawIndices(TemplateParams->size());
642 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
643 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
644 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
645 unsigned Depth, Index;
646 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
647 if (Depth == 0 && !SawIndices[Index]) {
648 SawIndices[Index] = true;
649
650 // Save the deduced template argument for the parameter pack expanded
651 // by this pack expansion, then clear out the deduction.
652 DeducedPack Pack(Index);
653 Pack.Saved = Deduced[Index];
654 Deduced[Index] = TemplateArgument();
655
656 Packs.push_back(Pack);
657 }
658 }
659 }
660 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
661
662 for (auto &Pack : Packs) {
663 if (Info.PendingDeducedPacks.size() > Pack.Index)
664 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
665 else
666 Info.PendingDeducedPacks.resize(Pack.Index + 1);
667 Info.PendingDeducedPacks[Pack.Index] = &Pack;
668
669 if (S.CurrentInstantiationScope) {
670 // If the template argument pack was explicitly specified, add that to
671 // the set of deduced arguments.
672 const TemplateArgument *ExplicitArgs;
673 unsigned NumExplicitArgs;
674 NamedDecl *PartiallySubstitutedPack =
675 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
676 &ExplicitArgs, &NumExplicitArgs);
677 if (PartiallySubstitutedPack &&
678 getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
679 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
680 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000681 }
682 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000683
Richard Smith0a80d572014-05-29 01:12:14 +0000684 ~PackDeductionScope() {
685 for (auto &Pack : Packs)
686 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000687 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Richard Smith0a80d572014-05-29 01:12:14 +0000689 /// Move to deducing the next element in each pack that is being deduced.
690 void nextPackElement() {
691 // Capture the deduced template arguments for each parameter pack expanded
692 // by this pack expansion, add them to the list of arguments we've deduced
693 // for that pack, then clear out the deduced argument.
694 for (auto &Pack : Packs) {
695 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
696 if (!DeducedArg.isNull()) {
697 Pack.New.push_back(DeducedArg);
698 DeducedArg = DeducedTemplateArgument();
699 }
700 }
701 }
702
703 /// \brief Finish template argument deduction for a set of argument packs,
704 /// producing the argument packs and checking for consistency with prior
705 /// deductions.
706 Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
707 // Build argument packs for each of the parameter packs expanded by this
708 // pack expansion.
709 for (auto &Pack : Packs) {
710 // Put back the old value for this pack.
711 Deduced[Pack.Index] = Pack.Saved;
712
713 // Build or find a new value for this pack.
714 DeducedTemplateArgument NewPack;
715 if (HasAnyArguments && Pack.New.empty()) {
716 if (Pack.DeferredDeduction.isNull()) {
717 // We were not able to deduce anything for this parameter pack
718 // (because it only appeared in non-deduced contexts), so just
719 // restore the saved argument pack.
720 continue;
721 }
722
723 NewPack = Pack.DeferredDeduction;
724 Pack.DeferredDeduction = TemplateArgument();
725 } else if (Pack.New.empty()) {
726 // If we deduced an empty argument pack, create it now.
727 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
728 } else {
729 TemplateArgument *ArgumentPack =
730 new (S.Context) TemplateArgument[Pack.New.size()];
731 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
732 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000733 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith0a80d572014-05-29 01:12:14 +0000734 Pack.New[0].wasDeducedFromArrayBound());
735 }
736
737 // Pick where we're going to put the merged pack.
738 DeducedTemplateArgument *Loc;
739 if (Pack.Outer) {
740 if (Pack.Outer->DeferredDeduction.isNull()) {
741 // Defer checking this pack until we have a complete pack to compare
742 // it against.
743 Pack.Outer->DeferredDeduction = NewPack;
744 continue;
745 }
746 Loc = &Pack.Outer->DeferredDeduction;
747 } else {
748 Loc = &Deduced[Pack.Index];
749 }
750
751 // Check the new pack matches any previous value.
752 DeducedTemplateArgument OldPack = *Loc;
753 DeducedTemplateArgument Result =
754 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
755
756 // If we deferred a deduction of this pack, check that one now too.
757 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
758 OldPack = Result;
759 NewPack = Pack.DeferredDeduction;
760 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
761 }
762
763 if (Result.isNull()) {
764 Info.Param =
765 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
766 Info.FirstArg = OldPack;
767 Info.SecondArg = NewPack;
768 return Sema::TDK_Inconsistent;
769 }
770
771 *Loc = Result;
772 }
773
774 return Sema::TDK_Success;
775 }
776
777private:
778 Sema &S;
779 TemplateParameterList *TemplateParams;
780 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
781 TemplateDeductionInfo &Info;
782
783 SmallVector<DeducedPack, 2> Packs;
784};
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000785} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000786
Douglas Gregor5499af42011-01-05 23:12:31 +0000787/// \brief Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000788/// types to the list of argument types, as in the parameter-type-lists of
789/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000790///
791/// \param S The semantic analysis object within which we are deducing
792///
793/// \param TemplateParams The template parameters that we are deducing
794///
795/// \param Params The list of parameter types
796///
797/// \param NumParams The number of types in \c Params
798///
799/// \param Args The list of argument types
800///
801/// \param NumArgs The number of types in \c Args
802///
803/// \param Info information about the template argument deduction itself
804///
805/// \param Deduced the deduced template arguments
806///
807/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
808/// how template argument deduction is performed.
809///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000810/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000812/// (C++0x [temp.deduct.partial]).
813///
Douglas Gregor5499af42011-01-05 23:12:31 +0000814/// \returns the result of template argument deduction so far. Note that a
815/// "success" result means that template argument deduction has not yet failed,
816/// but it may still fail, later, for other reasons.
817static Sema::TemplateDeductionResult
818DeduceTemplateArguments(Sema &S,
819 TemplateParameterList *TemplateParams,
820 const QualType *Params, unsigned NumParams,
821 const QualType *Args, unsigned NumArgs,
822 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000823 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +0000824 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000825 bool PartialOrdering = false) {
Douglas Gregor86bea352011-01-05 23:23:17 +0000826 // Fast-path check to see if we have too many/too few arguments.
827 if (NumParams != NumArgs &&
828 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
829 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
Richard Smith44ecdbd2013-01-31 05:19:49 +0000830 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000831
Douglas Gregor5499af42011-01-05 23:12:31 +0000832 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000833 // Similarly, if P has a form that contains (T), then each parameter type
834 // Pi of the respective parameter-type- list of P is compared with the
835 // corresponding parameter type Ai of the corresponding parameter-type-list
836 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +0000837 unsigned ArgIdx = 0, ParamIdx = 0;
838 for (; ParamIdx != NumParams; ++ParamIdx) {
839 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000840 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +0000841 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
842 if (!Expansion) {
843 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000844
Douglas Gregor5499af42011-01-05 23:12:31 +0000845 // Make sure we have an argument.
846 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000847 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000848
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000849 if (isa<PackExpansionType>(Args[ArgIdx])) {
850 // C++0x [temp.deduct.type]p22:
851 // If the original function parameter associated with A is a function
852 // parameter pack and the function parameter associated with P is not
853 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +0000854 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000855 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000856
Douglas Gregor5499af42011-01-05 23:12:31 +0000857 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000858 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
859 Params[ParamIdx], Args[ArgIdx],
860 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +0000861 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000862 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000863
Douglas Gregor5499af42011-01-05 23:12:31 +0000864 ++ArgIdx;
865 continue;
866 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000867
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000868 // C++0x [temp.deduct.type]p5:
869 // The non-deduced contexts are:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000870 // - A function parameter pack that does not occur at the end of the
Douglas Gregor0dd423e2011-01-11 01:52:23 +0000871 // parameter-declaration-clause.
872 if (ParamIdx + 1 < NumParams)
873 return Sema::TDK_Success;
874
Douglas Gregor5499af42011-01-05 23:12:31 +0000875 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000876 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +0000877 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000878 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +0000879 // comparison deduces template arguments for subsequent positions in the
880 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000881
Douglas Gregor5499af42011-01-05 23:12:31 +0000882 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +0000883 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000884
Douglas Gregor5499af42011-01-05 23:12:31 +0000885 bool HasAnyArguments = false;
886 for (; ArgIdx < NumArgs; ++ArgIdx) {
887 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888
Douglas Gregor5499af42011-01-05 23:12:31 +0000889 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000890 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000891 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
892 Args[ArgIdx], Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +0000893 TDF, PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +0000894 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000895
Richard Smith0a80d572014-05-29 01:12:14 +0000896 PackScope.nextPackElement();
Douglas Gregor5499af42011-01-05 23:12:31 +0000897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000898
Douglas Gregor5499af42011-01-05 23:12:31 +0000899 // Build argument packs for each of the parameter packs expanded by this
900 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +0000901 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000902 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +0000903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000904
Douglas Gregor5499af42011-01-05 23:12:31 +0000905 // Make sure we don't have any extra arguments.
906 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +0000907 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000908
Douglas Gregor5499af42011-01-05 23:12:31 +0000909 return Sema::TDK_Success;
910}
911
Douglas Gregor1d684c22011-04-28 00:56:09 +0000912/// \brief Determine whether the parameter has qualifiers that are either
913/// inconsistent with or a superset of the argument's qualifiers.
914static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
915 QualType ArgType) {
916 Qualifiers ParamQs = ParamType.getQualifiers();
917 Qualifiers ArgQs = ArgType.getQualifiers();
918
919 if (ParamQs == ArgQs)
920 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000921
Douglas Gregor1d684c22011-04-28 00:56:09 +0000922 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +0000923 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +0000924 ParamQs.hasObjCGCAttr())
925 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000926
Douglas Gregor1d684c22011-04-28 00:56:09 +0000927 // Mismatched (but not missing) address spaces.
928 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
929 ParamQs.hasAddressSpace())
930 return true;
931
John McCall31168b02011-06-15 23:02:42 +0000932 // Mismatched (but not missing) Objective-C lifetime qualifiers.
933 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
934 ParamQs.hasObjCLifetime())
935 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +0000936
Douglas Gregor1d684c22011-04-28 00:56:09 +0000937 // CVR qualifier superset.
938 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
939 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
940 == ParamQs.getCVRQualifiers());
941}
942
Douglas Gregor19a41f12013-04-17 08:45:07 +0000943/// \brief Compare types for equality with respect to possibly compatible
944/// function types (noreturn adjustment, implicit calling conventions). If any
945/// of parameter and argument is not a function, just perform type comparison.
946///
947/// \param Param the template parameter type.
948///
949/// \param Arg the argument type.
950bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
951 CanQualType Arg) {
952 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
953 *ArgFunction = Arg->getAs<FunctionType>();
954
955 // Just compare if not functions.
956 if (!ParamFunction || !ArgFunction)
957 return Param == Arg;
958
959 // Noreturn adjustment.
960 QualType AdjustedParam;
961 if (IsNoReturnConversion(Param, Arg, AdjustedParam))
962 return Arg == Context.getCanonicalType(AdjustedParam);
963
964 // FIXME: Compatible calling conventions.
965
966 return Param == Arg;
967}
968
Douglas Gregorcceb9752009-06-26 18:27:22 +0000969/// \brief Deduce the template arguments by comparing the parameter type and
970/// the argument type (C++ [temp.deduct.type]).
971///
Chandler Carruthc1263112010-02-07 21:33:28 +0000972/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000973///
974/// \param TemplateParams the template parameters that we are deducing
975///
976/// \param ParamIn the parameter type
977///
978/// \param ArgIn the argument type
979///
980/// \param Info information about the template argument deduction itself
981///
982/// \param Deduced the deduced template arguments
983///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000984/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +0000985/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +0000986///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000987/// \param PartialOrdering Whether we're performing template argument deduction
988/// in the context of partial ordering (C++0x [temp.deduct.partial]).
989///
Douglas Gregorcceb9752009-06-26 18:27:22 +0000990/// \returns the result of template argument deduction so far. Note that a
991/// "success" result means that template argument deduction has not yet failed,
992/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000993static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000994DeduceTemplateArgumentsByTypeMatch(Sema &S,
995 TemplateParameterList *TemplateParams,
996 QualType ParamIn, QualType ArgIn,
997 TemplateDeductionInfo &Info,
998 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
999 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001000 bool PartialOrdering,
1001 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001002 // We only want to look at the canonical types, since typedefs and
1003 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001004 QualType Param = S.Context.getCanonicalType(ParamIn);
1005 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001006
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001007 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001008 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001009 if (const PackExpansionType *ArgExpansion
1010 = dyn_cast<PackExpansionType>(Arg))
1011 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001012
Douglas Gregorb837ea42011-01-11 17:34:58 +00001013 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001014 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001015 // Before the partial ordering is done, certain transformations are
1016 // performed on the types used for partial ordering:
1017 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001018 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1019 if (ParamRef)
1020 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001021
Douglas Gregorb837ea42011-01-11 17:34:58 +00001022 // - If A is a reference type, A is replaced by the type referred to.
1023 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1024 if (ArgRef)
1025 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026
Richard Smithed563c22015-02-20 04:45:22 +00001027 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1028 // C++11 [temp.deduct.partial]p9:
1029 // If, for a given type, deduction succeeds in both directions (i.e.,
1030 // the types are identical after the transformations above) and both
1031 // P and A were reference types [...]:
1032 // - if [one type] was an lvalue reference and [the other type] was
1033 // not, [the other type] is not considered to be at least as
1034 // specialized as [the first type]
1035 // - if [one type] is more cv-qualified than [the other type],
1036 // [the other type] is not considered to be at least as specialized
1037 // as [the first type]
1038 // Objective-C ARC adds:
1039 // - [one type] has non-trivial lifetime, [the other type] has
1040 // __unsafe_unretained lifetime, and the types are otherwise
1041 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001042 //
Richard Smithed563c22015-02-20 04:45:22 +00001043 // A is "considered to be at least as specialized" as P iff deduction
1044 // succeeds, so we model this as a deduction failure. Note that
1045 // [the first type] is P and [the other type] is A here; the standard
1046 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001047 Qualifiers ParamQuals = Param.getQualifiers();
1048 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001049 if ((ParamRef->isLValueReferenceType() &&
1050 !ArgRef->isLValueReferenceType()) ||
1051 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1052 (ParamQuals.hasNonTrivialObjCLifetime() &&
1053 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1054 ParamQuals.withoutObjCLifetime() ==
1055 ArgQuals.withoutObjCLifetime())) {
1056 Info.FirstArg = TemplateArgument(ParamIn);
1057 Info.SecondArg = TemplateArgument(ArgIn);
1058 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001059 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001061
Richard Smithed563c22015-02-20 04:45:22 +00001062 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001063 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001064 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001065 // version of P.
1066 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001067 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001068 // version of A.
1069 Arg = Arg.getUnqualifiedType();
1070 } else {
1071 // C++0x [temp.deduct.call]p4 bullet 1:
1072 // - If the original P is a reference type, the deduced A (i.e., the type
1073 // referred to by the reference) can be more cv-qualified than the
1074 // transformed A.
1075 if (TDF & TDF_ParamWithReferenceType) {
1076 Qualifiers Quals;
1077 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1078 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001079 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001080 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001082
Douglas Gregor85f240c2011-01-25 17:19:08 +00001083 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1084 // C++0x [temp.deduct.type]p10:
1085 // If P and A are function types that originated from deduction when
1086 // taking the address of a function template (14.8.2.2) or when deducing
1087 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001088 // Ai are parameters of the top-level parameter-type-list of P and A,
1089 // respectively, Pi is adjusted if it is an rvalue reference to a
1090 // cv-unqualified template parameter and Ai is an lvalue reference, in
1091 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001092 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1093 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001094 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001095 TDF &= ~TDF_TopLevelParameterTypeList;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001096
Douglas Gregor85f240c2011-01-25 17:19:08 +00001097 if (const RValueReferenceType *ParamRef
1098 = Param->getAs<RValueReferenceType>()) {
1099 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1100 !ParamRef->getPointeeType().getQualifiers())
1101 if (Arg->isLValueReferenceType())
1102 Param = ParamRef->getPointeeType();
1103 }
1104 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001105 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001106
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001107 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001108 // A template type argument T, a template template argument TT or a
1109 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001110 // the following forms:
1111 //
1112 // T
1113 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001114 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001115 = Param->getAs<TemplateTypeParmType>()) {
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001116 // Just skip any attempts to deduce from a placeholder type.
1117 if (Arg->isPlaceholderType())
1118 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001119
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001120 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001121 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001122
Douglas Gregor60454822009-07-22 20:02:25 +00001123 // If the argument type is an array type, move the qualifiers up to the
1124 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001125 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001126 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001127 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001128 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001129 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001130 RecanonicalizeArg = true;
1131 }
1132 }
Mike Stump11289f42009-09-09 15:08:12 +00001133
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001134 // The argument type can not be less qualified than the parameter
1135 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001136 if (!(TDF & TDF_IgnoreQualifiers) &&
1137 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001138 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001139 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001140 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001141 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001142 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001143
1144 assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
Chandler Carruthc1263112010-02-07 21:33:28 +00001145 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001146 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001147
Douglas Gregor1d684c22011-04-28 00:56:09 +00001148 // Remove any qualifiers on the parameter from the deduced type.
1149 // We checked the qualifiers for consistency above.
1150 Qualifiers DeducedQs = DeducedType.getQualifiers();
1151 Qualifiers ParamQs = Param.getQualifiers();
1152 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1153 if (ParamQs.hasObjCGCAttr())
1154 DeducedQs.removeObjCGCAttr();
1155 if (ParamQs.hasAddressSpace())
1156 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001157 if (ParamQs.hasObjCLifetime())
1158 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001159
Douglas Gregore46db902011-06-17 22:11:49 +00001160 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001161 // If template deduction would produce a lifetime qualifier on a type
1162 // that is not a lifetime type, template argument deduction fails.
1163 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1164 !DeducedType->isDependentType()) {
1165 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1166 Info.FirstArg = TemplateArgument(Param);
1167 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001168 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001169 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001170
Douglas Gregora4f2b432011-07-26 14:53:44 +00001171 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001172 // If template deduction would produce an argument type with lifetime type
1173 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001174 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001175 DeducedType->isObjCLifetimeType() &&
1176 !DeducedQs.hasObjCLifetime())
1177 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001178
Douglas Gregor1d684c22011-04-28 00:56:09 +00001179 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1180 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001181
Douglas Gregord6605db2009-07-22 21:30:48 +00001182 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001183 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001184
Richard Smith5f274382016-09-28 23:55:27 +00001185 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001187 Deduced[Index],
1188 NewDeduced);
1189 if (Result.isNull()) {
1190 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1191 Info.FirstArg = Deduced[Index];
1192 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001193 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001194 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001195
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001196 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001197 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001198 }
1199
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001200 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001201 Info.FirstArg = TemplateArgument(ParamIn);
1202 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001203
Douglas Gregorfb322d82011-01-14 05:11:40 +00001204 // If the parameter is an already-substituted template parameter
1205 // pack, do nothing: we don't know which of its arguments to look
1206 // at, so we have to wait until all of the parameter packs in this
1207 // expansion have arguments.
1208 if (isa<SubstTemplateTypeParmPackType>(Param))
1209 return Sema::TDK_Success;
1210
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001211 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001212 CanQualType CanParam = S.Context.getCanonicalType(Param);
1213 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001214 if (!(TDF & TDF_IgnoreQualifiers)) {
1215 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001216 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001217 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001218 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001219 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001220 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001221 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001222
Douglas Gregor194ea692012-03-11 03:29:50 +00001223 // If the parameter type is not dependent, there is nothing to deduce.
1224 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001225 if (!(TDF & TDF_SkipNonDependent)) {
1226 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1227 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1228 Param != Arg;
1229 if (NonDeduced) {
1230 return Sema::TDK_NonDeducedMismatch;
1231 }
1232 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001233 return Sema::TDK_Success;
1234 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001235 } else if (!Param->isDependentType()) {
1236 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1237 ArgUnqualType = CanArg.getUnqualifiedType();
1238 bool Success = (TDF & TDF_InOverloadResolution)?
1239 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1240 ArgUnqualType) :
1241 ParamUnqualType == ArgUnqualType;
1242 if (Success)
1243 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001244 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001245
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001246 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001247 // Non-canonical types cannot appear here.
1248#define NON_CANONICAL_TYPE(Class, Base) \
1249 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1250#define TYPE(Class, Base)
1251#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001252
Douglas Gregor39c02722011-06-15 16:02:29 +00001253 case Type::TemplateTypeParm:
1254 case Type::SubstTemplateTypeParmPack:
1255 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001256
1257 // These types cannot be dependent, so simply check whether the types are
1258 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001259 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001260 case Type::VariableArray:
1261 case Type::Vector:
1262 case Type::FunctionNoProto:
1263 case Type::Record:
1264 case Type::Enum:
1265 case Type::ObjCObject:
1266 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001267 case Type::ObjCObjectPointer: {
1268 if (TDF & TDF_SkipNonDependent)
1269 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001270
Douglas Gregor194ea692012-03-11 03:29:50 +00001271 if (TDF & TDF_IgnoreQualifiers) {
1272 Param = Param.getUnqualifiedType();
1273 Arg = Arg.getUnqualifiedType();
1274 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001275
Douglas Gregor194ea692012-03-11 03:29:50 +00001276 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1277 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001278
1279 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001280 case Type::Complex:
1281 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001282 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1283 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001284 ComplexArg->getElementType(),
1285 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001286
1287 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001288
1289 // _Atomic T [extension]
1290 case Type::Atomic:
1291 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001292 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001293 cast<AtomicType>(Param)->getValueType(),
1294 AtomicArg->getValueType(),
1295 Info, Deduced, TDF);
1296
1297 return Sema::TDK_NonDeducedMismatch;
1298
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001299 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001300 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001301 QualType PointeeType;
1302 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1303 PointeeType = PointerArg->getPointeeType();
1304 } else if (const ObjCObjectPointerType *PointerArg
1305 = Arg->getAs<ObjCObjectPointerType>()) {
1306 PointeeType = PointerArg->getPointeeType();
1307 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001308 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001309 }
Mike Stump11289f42009-09-09 15:08:12 +00001310
Douglas Gregorfc516c92009-06-26 23:27:24 +00001311 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001312 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1313 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001314 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001315 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001316 }
Mike Stump11289f42009-09-09 15:08:12 +00001317
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001318 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001319 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001320 const LValueReferenceType *ReferenceArg =
1321 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001322 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001323 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001324
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001325 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001326 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001327 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001328 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001329
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001330 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001331 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001332 const RValueReferenceType *ReferenceArg =
1333 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001334 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001335 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001336
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001337 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1338 cast<RValueReferenceType>(Param)->getPointeeType(),
1339 ReferenceArg->getPointeeType(),
1340 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001341 }
Mike Stump11289f42009-09-09 15:08:12 +00001342
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001343 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001344 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001345 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001346 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001347 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001348 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001349
John McCallf7332682010-08-19 00:20:19 +00001350 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001351 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1352 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1353 IncompleteArrayArg->getElementType(),
1354 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001355 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001356
1357 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001358 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001359 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001360 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001361 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001362 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001363
1364 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001365 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001366 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001367 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001368
John McCallf7332682010-08-19 00:20:19 +00001369 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001370 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1371 ConstantArrayParm->getElementType(),
1372 ConstantArrayArg->getElementType(),
1373 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001374 }
1375
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001376 // type [i]
1377 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001378 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001379 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001380 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001381
John McCallf7332682010-08-19 00:20:19 +00001382 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1383
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001384 // Check the element type of the arrays
1385 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001386 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001387 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001388 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1389 DependentArrayParm->getElementType(),
1390 ArrayArg->getElementType(),
1391 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001392 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001393
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001394 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001395 NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001396 = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1397 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001398 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001399
1400 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001401 // template parameter.
Mike Stump11289f42009-09-09 15:08:12 +00001402 assert(NTTP->getDepth() == 0 &&
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001403 "Cannot deduce non-type template argument at depth > 0");
Mike Stump11289f42009-09-09 15:08:12 +00001404 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001405 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1406 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001407 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001408 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001409 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001410 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001411 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001412 if (const DependentSizedArrayType *DependentArrayArg
1413 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001414 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001415 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001416 DependentArrayArg->getSizeExpr(),
1417 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001419 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001420 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001421 }
Mike Stump11289f42009-09-09 15:08:12 +00001422
1423 // type(*)(T)
1424 // T(*)()
1425 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001426 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001427 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001428 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001429 dyn_cast<FunctionProtoType>(Arg);
1430 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001431 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001432
1433 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001434 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001435
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001436 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001437 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001438 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001439 != FunctionProtoArg->getRefQualifier() ||
1440 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001441 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001442
Anders Carlsson2128ec72009-06-08 15:19:08 +00001443 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001444 if (Sema::TemplateDeductionResult Result =
1445 DeduceTemplateArgumentsByTypeMatch(
1446 S, TemplateParams, FunctionProtoParam->getReturnType(),
1447 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001448 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001449
Alp Toker9cacbab2014-01-20 20:26:09 +00001450 return DeduceTemplateArguments(
1451 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1452 FunctionProtoParam->getNumParams(),
1453 FunctionProtoArg->param_type_begin(),
1454 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001455 }
Mike Stump11289f42009-09-09 15:08:12 +00001456
John McCalle78aac42010-03-10 03:28:59 +00001457 case Type::InjectedClassName: {
1458 // Treat a template's injected-class-name as if the template
1459 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001460 Param = cast<InjectedClassNameType>(Param)
1461 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001462 assert(isa<TemplateSpecializationType>(Param) &&
1463 "injected class name is not a template specialization type");
1464 // fall through
1465 }
1466
Douglas Gregor705c9002009-06-26 20:57:09 +00001467 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001468 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001469 // TT<T>
1470 // TT<i>
1471 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001472 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001473 const TemplateSpecializationType *SpecParam =
1474 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001475
Richard Smith9b296e32016-04-25 19:09:05 +00001476 // When Arg cannot be a derived class, we can just try to deduce template
1477 // arguments from the template-id.
1478 const RecordType *RecordT = Arg->getAs<RecordType>();
1479 if (!(TDF & TDF_DerivedClass) || !RecordT)
1480 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1481 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001482
Richard Smith9b296e32016-04-25 19:09:05 +00001483 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1484 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001485
Richard Smith9b296e32016-04-25 19:09:05 +00001486 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1487 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001488
Richard Smith9b296e32016-04-25 19:09:05 +00001489 if (Result == Sema::TDK_Success)
1490 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001491
Richard Smith9b296e32016-04-25 19:09:05 +00001492 // We cannot inspect base classes as part of deduction when the type
1493 // is incomplete, so either instantiate any templates necessary to
1494 // complete the type, or skip over it if it cannot be completed.
1495 if (!S.isCompleteType(Info.getLocation(), Arg))
1496 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001497
Richard Smith9b296e32016-04-25 19:09:05 +00001498 // C++14 [temp.deduct.call] p4b3:
1499 // If P is a class and P has the form simple-template-id, then the
1500 // transformed A can be a derived class of the deduced A. Likewise if
1501 // P is a pointer to a class of the form simple-template-id, the
1502 // transformed A can be a pointer to a derived class pointed to by the
1503 // deduced A.
1504 //
1505 // These alternatives are considered only if type deduction would
1506 // otherwise fail. If they yield more than one possible deduced A, the
1507 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001508
Faisal Vali683b0742016-05-19 02:28:21 +00001509 // Reset the incorrectly deduced argument from above.
1510 Deduced = DeducedOrig;
1511
1512 // Use data recursion to crawl through the list of base classes.
1513 // Visited contains the set of nodes we have already visited, while
1514 // ToVisit is our stack of records that we still need to visit.
1515 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1516 SmallVector<const RecordType *, 8> ToVisit;
1517 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001518 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001519 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001520 while (!ToVisit.empty()) {
1521 // Retrieve the next class in the inheritance hierarchy.
1522 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001523
Faisal Vali683b0742016-05-19 02:28:21 +00001524 // If we have already seen this type, skip it.
1525 if (!Visited.insert(NextT).second)
1526 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001527
Faisal Vali683b0742016-05-19 02:28:21 +00001528 // If this is a base class, try to perform template argument
1529 // deduction from it.
1530 if (NextT != RecordT) {
1531 TemplateDeductionInfo BaseInfo(Info.getLocation());
1532 Sema::TemplateDeductionResult BaseResult =
1533 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1534 QualType(NextT, 0), BaseInfo, Deduced);
1535
1536 // If template argument deduction for this base was successful,
1537 // note that we had some success. Otherwise, ignore any deductions
1538 // from this base class.
1539 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001540 // If we've already seen some success, then deduction fails due to
1541 // an ambiguity (temp.deduct.call p5).
1542 if (Successful)
1543 return Sema::TDK_MiscellaneousDeductionFailure;
1544
Faisal Vali683b0742016-05-19 02:28:21 +00001545 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001546 std::swap(SuccessfulDeduced, Deduced);
1547
Faisal Vali683b0742016-05-19 02:28:21 +00001548 Info.Param = BaseInfo.Param;
1549 Info.FirstArg = BaseInfo.FirstArg;
1550 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001551 }
1552
1553 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001554 }
Mike Stump11289f42009-09-09 15:08:12 +00001555
Faisal Vali683b0742016-05-19 02:28:21 +00001556 // Visit base classes
1557 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1558 for (const auto &Base : Next->bases()) {
1559 assert(Base.getType()->isRecordType() &&
1560 "Base class that isn't a record?");
1561 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1562 }
1563 }
Mike Stump11289f42009-09-09 15:08:12 +00001564
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001565 if (Successful) {
1566 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001567 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001568 }
Richard Smith9b296e32016-04-25 19:09:05 +00001569
Douglas Gregore81f3e72009-07-07 23:09:34 +00001570 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001571 }
1572
Douglas Gregor637d9982009-06-10 23:47:09 +00001573 // T type::*
1574 // T T::*
1575 // T (type::*)()
1576 // type (T::*)()
1577 // type (type::*)(T)
1578 // type (T::*)(T)
1579 // T (type::*)(T)
1580 // T (T::*)()
1581 // T (T::*)(T)
1582 case Type::MemberPointer: {
1583 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1584 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1585 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001586 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001587
David Majnemera381cda2015-11-30 20:34:28 +00001588 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1589 if (ParamPointeeType->isFunctionType())
1590 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1591 /*IsCtorOrDtor=*/false, Info.getLocation());
1592 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1593 if (ArgPointeeType->isFunctionType())
1594 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1595 /*IsCtorOrDtor=*/false, Info.getLocation());
1596
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001597 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001598 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001599 ParamPointeeType,
1600 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001601 Info, Deduced,
1602 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001603 return Result;
1604
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001605 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1606 QualType(MemPtrParam->getClass(), 0),
1607 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001608 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001609 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001610 }
1611
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001612 // (clang extension)
1613 //
Mike Stump11289f42009-09-09 15:08:12 +00001614 // type(^)(T)
1615 // T(^)()
1616 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001617 case Type::BlockPointer: {
1618 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1619 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001620
Anders Carlssona767eee2009-06-12 16:23:10 +00001621 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001622 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001623
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001624 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1625 BlockPtrParam->getPointeeType(),
1626 BlockPtrArg->getPointeeType(),
1627 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001628 }
1629
Douglas Gregor39c02722011-06-15 16:02:29 +00001630 // (clang extension)
1631 //
1632 // T __attribute__(((ext_vector_type(<integral constant>))))
1633 case Type::ExtVector: {
1634 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1635 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1636 // Make sure that the vectors have the same number of elements.
1637 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1638 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001639
Douglas Gregor39c02722011-06-15 16:02:29 +00001640 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001641 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1642 VectorParam->getElementType(),
1643 VectorArg->getElementType(),
1644 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001645 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001646
1647 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001648 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1649 // We can't check the number of elements, since the argument has a
1650 // dependent number of elements. This can only occur during partial
1651 // ordering.
1652
1653 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001654 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1655 VectorParam->getElementType(),
1656 VectorArg->getElementType(),
1657 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001658 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001659
Douglas Gregor39c02722011-06-15 16:02:29 +00001660 return Sema::TDK_NonDeducedMismatch;
1661 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001662
Douglas Gregor39c02722011-06-15 16:02:29 +00001663 // (clang extension)
1664 //
1665 // T __attribute__(((ext_vector_type(N))))
1666 case Type::DependentSizedExtVector: {
1667 const DependentSizedExtVectorType *VectorParam
1668 = cast<DependentSizedExtVectorType>(Param);
1669
1670 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1671 // Perform deduction on the element types.
1672 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001673 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1674 VectorParam->getElementType(),
1675 VectorArg->getElementType(),
1676 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001677 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001678
Douglas Gregor39c02722011-06-15 16:02:29 +00001679 // Perform deduction on the vector size, if we can.
1680 NonTypeTemplateParmDecl *NTTP
1681 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1682 if (!NTTP)
1683 return Sema::TDK_Success;
1684
1685 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1686 ArgSize = VectorArg->getNumElements();
Richard Smith5f274382016-09-28 23:55:27 +00001687 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1688 S.Context.IntTy, false, Info, Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001689 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001690
1691 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001692 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1693 // Perform deduction on the element types.
1694 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001695 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1696 VectorParam->getElementType(),
1697 VectorArg->getElementType(),
1698 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001699 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001700
Douglas Gregor39c02722011-06-15 16:02:29 +00001701 // Perform deduction on the vector size, if we can.
1702 NonTypeTemplateParmDecl *NTTP
1703 = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1704 if (!NTTP)
1705 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001706
Richard Smith5f274382016-09-28 23:55:27 +00001707 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1708 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001709 Info, Deduced);
1710 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001711
Douglas Gregor39c02722011-06-15 16:02:29 +00001712 return Sema::TDK_NonDeducedMismatch;
1713 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001714
Douglas Gregor637d9982009-06-10 23:47:09 +00001715 case Type::TypeOfExpr:
1716 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001717 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001718 case Type::UnresolvedUsing:
1719 case Type::Decltype:
1720 case Type::UnaryTransform:
1721 case Type::Auto:
1722 case Type::DependentTemplateSpecialization:
1723 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001724 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001725 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001726 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001727 }
1728
David Blaikiee4d798f2012-01-20 21:50:17 +00001729 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001730}
1731
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001732static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001733DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001734 TemplateParameterList *TemplateParams,
1735 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001736 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001737 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001738 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001739 // If the template argument is a pack expansion, perform template argument
1740 // deduction against the pattern of that expansion. This only occurs during
1741 // partial ordering.
1742 if (Arg.isPackExpansion())
1743 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001744
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001745 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001746 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001747 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001748
1749 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001750 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001751 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1752 Param.getAsType(),
1753 Arg.getAsType(),
1754 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001755 Info.FirstArg = Param;
1756 Info.SecondArg = Arg;
1757 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001758
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001759 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001760 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001761 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001762 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001763 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001764 Info.FirstArg = Param;
1765 Info.SecondArg = Arg;
1766 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001767
1768 case TemplateArgument::TemplateExpansion:
1769 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001771 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001772 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001773 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001774 return Sema::TDK_Success;
1775
1776 Info.FirstArg = Param;
1777 Info.SecondArg = Arg;
1778 return Sema::TDK_NonDeducedMismatch;
1779
1780 case TemplateArgument::NullPtr:
1781 if (Arg.getKind() == TemplateArgument::NullPtr &&
1782 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001783 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001785 Info.FirstArg = Param;
1786 Info.SecondArg = Arg;
1787 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001788
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001789 case TemplateArgument::Integral:
1790 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001791 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001792 return Sema::TDK_Success;
1793
1794 Info.FirstArg = Param;
1795 Info.SecondArg = Arg;
1796 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001797 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001798
1799 if (Arg.getKind() == TemplateArgument::Expression) {
1800 Info.FirstArg = Param;
1801 Info.SecondArg = Arg;
1802 return Sema::TDK_NonDeducedMismatch;
1803 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001804
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001805 Info.FirstArg = Param;
1806 Info.SecondArg = Arg;
1807 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001808
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001809 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001810 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001811 = getDeducedParameterFromExpr(Param.getAsExpr())) {
1812 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001813 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001814 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001815 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001816 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001817 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001818 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001819 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1820 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001821 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001822 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001823 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1824 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001825 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001826 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1827 Arg.getAsDecl(),
1828 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001829 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001830
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001831 Info.FirstArg = Param;
1832 Info.SecondArg = Arg;
1833 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001834 }
Mike Stump11289f42009-09-09 15:08:12 +00001835
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001836 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001837 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001838 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001839 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001840 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001841 }
Mike Stump11289f42009-09-09 15:08:12 +00001842
David Blaikiee4d798f2012-01-20 21:50:17 +00001843 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001844}
1845
Douglas Gregor7baabef2010-12-22 18:17:10 +00001846/// \brief Determine whether there is a template argument to be used for
1847/// deduction.
1848///
1849/// This routine "expands" argument packs in-place, overriding its input
1850/// parameters so that \c Args[ArgIdx] will be the available template argument.
1851///
1852/// \returns true if there is another template argument (which will be at
1853/// \c Args[ArgIdx]), false otherwise.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001854static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001855 unsigned &ArgIdx,
1856 unsigned &NumArgs) {
1857 if (ArgIdx == NumArgs)
1858 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001859
Douglas Gregor7baabef2010-12-22 18:17:10 +00001860 const TemplateArgument &Arg = Args[ArgIdx];
1861 if (Arg.getKind() != TemplateArgument::Pack)
1862 return true;
1863
1864 assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1865 Args = Arg.pack_begin();
1866 NumArgs = Arg.pack_size();
1867 ArgIdx = 0;
1868 return ArgIdx < NumArgs;
1869}
1870
Douglas Gregord0ad2942010-12-23 01:24:45 +00001871/// \brief Determine whether the given set of template arguments has a pack
1872/// expansion that is not the last template argument.
1873static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args,
1874 unsigned NumArgs) {
1875 unsigned ArgIdx = 0;
1876 while (ArgIdx < NumArgs) {
1877 const TemplateArgument &Arg = Args[ArgIdx];
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001878
Douglas Gregord0ad2942010-12-23 01:24:45 +00001879 // Unwrap argument packs.
1880 if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1881 Args = Arg.pack_begin();
1882 NumArgs = Arg.pack_size();
1883 ArgIdx = 0;
1884 continue;
1885 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001886
Douglas Gregord0ad2942010-12-23 01:24:45 +00001887 ++ArgIdx;
1888 if (ArgIdx == NumArgs)
1889 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890
Douglas Gregord0ad2942010-12-23 01:24:45 +00001891 if (Arg.isPackExpansion())
1892 return true;
1893 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001894
Douglas Gregord0ad2942010-12-23 01:24:45 +00001895 return false;
1896}
1897
Douglas Gregor7baabef2010-12-22 18:17:10 +00001898static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001899DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001900 const TemplateArgument *Params, unsigned NumParams,
1901 const TemplateArgument *Args, unsigned NumArgs,
1902 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001903 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1904 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001905 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001906 // If the template argument list of P contains a pack expansion that is not
1907 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001908 // non-deduced context.
Douglas Gregord0ad2942010-12-23 01:24:45 +00001909 if (hasPackExpansionBeforeEnd(Params, NumParams))
1910 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001911
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001912 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913 // If P has a form that contains <T> or <i>, then each argument Pi of the
1914 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001915 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001916 unsigned ArgIdx = 0, ParamIdx = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001917 for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
Douglas Gregor7baabef2010-12-22 18:17:10 +00001918 ++ParamIdx) {
1919 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.
1923 if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
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 Smith0a80d572014-05-29 01:12:14 +00001965 for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++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) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001994 ParamList.data(), ParamList.size(),
1995 ArgList.data(), ArgList.size(),
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001996 Info, Deduced, false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001997}
1998
Douglas Gregor705c9002009-06-26 20:57:09 +00001999/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002000static bool isSameTemplateArg(ASTContext &Context,
Douglas Gregor705c9002009-06-26 20:57:09 +00002001 const TemplateArgument &X,
2002 const TemplateArgument &Y) {
2003 if (X.getKind() != Y.getKind())
2004 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002005
Douglas Gregor705c9002009-06-26 20:57:09 +00002006 switch (X.getKind()) {
2007 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002008 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002009
Douglas Gregor705c9002009-06-26 20:57:09 +00002010 case TemplateArgument::Type:
2011 return Context.getCanonicalType(X.getAsType()) ==
2012 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002013
Douglas Gregor705c9002009-06-26 20:57:09 +00002014 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002015 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002016
2017 case TemplateArgument::NullPtr:
2018 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002019
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002020 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002021 case TemplateArgument::TemplateExpansion:
2022 return Context.getCanonicalTemplateName(
2023 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2024 Context.getCanonicalTemplateName(
2025 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002026
Douglas Gregor705c9002009-06-26 20:57:09 +00002027 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002028 return X.getAsIntegral() == Y.getAsIntegral();
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002030 case TemplateArgument::Expression: {
2031 llvm::FoldingSetNodeID XID, YID;
2032 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002034 return XID == YID;
2035 }
Mike Stump11289f42009-09-09 15:08:12 +00002036
Douglas Gregor705c9002009-06-26 20:57:09 +00002037 case TemplateArgument::Pack:
2038 if (X.pack_size() != Y.pack_size())
2039 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002040
2041 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2042 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002043 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002044 XP != XPEnd; ++XP, ++YP)
Douglas Gregor705c9002009-06-26 20:57:09 +00002045 if (!isSameTemplateArg(Context, *XP, *YP))
2046 return false;
2047
2048 return true;
2049 }
2050
David Blaikiee4d798f2012-01-20 21:50:17 +00002051 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002052}
2053
Douglas Gregorca4686d2011-01-04 23:35:54 +00002054/// \brief Allocate a TemplateArgumentLoc where all locations have
2055/// been initialized to the given location.
2056///
James Dennett634962f2012-06-14 21:40:34 +00002057/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002058/// location information for.
2059///
2060/// \param NTTPType For a declaration template argument, the type of
2061/// the non-type template parameter that corresponds to this template
2062/// argument.
2063///
2064/// \param Loc The source location to use for the resulting template
2065/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002066TemplateArgumentLoc
2067Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2068 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002069 switch (Arg.getKind()) {
2070 case TemplateArgument::Null:
2071 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002072
Douglas Gregorca4686d2011-01-04 23:35:54 +00002073 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002074 return TemplateArgumentLoc(
2075 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002076
Douglas Gregorca4686d2011-01-04 23:35:54 +00002077 case TemplateArgument::Declaration: {
Richard Smith7873de02016-08-11 22:25:46 +00002078 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2079 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002080 return TemplateArgumentLoc(TemplateArgument(E), E);
2081 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082
Eli Friedmanb826a002012-09-26 02:36:12 +00002083 case TemplateArgument::NullPtr: {
Richard Smith7873de02016-08-11 22:25:46 +00002084 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2085 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002086 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2087 E);
2088 }
2089
Douglas Gregorca4686d2011-01-04 23:35:54 +00002090 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002091 Expr *E =
2092 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002093 return TemplateArgumentLoc(TemplateArgument(E), E);
2094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095
Douglas Gregor9d802122011-03-02 17:09:35 +00002096 case TemplateArgument::Template:
2097 case TemplateArgument::TemplateExpansion: {
2098 NestedNameSpecifierLocBuilder Builder;
2099 TemplateName Template = Arg.getAsTemplate();
2100 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002101 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002102 else if (QualifiedTemplateName *QTN =
2103 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002104 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002105
Douglas Gregor9d802122011-03-02 17:09:35 +00002106 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002107 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002108 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002109
2110 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002111 Loc, Loc);
2112 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002113
Douglas Gregorca4686d2011-01-04 23:35:54 +00002114 case TemplateArgument::Expression:
2115 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002116
Douglas Gregorca4686d2011-01-04 23:35:54 +00002117 case TemplateArgument::Pack:
2118 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002120
David Blaikiee4d798f2012-01-20 21:50:17 +00002121 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002122}
2123
2124
2125/// \brief Convert the given deduced template argument and add it to the set of
2126/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002127static bool
2128ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2129 DeducedTemplateArgument Arg,
2130 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002131 TemplateDeductionInfo &Info,
2132 bool InFunctionTemplate,
2133 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002134 // First, for a non-type template parameter type that is
2135 // initialized by a declaration, we need the type of the
2136 // corresponding non-type template parameter.
2137 QualType NTTPType;
2138 if (NonTypeTemplateParmDecl *NTTP =
2139 dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2140 NTTPType = NTTP->getType();
2141 if (NTTPType->isDependentType()) {
David Majnemer8b622692016-07-03 21:17:51 +00002142 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith37acb792016-02-03 20:15:01 +00002143 NTTPType = S.SubstType(NTTPType,
2144 MultiLevelTemplateArgumentList(TemplateArgs),
2145 NTTP->getLocation(),
2146 NTTP->getDeclName());
2147 if (NTTPType.isNull())
2148 return true;
2149 }
2150 }
2151
2152 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2153 unsigned ArgumentPackIndex) {
2154 // Convert the deduced template argument into a template
2155 // argument that we can check, almost as if the user had written
2156 // the template argument explicitly.
2157 TemplateArgumentLoc ArgLoc =
Richard Smith7873de02016-08-11 22:25:46 +00002158 S.getTrivialTemplateArgumentLoc(Arg, NTTPType, Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002159
2160 // Check the template argument, converting it as necessary.
2161 return S.CheckTemplateArgument(
2162 Param, ArgLoc, Template, Template->getLocation(),
2163 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2164 InFunctionTemplate
2165 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2166 : Sema::CTAK_Deduced)
2167 : Sema::CTAK_Specified);
2168 };
2169
Douglas Gregorca4686d2011-01-04 23:35:54 +00002170 if (Arg.getKind() == TemplateArgument::Pack) {
2171 // This is a template argument pack, so check each of its arguments against
2172 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002173 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002174 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002175 // When converting the deduced template argument, append it to the
2176 // general output list. We need to do this so that the template argument
2177 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002178 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002179 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002180 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2181 "deduced nested pack");
2182 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002183 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184
Douglas Gregor51bc5712011-01-05 20:52:18 +00002185 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002186 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188
Richard Smithdf18ee92016-02-03 20:40:30 +00002189 // If the pack is empty, we still need to substitute into the parameter
2190 // itself, in case that substitution fails. For non-type parameters, we did
2191 // this above. For type parameters, no substitution is ever required.
2192 auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param);
2193 if (TTP && PackedArgsBuilder.empty()) {
2194 // Set up a template instantiation context.
2195 LocalInstantiationScope Scope(S);
2196 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2197 TTP, Output,
2198 Template->getSourceRange());
2199 if (Inst.isInvalid())
2200 return true;
2201
David Majnemer8b622692016-07-03 21:17:51 +00002202 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smithdf18ee92016-02-03 20:40:30 +00002203 if (!S.SubstDecl(TTP, S.CurContext,
2204 MultiLevelTemplateArgumentList(TemplateArgs)))
2205 return true;
2206 }
Richard Smith37acb792016-02-03 20:15:01 +00002207
Douglas Gregorca4686d2011-01-04 23:35:54 +00002208 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002209 Output.push_back(
2210 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002211 return false;
2212 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002213
Richard Smith37acb792016-02-03 20:15:01 +00002214 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002215}
2216
Douglas Gregor684268d2010-04-29 06:21:43 +00002217/// Complete template argument deduction for a class template partial
2218/// specialization.
2219static Sema::TemplateDeductionResult
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002220FinishTemplateArgumentDeduction(Sema &S,
Douglas Gregor684268d2010-04-29 06:21:43 +00002221 ClassTemplatePartialSpecializationDecl *Partial,
2222 const TemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002223 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
John McCall19c1bfd2010-08-25 05:32:35 +00002224 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002225 // Unevaluated SFINAE context.
2226 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002227 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002228
Douglas Gregor684268d2010-04-29 06:21:43 +00002229 Sema::ContextRAII SavedContext(S, Partial);
2230
2231 // C++ [temp.deduct.type]p2:
2232 // [...] or if any template argument remains neither deduced nor
2233 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002234 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraef93f22011-01-04 22:23:38 +00002235 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2236 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002237 NamedDecl *Param = PartialParams->getParam(I);
Douglas Gregor684268d2010-04-29 06:21:43 +00002238 if (Deduced[I].isNull()) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002239 Info.Param = makeTemplateParameter(Param);
Douglas Gregor684268d2010-04-29 06:21:43 +00002240 return Sema::TDK_Incomplete;
2241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242
Douglas Gregorca4686d2011-01-04 23:35:54 +00002243 // We have deduced this argument, so it still needs to be
2244 // checked and converted.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002245 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002246 Partial, Info, false,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002247 Builder)) {
2248 Info.Param = makeTemplateParameter(Param);
2249 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002250 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002251 return Sema::TDK_SubstitutionFailure;
2252 }
Douglas Gregor684268d2010-04-29 06:21:43 +00002253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002254
Douglas Gregor684268d2010-04-29 06:21:43 +00002255 // Form the template argument list from the deduced template arguments.
2256 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002257 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002258
Douglas Gregor684268d2010-04-29 06:21:43 +00002259 Info.reset(DeducedArgumentList);
2260
2261 // Substitute the deduced template arguments into the template
2262 // arguments of the class template partial specialization, and
2263 // verify that the instantiated template arguments are both valid
2264 // and are equivalent to the template arguments originally provided
2265 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002266 LocalInstantiationScope InstScope(S);
Douglas Gregor684268d2010-04-29 06:21:43 +00002267 ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002268 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
Douglas Gregor684268d2010-04-29 06:21:43 +00002269 = Partial->getTemplateArgsAsWritten();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002270 const TemplateArgumentLoc *PartialTemplateArgs
2271 = PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002272
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002273 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2274 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002275
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002276 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002277 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2278 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2279 if (ParamIdx >= Partial->getTemplateParameters()->size())
2280 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2281
2282 Decl *Param
2283 = const_cast<NamedDecl *>(
2284 Partial->getTemplateParameters()->getParam(ParamIdx));
2285 Info.Param = makeTemplateParameter(Param);
2286 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2287 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002288 }
2289
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002290 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Douglas Gregor684268d2010-04-29 06:21:43 +00002291 if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
Douglas Gregorca4686d2011-01-04 23:35:54 +00002292 InstArgs, false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002293 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002294
Douglas Gregorca4686d2011-01-04 23:35:54 +00002295 TemplateParameterList *TemplateParams
2296 = ClassTemplate->getTemplateParameters();
2297 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002298 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002299 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002300 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002301 Info.FirstArg = TemplateArgs[I];
2302 Info.SecondArg = InstArg;
2303 return Sema::TDK_NonDeducedMismatch;
2304 }
2305 }
2306
2307 if (Trap.hasErrorOccurred())
2308 return Sema::TDK_SubstitutionFailure;
2309
2310 return Sema::TDK_Success;
2311}
2312
Douglas Gregor170bc422009-06-12 22:31:52 +00002313/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002314/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002315/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002316Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002317Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002318 const TemplateArgumentList &TemplateArgs,
2319 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002320 if (Partial->isInvalidDecl())
2321 return TDK_Invalid;
2322
Douglas Gregor170bc422009-06-12 22:31:52 +00002323 // C++ [temp.class.spec.match]p2:
2324 // A partial specialization matches a given actual template
2325 // argument list if the template arguments of the partial
2326 // specialization can be deduced from the actual template argument
2327 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002328
2329 // Unevaluated SFINAE context.
2330 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002331 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002332
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002333 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002334 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002335 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002336 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002337 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002338 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002339 TemplateArgs, Info, Deduced))
2340 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002341
Richard Smith80934652012-07-16 01:09:10 +00002342 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002343 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2344 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002345 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002346 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002347
Douglas Gregore1416332009-06-14 08:02:22 +00002348 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002349 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002350
2351 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
Douglas Gregor684268d2010-04-29 06:21:43 +00002352 Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002353}
Douglas Gregor91772d12009-06-13 00:26:55 +00002354
Larisse Voufo39a1e502013-08-06 01:03:05 +00002355/// Complete template argument deduction for a variable template partial
2356/// specialization.
Larisse Voufo30616382013-08-23 22:21:36 +00002357/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2358/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2359/// VarTemplate(Partial)SpecializationDecl with a new data
2360/// structure Template(Partial)SpecializationDecl, and
2361/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002362static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2363 Sema &S, VarTemplatePartialSpecializationDecl *Partial,
2364 const TemplateArgumentList &TemplateArgs,
2365 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2366 TemplateDeductionInfo &Info) {
2367 // Unevaluated SFINAE context.
2368 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2369 Sema::SFINAETrap Trap(S);
2370
2371 // C++ [temp.deduct.type]p2:
2372 // [...] or if any template argument remains neither deduced nor
2373 // explicitly specified, template argument deduction fails.
2374 SmallVector<TemplateArgument, 4> Builder;
2375 TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2376 for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2377 NamedDecl *Param = PartialParams->getParam(I);
2378 if (Deduced[I].isNull()) {
2379 Info.Param = makeTemplateParameter(Param);
2380 return Sema::TDK_Incomplete;
2381 }
2382
2383 // We have deduced this argument, so it still needs to be
2384 // checked and converted.
Richard Smith37acb792016-02-03 20:15:01 +00002385 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial,
2386 Info, false, Builder)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002387 Info.Param = makeTemplateParameter(Param);
2388 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002389 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Larisse Voufo39a1e502013-08-06 01:03:05 +00002390 return Sema::TDK_SubstitutionFailure;
2391 }
2392 }
2393
2394 // Form the template argument list from the deduced template arguments.
2395 TemplateArgumentList *DeducedArgumentList = TemplateArgumentList::CreateCopy(
David Majnemer8b622692016-07-03 21:17:51 +00002396 S.Context, Builder);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002397
2398 Info.reset(DeducedArgumentList);
2399
2400 // Substitute the deduced template arguments into the template
2401 // arguments of the class template partial specialization, and
2402 // verify that the instantiated template arguments are both valid
2403 // and are equivalent to the template arguments originally provided
2404 // to the class template.
2405 LocalInstantiationScope InstScope(S);
2406 VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002407 const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2408 = Partial->getTemplateArgsAsWritten();
2409 const TemplateArgumentLoc *PartialTemplateArgs
2410 = PartialTemplArgInfo->getTemplateArgs();
Larisse Voufo39a1e502013-08-06 01:03:05 +00002411
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002412 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2413 PartialTemplArgInfo->RAngleLoc);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002414
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002415 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002416 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2417 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2418 if (ParamIdx >= Partial->getTemplateParameters()->size())
2419 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2420
2421 Decl *Param = const_cast<NamedDecl *>(
2422 Partial->getTemplateParameters()->getParam(ParamIdx));
2423 Info.Param = makeTemplateParameter(Param);
2424 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2425 return Sema::TDK_SubstitutionFailure;
2426 }
2427 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2428 if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2429 false, ConvertedInstArgs))
2430 return Sema::TDK_SubstitutionFailure;
2431
2432 TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2433 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2434 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2435 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2436 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2437 Info.FirstArg = TemplateArgs[I];
2438 Info.SecondArg = InstArg;
2439 return Sema::TDK_NonDeducedMismatch;
2440 }
2441 }
2442
2443 if (Trap.hasErrorOccurred())
2444 return Sema::TDK_SubstitutionFailure;
2445
2446 return Sema::TDK_Success;
2447}
2448
2449/// \brief Perform template argument deduction to determine whether
2450/// the given template arguments match the given variable template
2451/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo30616382013-08-23 22:21:36 +00002452/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2453/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2454/// VarTemplate(Partial)SpecializationDecl with a new data
2455/// structure Template(Partial)SpecializationDecl, and
2456/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00002457Sema::TemplateDeductionResult
2458Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2459 const TemplateArgumentList &TemplateArgs,
2460 TemplateDeductionInfo &Info) {
2461 if (Partial->isInvalidDecl())
2462 return TDK_Invalid;
2463
2464 // C++ [temp.class.spec.match]p2:
2465 // A partial specialization matches a given actual template
2466 // argument list if the template arguments of the partial
2467 // specialization can be deduced from the actual template argument
2468 // list (14.8.2).
2469
2470 // Unevaluated SFINAE context.
2471 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2472 SFINAETrap Trap(*this);
2473
2474 SmallVector<DeducedTemplateArgument, 4> Deduced;
2475 Deduced.resize(Partial->getTemplateParameters()->size());
2476 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2477 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2478 TemplateArgs, Info, Deduced))
2479 return Result;
2480
2481 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002482 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2483 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002484 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002485 return TDK_InstantiationDepth;
2486
2487 if (Trap.hasErrorOccurred())
2488 return Sema::TDK_SubstitutionFailure;
2489
2490 return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2491 Deduced, Info);
2492}
2493
Douglas Gregorfc516c92009-06-26 23:27:24 +00002494/// \brief Determine whether the given type T is a simple-template-id type.
2495static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002496 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002497 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002498 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002499
Douglas Gregorfc516c92009-06-26 23:27:24 +00002500 return false;
2501}
Douglas Gregor9b146582009-07-08 20:55:45 +00002502
2503/// \brief Substitute the explicitly-provided template arguments into the
2504/// given function template according to C++ [temp.arg.explicit].
2505///
2506/// \param FunctionTemplate the function template into which the explicit
2507/// template arguments will be substituted.
2508///
James Dennett634962f2012-06-14 21:40:34 +00002509/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002510/// arguments.
2511///
Mike Stump11289f42009-09-09 15:08:12 +00002512/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002513/// with the converted and checked explicit template arguments.
2514///
Mike Stump11289f42009-09-09 15:08:12 +00002515/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002516/// parameters.
2517///
2518/// \param FunctionType if non-NULL, the result type of the function template
2519/// will also be instantiated and the pointed-to value will be updated with
2520/// the instantiated function type.
2521///
2522/// \param Info if substitution fails for any reason, this object will be
2523/// populated with more information about the failure.
2524///
2525/// \returns TDK_Success if substitution was successful, or some failure
2526/// condition.
2527Sema::TemplateDeductionResult
2528Sema::SubstituteExplicitTemplateArguments(
2529 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002530 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002531 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2532 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002533 QualType *FunctionType,
2534 TemplateDeductionInfo &Info) {
2535 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2536 TemplateParameterList *TemplateParams
2537 = FunctionTemplate->getTemplateParameters();
2538
John McCall6b51f282009-11-23 01:53:49 +00002539 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002540 // No arguments to substitute; just copy over the parameter types and
2541 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002542 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002543 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002544
Douglas Gregor9b146582009-07-08 20:55:45 +00002545 if (FunctionType)
2546 *FunctionType = Function->getType();
2547 return TDK_Success;
2548 }
Mike Stump11289f42009-09-09 15:08:12 +00002549
Eli Friedman77dcc722012-02-08 03:07:05 +00002550 // Unevaluated SFINAE context.
2551 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002552 SFINAETrap Trap(*this);
2553
Douglas Gregor9b146582009-07-08 20:55:45 +00002554 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002555 // Template arguments that are present shall be specified in the
2556 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002557 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002558 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002559 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002560
2561 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002562 // explicitly-specified template arguments against this function template,
2563 // and then substitute them into the function parameter types.
Richard Smith80934652012-07-16 01:09:10 +00002564 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002565 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2566 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002567 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2568 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002569 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002570 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002571
Douglas Gregor9b146582009-07-08 20:55:45 +00002572 if (CheckTemplateArgumentList(FunctionTemplate,
Douglas Gregor9b146582009-07-08 20:55:45 +00002573 SourceLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002574 ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00002575 true,
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002576 Builder) || Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002577 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002578 if (Index >= TemplateParams->size())
2579 Index = TemplateParams->size() - 1;
2580 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002581 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002582 }
Mike Stump11289f42009-09-09 15:08:12 +00002583
Douglas Gregor9b146582009-07-08 20:55:45 +00002584 // Form the template argument list from the explicitly-specified
2585 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002586 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002587 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002588 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002589
John McCall036855a2010-10-12 19:40:14 +00002590 // Template argument deduction and the final substitution should be
2591 // done in the context of the templated declaration. Explicit
2592 // argument substitution, on the other hand, needs to happen in the
2593 // calling context.
2594 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2595
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002596 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002597 // note that the template argument pack is partially substituted and record
2598 // the explicit template arguments. They'll be used as part of deduction
2599 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002600 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2601 const TemplateArgument &Arg = Builder[I];
2602 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002603 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002604 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002605 Arg.pack_begin(),
2606 Arg.pack_size());
2607 break;
2608 }
2609 }
2610
Richard Smith5e580292012-02-10 09:58:53 +00002611 const FunctionProtoType *Proto
2612 = Function->getType()->getAs<FunctionProtoType>();
2613 assert(Proto && "Function template does not have a prototype?");
2614
Richard Smith70b13042015-01-09 01:19:56 +00002615 // Isolate our substituted parameters from our caller.
2616 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2617
John McCallc8e321d2016-03-01 02:09:25 +00002618 ExtParameterInfoBuilder ExtParamInfos;
2619
Douglas Gregor9b146582009-07-08 20:55:45 +00002620 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002621 // explicitly-specified template arguments. If the function has a trailing
2622 // return type, substitute it after the arguments to ensure we substitute
2623 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002624 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002625 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002626 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002627 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002628 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002629 return TDK_SubstitutionFailure;
2630 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002631
Richard Smith5e580292012-02-10 09:58:53 +00002632 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002633 QualType ResultType;
2634 {
2635 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002636 // If a declaration declares a member function or member function
2637 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002638 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002639 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002640 // declarator.
2641 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002642 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002643 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2644 ThisContext = Method->getParent();
2645 ThisTypeQuals = Method->getTypeQualifiers();
2646 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002647
Douglas Gregor3024f072012-04-16 07:05:22 +00002648 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002649 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002650
2651 ResultType =
2652 SubstType(Proto->getReturnType(),
2653 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2654 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002655 if (ResultType.isNull() || Trap.hasErrorOccurred())
2656 return TDK_SubstitutionFailure;
2657 }
John McCallc8e321d2016-03-01 02:09:25 +00002658
Richard Smith5e580292012-02-10 09:58:53 +00002659 // Instantiate the types of each of the function parameters given the
2660 // explicitly-specified template arguments if we didn't do so earlier.
2661 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002662 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002663 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002664 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002665 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002666 return TDK_SubstitutionFailure;
2667
Douglas Gregor9b146582009-07-08 20:55:45 +00002668 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002669 auto EPI = Proto->getExtProtoInfo();
2670 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002671 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002672 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002673 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002674 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002675 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2676 return TDK_SubstitutionFailure;
2677 }
Mike Stump11289f42009-09-09 15:08:12 +00002678
Douglas Gregor9b146582009-07-08 20:55:45 +00002679 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002680 // Trailing template arguments that can be deduced (14.8.2) may be
2681 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002682 // template arguments can be deduced, they may all be omitted; in this
2683 // case, the empty template argument list <> itself may also be omitted.
2684 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002685 // Take all of the explicitly-specified arguments and put them into
2686 // the set of deduced template arguments. Explicitly-specified
2687 // parameter packs, however, will be set to NULL since the deduction
2688 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002689 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002690 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2691 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2692 if (Arg.getKind() == TemplateArgument::Pack)
2693 Deduced.push_back(DeducedTemplateArgument());
2694 else
2695 Deduced.push_back(Arg);
2696 }
Mike Stump11289f42009-09-09 15:08:12 +00002697
Douglas Gregor9b146582009-07-08 20:55:45 +00002698 return TDK_Success;
2699}
2700
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002701/// \brief Check whether the deduced argument type for a call to a function
2702/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002703static bool
2704CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002705 QualType DeducedA) {
2706 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002707
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002708 QualType A = OriginalArg.OriginalArgType;
2709 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002710
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002711 // Check for type equality (top-level cv-qualifiers are ignored).
2712 if (Context.hasSameUnqualifiedType(A, DeducedA))
2713 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002714
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002715 // Strip off references on the argument types; they aren't needed for
2716 // the following checks.
2717 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2718 DeducedA = DeducedARef->getPointeeType();
2719 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2720 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002721
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002722 // C++ [temp.deduct.call]p4:
2723 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002724 // - If the original P is a reference type, the deduced A (i.e., the
2725 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002726 // the transformed A.
2727 if (const ReferenceType *OriginalParamRef
2728 = OriginalParamType->getAs<ReferenceType>()) {
2729 // We don't want to keep the reference around any more.
2730 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002731
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002732 Qualifiers AQuals = A.getQualifiers();
2733 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002734
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002735 // Under Objective-C++ ARC, the deduced type may have implicitly
2736 // been given strong or (when dealing with a const reference)
2737 // unsafe_unretained lifetime. If so, update the original
2738 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002739 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002740 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2741 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2742 (DeducedAQuals.hasConst() &&
2743 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2744 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002745 }
2746
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002747 if (AQuals == DeducedAQuals) {
2748 // Qualifiers match; there's nothing to do.
2749 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002750 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002751 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002752 // Qualifiers are compatible, so have the argument type adopt the
2753 // deduced argument type's qualifiers as if we had performed the
2754 // qualification conversion.
2755 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2756 }
2757 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002758
2759 // - The transformed A can be another pointer or pointer to member
2760 // type that can be converted to the deduced A via a qualification
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002761 // conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002762 //
2763 // Also allow conversions which merely strip [[noreturn]] from function types
2764 // (recursively) as an extension.
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002765 // FIXME: Currently, this doesn't play nicely with qualification conversions.
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002766 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002767 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002768 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002769 (S.IsQualificationConversion(A, DeducedA, false,
2770 ObjCLifetimeConversion) ||
2771 S.IsNoReturnConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002772 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002773
2774
2775 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002776 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002777 // [...] Likewise, if P is a pointer to a class of the form
2778 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002779 // derived class pointed to by the deduced A.
2780 if (const PointerType *OriginalParamPtr
2781 = OriginalParamType->getAs<PointerType>()) {
2782 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2783 if (const PointerType *APtr = A->getAs<PointerType>()) {
2784 if (A->getPointeeType()->isRecordType()) {
2785 OriginalParamType = OriginalParamPtr->getPointeeType();
2786 DeducedA = DeducedAPtr->getPointeeType();
2787 A = APtr->getPointeeType();
2788 }
2789 }
2790 }
2791 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002792
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002793 if (Context.hasSameUnqualifiedType(A, DeducedA))
2794 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002795
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002796 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002797 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002798 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002799
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002800 return true;
2801}
2802
Mike Stump11289f42009-09-09 15:08:12 +00002803/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002804/// checking the deduced template arguments for completeness and forming
2805/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002806///
2807/// \param OriginalCallArgs If non-NULL, the original call arguments against
2808/// which the deduced argument types should be compared.
Mike Stump11289f42009-09-09 15:08:12 +00002809Sema::TemplateDeductionResult
Douglas Gregor9b146582009-07-08 20:55:45 +00002810Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002811 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002812 unsigned NumExplicitlySpecified,
Douglas Gregor9b146582009-07-08 20:55:45 +00002813 FunctionDecl *&Specialization,
Douglas Gregore65aacb2011-06-16 16:50:48 +00002814 TemplateDeductionInfo &Info,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002815 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2816 bool PartialOverloading) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002817 TemplateParameterList *TemplateParams
2818 = FunctionTemplate->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00002819
Eli Friedman77dcc722012-02-08 03:07:05 +00002820 // Unevaluated SFINAE context.
2821 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002822 SFINAETrap Trap(*this);
2823
Douglas Gregor9b146582009-07-08 20:55:45 +00002824 // Enter a new template instantiation context while we instantiate the
2825 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002826 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002827 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2828 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002829 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2830 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002831 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002832 return TDK_InstantiationDepth;
2833
John McCalle23b8712010-04-29 01:18:58 +00002834 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002835
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002836 // C++ [temp.deduct.type]p2:
2837 // [...] or if any template argument remains neither deduced nor
2838 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002839 SmallVector<TemplateArgument, 4> Builder;
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002840 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2841 NamedDecl *Param = TemplateParams->getParam(I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002842
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002843 if (!Deduced[I].isNull()) {
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002844 if (I < NumExplicitlySpecified) {
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002845 // We have already fully type-checked and converted this
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002846 // argument, because it was explicitly-specified. Just record the
Douglas Gregor6e9cf632010-10-12 18:51:08 +00002847 // presence of this argument.
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002848 Builder.push_back(Deduced[I]);
Faisal Vali3628cb92014-06-01 16:11:54 +00002849 // We may have had explicitly-specified template arguments for a
2850 // template parameter pack (that may or may not have been extended
2851 // via additional deduced arguments).
2852 if (Param->isParameterPack() && CurrentInstantiationScope) {
2853 if (CurrentInstantiationScope->getPartiallySubstitutedPack() ==
2854 Param) {
2855 // Forget the partially-substituted pack; its substitution is now
2856 // complete.
2857 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2858 }
2859 }
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002860 continue;
2861 }
Richard Smith37acb792016-02-03 20:15:01 +00002862
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002863 // We have deduced this argument, so it still needs to be
2864 // checked and converted.
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002865 if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
Richard Smith37acb792016-02-03 20:15:01 +00002866 FunctionTemplate, Info,
Douglas Gregorca4686d2011-01-04 23:35:54 +00002867 true, Builder)) {
Douglas Gregoraaa6a902011-01-04 22:13:36 +00002868 Info.Param = makeTemplateParameter(Param);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002869 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002870 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002871 return TDK_SubstitutionFailure;
2872 }
2873
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002874 continue;
2875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002876
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002877 // C++0x [temp.arg.explicit]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002878 // A trailing template parameter pack (14.5.3) not otherwise deduced will
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002879 // be deduced to an empty sequence of template arguments.
2880 // FIXME: Where did the word "trailing" come from?
2881 if (Param->isTemplateParameterPack()) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002882 // We may have had explicitly-specified template arguments for this
2883 // template parameter pack. If so, our empty deduction extends the
2884 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2885 const TemplateArgument *ExplicitArgs;
2886 unsigned NumExplicitArgs;
Richard Smith802c4b72012-08-23 06:16:52 +00002887 if (CurrentInstantiationScope &&
2888 CurrentInstantiationScope->getPartiallySubstitutedPack(&ExplicitArgs,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002889 &NumExplicitArgs)
Douglas Gregorcaddba92013-01-18 22:27:09 +00002890 == Param) {
Benjamin Kramercce63472015-08-05 09:40:22 +00002891 Builder.push_back(TemplateArgument(
2892 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002893
Richard Smithdf18ee92016-02-03 20:40:30 +00002894 // Forget the partially-substituted pack; its substitution is now
Douglas Gregorcaddba92013-01-18 22:27:09 +00002895 // complete.
2896 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2897 } else {
Richard Smithdf18ee92016-02-03 20:40:30 +00002898 // Go through the motions of checking the empty argument pack against
2899 // the parameter pack.
2900 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2901 if (ConvertDeducedTemplateArgument(*this, Param, DeducedPack,
2902 FunctionTemplate, Info, true,
2903 Builder)) {
2904 Info.Param = makeTemplateParameter(Param);
2905 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002906 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
Richard Smithdf18ee92016-02-03 20:40:30 +00002907 return TDK_SubstitutionFailure;
2908 }
Douglas Gregorcaddba92013-01-18 22:27:09 +00002909 }
Douglas Gregorca4d91d2010-12-23 01:52:01 +00002910 continue;
2911 }
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002912
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913 // Substitute into the default template argument, if available.
Richard Smithc87b9382013-07-04 01:01:24 +00002914 bool HasDefaultArg = false;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002915 TemplateArgumentLoc DefArg
2916 = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2917 FunctionTemplate->getLocation(),
2918 FunctionTemplate->getSourceRange().getEnd(),
2919 Param,
Richard Smithc87b9382013-07-04 01:01:24 +00002920 Builder, HasDefaultArg);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002921
2922 // If there was no default argument, deduction is incomplete.
2923 if (DefArg.getArgument().isNull()) {
2924 Info.Param = makeTemplateParameter(
2925 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
David Majnemer8b622692016-07-03 21:17:51 +00002926 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002927 if (PartialOverloading) break;
2928
Richard Smithc87b9382013-07-04 01:01:24 +00002929 return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002930 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002931
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002932 // Check whether we can actually use the default argument.
2933 if (CheckTemplateArgument(Param, DefArg,
2934 FunctionTemplate,
2935 FunctionTemplate->getLocation(),
2936 FunctionTemplate->getSourceRange().getEnd(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002937 0, Builder,
Douglas Gregor2f157c92011-06-03 02:59:40 +00002938 CTAK_Specified)) {
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002939 Info.Param = makeTemplateParameter(
2940 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002941 // FIXME: These template arguments are temporary. Free them!
David Majnemer8b622692016-07-03 21:17:51 +00002942 Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002943 return TDK_SubstitutionFailure;
2944 }
2945
2946 // If we get here, we successfully used the default template argument.
2947 }
2948
2949 // Form the template argument list from the deduced template arguments.
2950 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002951 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002952 Info.reset(DeducedArgumentList);
2953
Mike Stump11289f42009-09-09 15:08:12 +00002954 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002955 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002956 DeclContext *Owner = FunctionTemplate->getDeclContext();
2957 if (FunctionTemplate->getFriendObjectKind())
2958 Owner = FunctionTemplate->getLexicalDeclContext();
Douglas Gregor9b146582009-07-08 20:55:45 +00002959 Specialization = cast_or_null<FunctionDecl>(
Douglas Gregor16142372010-04-28 04:52:24 +00002960 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
Douglas Gregor39cacdb2009-08-28 20:50:45 +00002961 MultiLevelTemplateArgumentList(*DeducedArgumentList)));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002962 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002963 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002964
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002965 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002966 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002967
Mike Stump11289f42009-09-09 15:08:12 +00002968 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002969 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00002970 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2971 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00002972 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00002973
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002974 // There may have been an error that did not prevent us from constructing a
2975 // declaration. Mark the declaration invalid and return with a substitution
2976 // failure.
2977 if (Trap.hasErrorOccurred()) {
2978 Specialization->setInvalidDecl(true);
2979 return TDK_SubstitutionFailure;
2980 }
2981
Douglas Gregore65aacb2011-06-16 16:50:48 +00002982 if (OriginalCallArgs) {
2983 // C++ [temp.deduct.call]p4:
2984 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00002985 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00002986 // is transformed as described above). [...]
2987 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2988 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Douglas Gregore65aacb2011-06-16 16:50:48 +00002989 unsigned ParamIdx = OriginalArg.ArgIdx;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002990
Douglas Gregore65aacb2011-06-16 16:50:48 +00002991 if (ParamIdx >= Specialization->getNumParams())
2992 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002993
Douglas Gregore65aacb2011-06-16 16:50:48 +00002994 QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
Richard Smith9b534542015-12-31 02:02:54 +00002995 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2996 Info.FirstArg = TemplateArgument(DeducedA);
2997 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2998 Info.CallArgIndex = OriginalArg.ArgIdx;
2999 return TDK_DeducedMismatch;
3000 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003001 }
3002 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003003
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003004 // If we suppressed any diagnostics while performing template argument
3005 // deduction, and if we haven't already instantiated this declaration,
3006 // keep track of these diagnostics. They'll be emitted if this specialization
3007 // is actually used.
3008 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003009 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003010 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3011 if (Pos == SuppressedDiagnostics.end())
3012 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3013 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003014 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003015
Mike Stump11289f42009-09-09 15:08:12 +00003016 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003017}
3018
John McCall8d08b9b2010-08-27 09:08:28 +00003019/// Gets the type of a function for template-argument-deducton
3020/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003021static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003022 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003023 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003024 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003025 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003026 return QualType();
3027
John McCallc1f69982010-02-02 02:21:27 +00003028 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003029 if (Method->isInstance()) {
3030 // An instance method that's referenced in a form that doesn't
3031 // look like a member pointer is just invalid.
3032 if (!R.HasFormOfMemberPointer) return QualType();
3033
Richard Smith2a7d4812013-05-04 07:00:32 +00003034 return S.Context.getMemberPointerType(Fn->getType(),
3035 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003036 }
3037
3038 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003039 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003040}
3041
3042/// Apply the deduction rules for overload sets.
3043///
3044/// \return the null type if this argument should be treated as an
3045/// undeduced context
3046static QualType
3047ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003048 Expr *Arg, QualType ParamType,
3049 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050
John McCall8d08b9b2010-08-27 09:08:28 +00003051 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003052
John McCall8d08b9b2010-08-27 09:08:28 +00003053 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003054
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003055 // C++0x [temp.deduct.call]p4
3056 unsigned TDF = 0;
3057 if (ParamWasReference)
3058 TDF |= TDF_ParamWithReferenceType;
3059 if (R.IsAddressOfOperand)
3060 TDF |= TDF_IgnoreQualifiers;
3061
John McCallc1f69982010-02-02 02:21:27 +00003062 // C++0x [temp.deduct.call]p6:
3063 // When P is a function type, pointer to function type, or pointer
3064 // to member function type:
3065
3066 if (!ParamType->isFunctionType() &&
3067 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003068 !ParamType->isMemberFunctionPointerType()) {
3069 if (Ovl->hasExplicitTemplateArgs()) {
3070 // But we can still look for an explicit specialization.
3071 if (FunctionDecl *ExplicitSpec
3072 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003073 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003074 }
John McCallc1f69982010-02-02 02:21:27 +00003075
George Burgess IVcc2f3552016-03-19 21:51:45 +00003076 DeclAccessPair DAP;
3077 if (FunctionDecl *Viable =
3078 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3079 return GetTypeOfFunction(S, R, Viable);
3080
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003081 return QualType();
3082 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003083
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003084 // Gather the explicit template arguments, if any.
3085 TemplateArgumentListInfo ExplicitTemplateArgs;
3086 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003087 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003088 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003089 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3090 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003091 NamedDecl *D = (*I)->getUnderlyingDecl();
3092
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003093 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3094 // - If the argument is an overload set containing one or more
3095 // function templates, the parameter is treated as a
3096 // non-deduced context.
3097 if (!Ovl->hasExplicitTemplateArgs())
3098 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003099
3100 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003101 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003102 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003103 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3104 Specialization, Info))
3105 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003106
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003107 D = Specialization;
3108 }
John McCallc1f69982010-02-02 02:21:27 +00003109
3110 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003111 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003112 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003113
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003114 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003115 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003116 ArgType->isFunctionType())
3117 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003118
John McCallc1f69982010-02-02 02:21:27 +00003119 // - If the argument is an overload set (not containing function
3120 // templates), trial argument deduction is attempted using each
3121 // of the members of the set. If deduction succeeds for only one
3122 // of the overload set members, that member is used as the
3123 // argument value for the deduction. If deduction succeeds for
3124 // more than one member of the overload set the parameter is
3125 // treated as a non-deduced context.
3126
3127 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3128 // Type deduction is done independently for each P/A pair, and
3129 // the deduced template argument values are then combined.
3130 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003131 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003132 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003133 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003134 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003135 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3136 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003137 if (Result) continue;
3138 if (!Match.isNull()) return QualType();
3139 Match = ArgType;
3140 }
3141
3142 return Match;
3143}
3144
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003145/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003146/// described in C++ [temp.deduct.call].
3147///
3148/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003149/// argument deduction based on this P/A pair because the argument is an
3150/// overloaded function set that could not be resolved.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003151static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3152 TemplateParameterList *TemplateParams,
3153 QualType &ParamType,
3154 QualType &ArgType,
3155 Expr *Arg,
3156 unsigned &TDF) {
3157 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003158 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003159 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003160 if (ParamType.hasQualifiers())
3161 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003162
3163 // [...] If P is a reference type, the type referred to by P is
3164 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003165 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003166 if (ParamRefType)
3167 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003168
Nathan Sidwell96090022015-01-16 15:20:14 +00003169 // Overload sets usually make this parameter an undeduced context,
3170 // but there are sometimes special circumstances. Typically
3171 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003172 if (ArgType == S.Context.OverloadTy) {
3173 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3174 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003175 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003176 if (ArgType.isNull())
3177 return true;
3178 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003179
Douglas Gregor7825bf32011-01-06 22:09:01 +00003180 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003181 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003182 if (ArgType->isIncompleteArrayType()) {
3183 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003184 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003185 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003186
Douglas Gregor7825bf32011-01-06 22:09:01 +00003187 // C++0x [temp.deduct.call]p3:
Nathan Sidwell96090022015-01-16 15:20:14 +00003188 // If P is an rvalue reference to a cv-unqualified template
3189 // parameter and the argument is an lvalue, the type "lvalue
3190 // reference to A" is used in place of A for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003191 if (ParamRefType->isRValueReferenceType() &&
Nathan Sidwell96090022015-01-16 15:20:14 +00003192 !ParamType.getQualifiers() &&
3193 isa<TemplateTypeParmType>(ParamType) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003194 Arg->isLValue())
3195 ArgType = S.Context.getLValueReferenceType(ArgType);
3196 } else {
3197 // C++ [temp.deduct.call]p2:
3198 // If P is not a reference type:
3199 // - If A is an array type, the pointer type produced by the
3200 // array-to-pointer standard conversion (4.2) is used in place of
3201 // A for type deduction; otherwise,
3202 if (ArgType->isArrayType())
3203 ArgType = S.Context.getArrayDecayedType(ArgType);
3204 // - If A is a function type, the pointer type produced by the
3205 // function-to-pointer standard conversion (4.3) is used in place
3206 // of A for type deduction; otherwise,
3207 else if (ArgType->isFunctionType())
3208 ArgType = S.Context.getPointerType(ArgType);
3209 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003210 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003211 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003212 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003213 }
3214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003215
Douglas Gregor7825bf32011-01-06 22:09:01 +00003216 // C++0x [temp.deduct.call]p4:
3217 // In general, the deduction process attempts to find template argument
3218 // values that will make the deduced A identical to A (after the type A
3219 // is transformed as described above). [...]
3220 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003221
Douglas Gregor7825bf32011-01-06 22:09:01 +00003222 // - If the original P is a reference type, the deduced A (i.e., the
3223 // type referred to by the reference) can be more cv-qualified than
3224 // the transformed A.
3225 if (ParamRefType)
3226 TDF |= TDF_ParamWithReferenceType;
3227 // - The transformed A can be another pointer or pointer to member
3228 // type that can be converted to the deduced A via a qualification
3229 // conversion (4.4).
3230 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3231 ArgType->isObjCObjectPointerType())
3232 TDF |= TDF_IgnoreQualifiers;
3233 // - If P is a class and P has the form simple-template-id, then the
3234 // transformed A can be a derived class of the deduced A. Likewise,
3235 // if P is a pointer to a class of the form simple-template-id, the
3236 // transformed A can be a pointer to a derived class pointed to by
3237 // the deduced A.
3238 if (isSimpleTemplateIdType(ParamType) ||
3239 (isa<PointerType>(ParamType) &&
3240 isSimpleTemplateIdType(
3241 ParamType->getAs<PointerType>()->getPointeeType())))
3242 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243
Douglas Gregor7825bf32011-01-06 22:09:01 +00003244 return false;
3245}
3246
Nico Weberc153d242014-07-28 00:02:09 +00003247static bool
3248hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3249 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003250
Hubert Tong3280b332015-06-25 00:25:49 +00003251static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(
3252 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3253 Expr *Arg, TemplateDeductionInfo &Info,
3254 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3255
3256/// \brief Attempt template argument deduction from an initializer list
3257/// deemed to be an argument in a function call.
3258static bool
3259DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams,
3260 QualType AdjustedParamType, InitListExpr *ILE,
3261 TemplateDeductionInfo &Info,
3262 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3263 unsigned TDF, Sema::TemplateDeductionResult &Result) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003264
3265 // [temp.deduct.call] p1 (post CWG-1591)
3266 // If removing references and cv-qualifiers from P gives
3267 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3268 // non-empty initializer list (8.5.4), then deduction is performed instead for
3269 // each element of the initializer list, taking P0 as a function template
3270 // parameter type and the initializer element as its argument, and in the
3271 // P0[N] case, if N is a non-type template parameter, N is deduced from the
3272 // length of the initializer list. Otherwise, an initializer list argument
3273 // causes the parameter to be considered a non-deduced context
3274
3275 const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3276
3277 const bool IsDependentSizedArray =
3278 !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3279
Faisal Validd76cc12015-12-10 12:29:11 +00003280 QualType ElTy; // The element type of the std::initializer_list or the array.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003281
3282 const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3283 S.isStdInitializerList(AdjustedParamType, &ElTy);
3284
3285 if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
Hubert Tong3280b332015-06-25 00:25:49 +00003286 return false;
3287
3288 Result = Sema::TDK_Success;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003289 // If we are not deducing against the 'T' in a std::initializer_list<T> then
3290 // deduce against the 'T' in T[N].
3291 if (ElTy.isNull()) {
3292 assert(!IsSTDList);
3293 ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
Hubert Tong3280b332015-06-25 00:25:49 +00003294 }
Faisal Valif6dfdb32015-12-10 05:36:39 +00003295 // Deduction only needs to be done for dependent types.
3296 if (ElTy->isDependentType()) {
3297 for (Expr *E : ILE->inits()) {
Craig Topper08529532015-12-10 08:49:55 +00003298 if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3299 E, Info, Deduced, TDF)))
Faisal Valif6dfdb32015-12-10 05:36:39 +00003300 return true;
3301 }
3302 }
3303 if (IsDependentSizedArray) {
3304 const DependentSizedArrayType *ArrTy =
3305 S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3306 // Determine the array bound is something we can deduce.
3307 if (NonTypeTemplateParmDecl *NTTP =
3308 getDeducedParameterFromExpr(ArrTy->getSizeExpr())) {
3309 // We can perform template argument deduction for the given non-type
3310 // template parameter.
3311 assert(NTTP->getDepth() == 0 &&
3312 "Cannot deduce non-type template argument at depth > 0");
3313 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3314 ILE->getNumInits());
Hubert Tong3280b332015-06-25 00:25:49 +00003315
Faisal Valif6dfdb32015-12-10 05:36:39 +00003316 Result = DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +00003317 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
Faisal Valif6dfdb32015-12-10 05:36:39 +00003318 /*ArrayBound=*/true, Info, Deduced);
3319 }
3320 }
Hubert Tong3280b332015-06-25 00:25:49 +00003321 return true;
3322}
3323
Sebastian Redl19181662012-03-15 21:40:51 +00003324/// \brief Perform template argument deduction by matching a parameter type
3325/// against a single expression, where the expression is an element of
Richard Smith8c6eeb92013-01-31 04:03:12 +00003326/// an initializer list that was originally matched against a parameter
3327/// of type \c initializer_list\<ParamType\>.
Sebastian Redl19181662012-03-15 21:40:51 +00003328static Sema::TemplateDeductionResult
3329DeduceTemplateArgumentByListElement(Sema &S,
3330 TemplateParameterList *TemplateParams,
3331 QualType ParamType, Expr *Arg,
3332 TemplateDeductionInfo &Info,
3333 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3334 unsigned TDF) {
3335 // Handle the case where an init list contains another init list as the
3336 // element.
3337 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003338 Sema::TemplateDeductionResult Result;
3339 if (!DeduceFromInitializerList(S, TemplateParams,
3340 ParamType.getNonReferenceType(), ILE, Info,
3341 Deduced, TDF, Result))
Sebastian Redl19181662012-03-15 21:40:51 +00003342 return Sema::TDK_Success; // Just ignore this expression.
3343
Hubert Tong3280b332015-06-25 00:25:49 +00003344 return Result;
Sebastian Redl19181662012-03-15 21:40:51 +00003345 }
3346
3347 // For all other cases, just match by type.
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003348 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003349 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
Richard Smith8c6eeb92013-01-31 04:03:12 +00003350 ArgType, Arg, TDF)) {
3351 Info.Expression = Arg;
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003352 return Sema::TDK_FailedOverloadResolution;
Richard Smith8c6eeb92013-01-31 04:03:12 +00003353 }
Sebastian Redl19181662012-03-15 21:40:51 +00003354 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003355 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003356}
3357
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003358/// \brief Perform template argument deduction from a function call
3359/// (C++ [temp.deduct.call]).
3360///
3361/// \param FunctionTemplate the function template for which we are performing
3362/// template argument deduction.
3363///
James Dennett18348b62012-06-22 08:52:37 +00003364/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003365/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003366///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003367/// \param Args the function call arguments
3368///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003369/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003370/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003371/// template argument deduction.
3372///
3373/// \param Info the argument will be updated to provide additional information
3374/// about template argument deduction.
3375///
3376/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003377Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3378 FunctionTemplateDecl *FunctionTemplate,
3379 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003380 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3381 bool PartialOverloading) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003382 if (FunctionTemplate->isInvalidDecl())
3383 return TDK_Invalid;
3384
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003385 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003386 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003387
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003388 // C++ [temp.deduct.call]p1:
3389 // Template argument deduction is done by comparing each function template
3390 // parameter type (call it P) with the type of the corresponding argument
3391 // of the call (call it A) as described below.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003392 unsigned CheckArgs = Args.size();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003393 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003394 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003395 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003396 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003397 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003398 if (Proto->isTemplateVariadic())
3399 /* Do nothing */;
3400 else if (Proto->isVariadic())
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003401 CheckArgs = NumParams;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402 else
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003403 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003404 }
Mike Stump11289f42009-09-09 15:08:12 +00003405
Douglas Gregor89026b52009-06-30 23:57:56 +00003406 // The types of the parameters from which we will perform template argument
3407 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003408 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003409 TemplateParameterList *TemplateParams
3410 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003411 SmallVector<DeducedTemplateArgument, 4> Deduced;
3412 SmallVector<QualType, 4> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003413 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003414 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003415 TemplateDeductionResult Result =
3416 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003417 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003418 Deduced,
3419 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003420 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003421 Info);
3422 if (Result)
3423 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003424
3425 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003426 } else {
3427 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003428 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003429 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3430 }
Mike Stump11289f42009-09-09 15:08:12 +00003431
Douglas Gregor89026b52009-06-30 23:57:56 +00003432 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003433 Deduced.resize(TemplateParams->size());
Douglas Gregor7825bf32011-01-06 22:09:01 +00003434 unsigned ArgIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003435 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003436 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3437 ParamIdx != NumParamTypes; ++ParamIdx) {
Douglas Gregore65aacb2011-06-16 16:50:48 +00003438 QualType OrigParamType = ParamTypes[ParamIdx];
3439 QualType ParamType = OrigParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003440
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003441 const PackExpansionType *ParamExpansion
Douglas Gregor7825bf32011-01-06 22:09:01 +00003442 = dyn_cast<PackExpansionType>(ParamType);
3443 if (!ParamExpansion) {
3444 // Simple case: matching a function parameter to a function argument.
3445 if (ArgIdx >= CheckArgs)
3446 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447
Douglas Gregor7825bf32011-01-06 22:09:01 +00003448 Expr *Arg = Args[ArgIdx++];
3449 QualType ArgType = Arg->getType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003450
Douglas Gregor7825bf32011-01-06 22:09:01 +00003451 unsigned TDF = 0;
3452 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3453 ParamType, ArgType, Arg,
3454 TDF))
3455 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Douglas Gregor0c83c812011-10-09 22:06:46 +00003457 // If we have nothing to deduce, we're done.
3458 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3459 continue;
3460
Sebastian Redl43144e72012-01-17 22:49:58 +00003461 // If the argument is an initializer list ...
3462 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003463 TemplateDeductionResult Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003464 // Removing references was already done.
Hubert Tong3280b332015-06-25 00:25:49 +00003465 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3466 Info, Deduced, TDF, Result))
Sebastian Redl43144e72012-01-17 22:49:58 +00003467 continue;
3468
Hubert Tong3280b332015-06-25 00:25:49 +00003469 if (Result)
3470 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003471 // Don't track the argument type, since an initializer list has none.
3472 continue;
3473 }
3474
Douglas Gregore65aacb2011-06-16 16:50:48 +00003475 // Keep track of the argument type and corresponding parameter index,
3476 // so we can check for compatibility between the deduced A and A.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003477 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
Douglas Gregor0c83c812011-10-09 22:06:46 +00003478 ArgType));
Douglas Gregore65aacb2011-06-16 16:50:48 +00003479
Douglas Gregor7825bf32011-01-06 22:09:01 +00003480 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003481 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3482 ParamType, ArgType,
3483 Info, Deduced, TDF))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003484 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003485
Douglas Gregor7825bf32011-01-06 22:09:01 +00003486 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003487 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488
Douglas Gregor7825bf32011-01-06 22:09:01 +00003489 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490 // For a function parameter pack that occurs at the end of the
3491 // parameter-declaration-list, the type A of each remaining argument of
3492 // the call is compared with the type P of the declarator-id of the
3493 // function parameter pack. Each comparison deduces template arguments
3494 // for subsequent positions in the template parameter packs expanded by
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003495 // the function parameter pack. For a function parameter pack that does
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003496 // not occur at the end of the parameter-declaration-list, the type of
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003497 // the parameter pack is a non-deduced context.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003498 if (ParamIdx + 1 < NumParamTypes)
Douglas Gregor0dd423e2011-01-11 01:52:23 +00003499 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003500
Douglas Gregor7825bf32011-01-06 22:09:01 +00003501 QualType ParamPattern = ParamExpansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00003502 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3503 ParamPattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504
Douglas Gregor7825bf32011-01-06 22:09:01 +00003505 bool HasAnyArguments = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003506 for (; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003507 HasAnyArguments = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003508
Douglas Gregore65aacb2011-06-16 16:50:48 +00003509 QualType OrigParamType = ParamPattern;
3510 ParamType = OrigParamType;
Douglas Gregor7825bf32011-01-06 22:09:01 +00003511 Expr *Arg = Args[ArgIdx];
3512 QualType ArgType = Arg->getType();
Richard Smith0a80d572014-05-29 01:12:14 +00003513
Douglas Gregor7825bf32011-01-06 22:09:01 +00003514 unsigned TDF = 0;
3515 if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3516 ParamType, ArgType, Arg,
3517 TDF)) {
3518 // We can't actually perform any deduction for this argument, so stop
3519 // deduction at this point.
3520 ++ArgIdx;
3521 break;
3522 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003523
Sebastian Redl43144e72012-01-17 22:49:58 +00003524 // As above, initializer lists need special handling.
3525 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
Hubert Tong3280b332015-06-25 00:25:49 +00003526 TemplateDeductionResult Result;
3527 if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3528 Info, Deduced, TDF, Result)) {
Sebastian Redl43144e72012-01-17 22:49:58 +00003529 ++ArgIdx;
3530 break;
3531 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003532
Hubert Tong3280b332015-06-25 00:25:49 +00003533 if (Result)
3534 return Result;
Sebastian Redl43144e72012-01-17 22:49:58 +00003535 } else {
3536
3537 // Keep track of the argument type and corresponding argument index,
3538 // so we can check for compatibility between the deduced A and A.
3539 if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Simon Pilgrim728134c2016-08-12 11:43:57 +00003540 OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
Sebastian Redl43144e72012-01-17 22:49:58 +00003541 ArgType));
3542
3543 if (TemplateDeductionResult Result
3544 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3545 ParamType, ArgType, Info,
3546 Deduced, TDF))
3547 return Result;
3548 }
Mike Stump11289f42009-09-09 15:08:12 +00003549
Richard Smith0a80d572014-05-29 01:12:14 +00003550 PackScope.nextPackElement();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003552
Douglas Gregor7825bf32011-01-06 22:09:01 +00003553 // Build argument packs for each of the parameter packs expanded by this
3554 // pack expansion.
Richard Smith0a80d572014-05-29 01:12:14 +00003555 if (auto Result = PackScope.finish(HasAnyArguments))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003556 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003557
Douglas Gregor7825bf32011-01-06 22:09:01 +00003558 // After we've matching against a parameter pack, we're done.
3559 break;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003560 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003561
Mike Stump11289f42009-09-09 15:08:12 +00003562 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
Nico Weberc153d242014-07-28 00:02:09 +00003563 NumExplicitlySpecified, Specialization,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003564 Info, &OriginalCallArgs,
3565 PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003566}
3567
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003568QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3569 QualType FunctionType) {
3570 if (ArgFunctionType.isNull())
3571 return ArgFunctionType;
3572
3573 const FunctionProtoType *FunctionTypeP =
3574 FunctionType->castAs<FunctionProtoType>();
3575 CallingConv CC = FunctionTypeP->getCallConv();
3576 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3577 const FunctionProtoType *ArgFunctionTypeP =
3578 ArgFunctionType->getAs<FunctionProtoType>();
3579 if (ArgFunctionTypeP->getCallConv() == CC &&
3580 ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3581 return ArgFunctionType;
3582
3583 FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3584 EI = EI.withNoReturn(NoReturn);
3585 ArgFunctionTypeP =
3586 cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3587 return QualType(ArgFunctionTypeP, 0);
3588}
3589
Douglas Gregor9b146582009-07-08 20:55:45 +00003590/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003591/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3592/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003593///
3594/// \param FunctionTemplate the function template for which we are performing
3595/// template argument deduction.
3596///
James Dennett18348b62012-06-22 08:52:37 +00003597/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003598/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003599///
3600/// \param ArgFunctionType the function type that will be used as the
3601/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003602/// function template's function type. This type may be NULL, if there is no
3603/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003604///
3605/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003606/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003607/// template argument deduction.
3608///
3609/// \param Info the argument will be updated to provide additional information
3610/// about template argument deduction.
3611///
3612/// \returns the result of template argument deduction.
3613Sema::TemplateDeductionResult
3614Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003615 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003616 QualType ArgFunctionType,
3617 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003618 TemplateDeductionInfo &Info,
3619 bool InOverloadResolution) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003620 if (FunctionTemplate->isInvalidDecl())
3621 return TDK_Invalid;
3622
Douglas Gregor9b146582009-07-08 20:55:45 +00003623 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3624 TemplateParameterList *TemplateParams
3625 = FunctionTemplate->getTemplateParameters();
3626 QualType FunctionType = Function->getType();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003627 if (!InOverloadResolution)
3628 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
Mike Stump11289f42009-09-09 15:08:12 +00003629
Douglas Gregor9b146582009-07-08 20:55:45 +00003630 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003631 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003632 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003633 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003634 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003635 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003636 if (TemplateDeductionResult Result
3637 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003638 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003639 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003640 &FunctionType, Info))
3641 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003642
3643 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003644 }
3645
Eli Friedman77dcc722012-02-08 03:07:05 +00003646 // Unevaluated SFINAE context.
3647 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003648 SFINAETrap Trap(*this);
3649
John McCallc1f69982010-02-02 02:21:27 +00003650 Deduced.resize(TemplateParams->size());
3651
Richard Smith2a7d4812013-05-04 07:00:32 +00003652 // If the function has a deduced return type, substitute it for a dependent
3653 // type so that we treat it as a non-deduced context in what follows.
Richard Smithc58f38f2013-08-14 20:16:31 +00003654 bool HasDeducedReturnType = false;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003655 if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
Alp Toker314cc812014-01-25 16:55:45 +00003656 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003657 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003658 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003659 }
3660
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003661 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003662 unsigned TDF = TDF_TopLevelParameterTypeList;
3663 if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003664 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003665 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003666 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003667 FunctionType, ArgFunctionType,
3668 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003669 return Result;
3670 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003671
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003672 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003673 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3674 NumExplicitlySpecified,
3675 Specialization, Info))
3676 return Result;
3677
Richard Smith2a7d4812013-05-04 07:00:32 +00003678 // If the function has a deduced return type, deduce it now, so we can check
3679 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003680 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003681 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003682 DeduceReturnType(Specialization, Info.getLocation(), false))
3683 return TDK_MiscellaneousDeductionFailure;
3684
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003685 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003686 // specialization with respect to arguments of compatible pointer to function
3687 // types, template argument deduction fails.
3688 if (!ArgFunctionType.isNull()) {
3689 if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3690 Context.getCanonicalType(Specialization->getType()),
3691 Context.getCanonicalType(ArgFunctionType)))
3692 return TDK_MiscellaneousDeductionFailure;
3693 else if(!InOverloadResolution &&
3694 !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3695 return TDK_MiscellaneousDeductionFailure;
3696 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003697
3698 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003699}
3700
Simon Pilgrim728134c2016-08-12 11:43:57 +00003701/// \brief Given a function declaration (e.g. a generic lambda conversion
3702/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003703/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3704/// to replace 'auto' with and not the actual result type you want
3705/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003706static inline void
3707SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003708 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003709 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003710 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003711 assert(AutoResultType->getContainedAutoType());
3712 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003713 TypeToReplaceAutoWith);
3714 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3715}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003716
Simon Pilgrim728134c2016-08-12 11:43:57 +00003717/// \brief Given a specialized conversion operator of a generic lambda
3718/// create the corresponding specializations of the call operator and
3719/// the static-invoker. If the return type of the call operator is auto,
3720/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003721/// return type of the destination function ptr.
3722
Simon Pilgrim728134c2016-08-12 11:43:57 +00003723static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003724SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3725 CXXConversionDecl *ConversionSpecialized,
3726 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3727 QualType ReturnTypeOfDestFunctionPtr,
3728 TemplateDeductionInfo &TDInfo,
3729 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003730
Faisal Vali2b3a3012013-10-24 23:40:02 +00003731 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003732 assert(LambdaClass && LambdaClass->isGenericLambda());
3733
Faisal Vali2b3a3012013-10-24 23:40:02 +00003734 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003735 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003736 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003737 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003738
3739 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003740 CallOpGeneric->getDescribedFunctionTemplate();
3741
Craig Topperc3ec1492014-05-26 06:22:03 +00003742 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003743 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003744 // generic lambda's call operator.
3745 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003746 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3747 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003748 0, CallOpSpecialized, TDInfo))
3749 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003750
Faisal Vali2b3a3012013-10-24 23:40:02 +00003751 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003752 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3753 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003754 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003755 CallOpSpecialized->getPointOfInstantiation(),
3756 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003757
Faisal Vali2b3a3012013-10-24 23:40:02 +00003758 // Check to see if the return type of the destination ptr-to-function
3759 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003760 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003761 ReturnTypeOfDestFunctionPtr))
3762 return Sema::TDK_NonDeducedMismatch;
3763 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003764 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003765 // specialized our corresponding call operator, we are ready to
3766 // specialize the static invoker with the deduced arguments of our
3767 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003768 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003769 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3770 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3771
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003772#ifndef NDEBUG
3773 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3774#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003775 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003776 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003777 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003778 "If the call operator succeeded so should the invoker!");
3779 // Set the result type to match the corresponding call operator
3780 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003781 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3782 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003783 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003784 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003785 // to substitute into the 'auto' of the invoker and conversion
3786 // function.
3787 // For e.g.
3788 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3789 // We don't want to subst 'int*' into 'auto' to get int**.
3790
Alp Toker314cc812014-01-25 16:55:45 +00003791 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3792 ->getContainedAutoType()
3793 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003794 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3795 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003796 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003797 TypeToReplaceAutoWith, S);
3798 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003799
Faisal Vali2b3a3012013-10-24 23:40:02 +00003800 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003801 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003802 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003803 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003804 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3805 getType().getTypePtr()->castAs<FunctionProtoType>();
3806 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3807 EPI.TypeQuals = 0;
3808 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003809 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003810 return Sema::TDK_Success;
3811}
Douglas Gregor05155d82009-08-21 23:19:43 +00003812/// \brief Deduce template arguments for a templated conversion
3813/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3814/// conversion function template specialization.
3815Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003816Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003817 QualType ToType,
3818 CXXConversionDecl *&Specialization,
3819 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003820 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003821 return TDK_Invalid;
3822
Faisal Vali2b3a3012013-10-24 23:40:02 +00003823 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003824 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3825
Faisal Vali2b3a3012013-10-24 23:40:02 +00003826 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003827
3828 // Canonicalize the types for deduction.
3829 QualType P = Context.getCanonicalType(FromType);
3830 QualType A = Context.getCanonicalType(ToType);
3831
Douglas Gregord99609a2011-03-06 09:03:20 +00003832 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003833 // If P is a reference type, the type referred to by P is used for
3834 // type deduction.
3835 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3836 P = PRef->getPointeeType();
3837
Douglas Gregord99609a2011-03-06 09:03:20 +00003838 // C++0x [temp.deduct.conv]p4:
3839 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003840 // for type deduction.
3841 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003842 A = ARef->getPointeeType().getUnqualifiedType();
3843 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003844 //
Mike Stump11289f42009-09-09 15:08:12 +00003845 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003846 else {
3847 assert(!A->isReferenceType() && "Reference types were handled above");
3848
3849 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003850 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003851 // of P for type deduction; otherwise,
3852 if (P->isArrayType())
3853 P = Context.getArrayDecayedType(P);
3854 // - If P is a function type, the pointer type produced by the
3855 // function-to-pointer standard conversion (4.3) is used in
3856 // place of P for type deduction; otherwise,
3857 else if (P->isFunctionType())
3858 P = Context.getPointerType(P);
3859 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003860 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003861 else
3862 P = P.getUnqualifiedType();
3863
Douglas Gregord99609a2011-03-06 09:03:20 +00003864 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003865 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003866 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003867 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003868 A = A.getUnqualifiedType();
3869 }
3870
Eli Friedman77dcc722012-02-08 03:07:05 +00003871 // Unevaluated SFINAE context.
3872 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003873 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003874
3875 // C++ [temp.deduct.conv]p1:
3876 // Template argument deduction is done by comparing the return
3877 // type of the template conversion function (call it P) with the
3878 // type that is required as the result of the conversion (call it
3879 // A) as described in 14.8.2.4.
3880 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003881 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003882 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003883 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003884
3885 // C++0x [temp.deduct.conv]p4:
3886 // In general, the deduction process attempts to find template
3887 // argument values that will make the deduced A identical to
3888 // A. However, there are two cases that allow a difference:
3889 unsigned TDF = 0;
3890 // - If the original A is a reference type, A can be more
3891 // cv-qualified than the deduced A (i.e., the type referred to
3892 // by the reference)
3893 if (ToType->isReferenceType())
3894 TDF |= TDF_ParamWithReferenceType;
3895 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003896 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003897 // conversion.
3898 //
3899 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3900 // both P and A are pointers or member pointers. In this case, we
3901 // just ignore cv-qualifiers completely).
3902 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003903 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003904 TDF |= TDF_IgnoreQualifiers;
3905 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003906 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3907 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003908 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003909
3910 // Create an Instantiation Scope for finalizing the operator.
3911 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003912 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003913 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003914 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003915 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003916 ConversionSpecialized, Info);
3917 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3918
3919 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003920 // to a ptr-to-function, use the deduced arguments from the conversion
3921 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003922 // e.g., int (*fp)(int) = [](auto a) { return a; };
3923 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003924
Faisal Vali2b3a3012013-10-24 23:40:02 +00003925 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003926 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003927 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003928 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003929 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003930 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003931 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003932 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3933
Simon Pilgrim728134c2016-08-12 11:43:57 +00003934 // Create the corresponding specializations of the call operator and
3935 // the static-invoker; and if the return type is auto,
3936 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003937 // DestFunctionPtrReturnType.
3938 // For instance:
3939 // auto L = [](auto a) { return f(a); };
3940 // int (*fp)(int) = L;
3941 // char (*fp2)(int) = L; <-- Not OK.
3942
3943 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00003944 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003945 Info, *this);
3946 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003947 return Result;
3948}
3949
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003950/// \brief Deduce template arguments for a function template when there is
3951/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3952///
3953/// \param FunctionTemplate the function template for which we are performing
3954/// template argument deduction.
3955///
James Dennett18348b62012-06-22 08:52:37 +00003956/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003957/// arguments.
3958///
3959/// \param Specialization if template argument deduction was successful,
3960/// this will be set to the function template specialization produced by
3961/// template argument deduction.
3962///
3963/// \param Info the argument will be updated to provide additional information
3964/// about template argument deduction.
3965///
3966/// \returns the result of template argument deduction.
3967Sema::TemplateDeductionResult
3968Sema::DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00003969 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003970 FunctionDecl *&Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003971 TemplateDeductionInfo &Info,
3972 bool InOverloadResolution) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003973 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003974 QualType(), Specialization, Info,
3975 InOverloadResolution);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003976}
3977
Richard Smith30482bc2011-02-20 03:19:35 +00003978namespace {
3979 /// Substitute the 'auto' type specifier within a type for a given replacement
3980 /// type.
3981 class SubstituteAutoTransform :
3982 public TreeTransform<SubstituteAutoTransform> {
3983 QualType Replacement;
3984 public:
Nico Weberc153d242014-07-28 00:02:09 +00003985 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3986 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3987 Replacement(Replacement) {}
3988
Richard Smith30482bc2011-02-20 03:19:35 +00003989 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3990 // If we're building the type pattern to deduce against, don't wrap the
3991 // substituted type in an AutoType. Certain template deduction rules
3992 // apply only when a template type parameter appears directly (and not if
3993 // the parameter is found through desugaring). For instance:
3994 // auto &&lref = lvalue;
3995 // must transform into "rvalue reference to T" not "rvalue reference to
3996 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith2a7d4812013-05-04 07:00:32 +00003997 if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
Richard Smith30482bc2011-02-20 03:19:35 +00003998 QualType Result = Replacement;
Richard Smith74aeef52013-04-26 16:15:35 +00003999 TemplateTypeParmTypeLoc NewTL =
4000 TLB.push<TemplateTypeParmTypeLoc>(Result);
Richard Smith30482bc2011-02-20 03:19:35 +00004001 NewTL.setNameLoc(TL.getNameLoc());
4002 return Result;
4003 } else {
Richard Smith27d807c2013-04-30 13:56:41 +00004004 bool Dependent =
4005 !Replacement.isNull() && Replacement->isDependentType();
4006 QualType Result =
4007 SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
Richard Smithe301ba22015-11-11 02:02:15 +00004008 TL.getTypePtr()->getKeyword(),
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004009 Dependent);
Richard Smith30482bc2011-02-20 03:19:35 +00004010 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4011 NewTL.setNameLoc(TL.getNameLoc());
4012 return Result;
4013 }
4014 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004015
4016 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4017 // Lambdas never need to be transformed.
4018 return E;
4019 }
Richard Smith061f1e22013-04-30 21:23:01 +00004020
Richard Smith2a7d4812013-05-04 07:00:32 +00004021 QualType Apply(TypeLoc TL) {
4022 // Create some scratch storage for the transformed type locations.
4023 // FIXME: We're just going to throw this information away. Don't build it.
4024 TypeLocBuilder TLB;
4025 TLB.reserve(TL.getFullDataSize());
4026 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004027 }
Richard Smith30482bc2011-02-20 03:19:35 +00004028 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004029}
Richard Smith30482bc2011-02-20 03:19:35 +00004030
Richard Smith2a7d4812013-05-04 07:00:32 +00004031Sema::DeduceAutoResult
4032Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result) {
4033 return DeduceAutoType(Type->getTypeLoc(), Init, Result);
4034}
4035
Richard Smith061f1e22013-04-30 21:23:01 +00004036/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004037///
4038/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004039/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004040/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004041/// deduced type.
Sebastian Redl09edce02012-01-23 22:09:39 +00004042Sema::DeduceAutoResult
Richard Smith2a7d4812013-05-04 07:00:32 +00004043Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result) {
John McCalld5c98ae2011-11-15 01:35:18 +00004044 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004045 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4046 if (NonPlaceholder.isInvalid())
4047 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004048 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004049 }
4050
Richard Smith2a7d4812013-05-04 07:00:32 +00004051 if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004052 Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004053 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004054 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004055 }
4056
Richard Smith74aeef52013-04-26 16:15:35 +00004057 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4058 // Since 'decltype(auto)' can only occur at the top of the type, we
4059 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004060 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004061 if (AT->isDecltypeAuto()) {
4062 if (isa<InitListExpr>(Init)) {
4063 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4064 return DAR_FailedAlreadyDiagnosed;
4065 }
4066
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004067 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004068 if (Deduced.isNull())
4069 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004070 // FIXME: Support a non-canonical deduced type for 'auto'.
4071 Deduced = Context.getCanonicalType(Deduced);
Richard Smith061f1e22013-04-30 21:23:01 +00004072 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004073 if (Result.isNull())
4074 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004075 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004076 } else if (!getLangOpts().CPlusPlus) {
4077 if (isa<InitListExpr>(Init)) {
4078 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4079 return DAR_FailedAlreadyDiagnosed;
4080 }
Richard Smith74aeef52013-04-26 16:15:35 +00004081 }
4082 }
4083
Richard Smith30482bc2011-02-20 03:19:35 +00004084 SourceLocation Loc = Init->getExprLoc();
4085
4086 LocalInstantiationScope InstScope(*this);
4087
4088 // Build template<class TemplParam> void Func(FuncParam);
Chandler Carruth08836322011-05-01 00:51:33 +00004089 TemplateTypeParmDecl *TemplParam =
Craig Topperc3ec1492014-05-26 06:22:03 +00004090 TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4091 nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004092 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4093 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004094 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4095 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004096
Richard Smith061f1e22013-04-30 21:23:01 +00004097 QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4098 assert(!FuncParam.isNull() &&
4099 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004100
4101 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004102 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004103 Deduced.resize(1);
4104 QualType InitType = Init->getType();
4105 unsigned TDF = 0;
Richard Smith30482bc2011-02-20 03:19:35 +00004106
Craig Toppere6706e42012-09-19 02:26:47 +00004107 TemplateDeductionInfo Info(Loc);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004108
Richard Smith74801c82012-07-08 04:13:07 +00004109 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004110 if (InitList) {
4111 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
James Y Knight7a22b242015-08-06 20:26:32 +00004112 if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4113 TemplArg, InitList->getInit(i),
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004114 Info, Deduced, TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004115 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004116 }
4117 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004118 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4119 Diag(Loc, diag::err_auto_bitfield);
4120 return DAR_FailedAlreadyDiagnosed;
4121 }
4122
James Y Knight7a22b242015-08-06 20:26:32 +00004123 if (AdjustFunctionParmAndArgTypesForDeduction(
4124 *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
Douglas Gregor0e60cd72012-04-04 05:10:53 +00004125 return DAR_Failed;
Richard Smith74801c82012-07-08 04:13:07 +00004126
James Y Knight7a22b242015-08-06 20:26:32 +00004127 if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4128 FuncParam, InitType, Info, Deduced,
4129 TDF))
Sebastian Redl09edce02012-01-23 22:09:39 +00004130 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004131 }
Richard Smith30482bc2011-02-20 03:19:35 +00004132
Eli Friedmane4310952012-11-06 23:56:42 +00004133 if (Deduced[0].getKind() != TemplateArgument::Type)
Sebastian Redl09edce02012-01-23 22:09:39 +00004134 return DAR_Failed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004135
Eli Friedmane4310952012-11-06 23:56:42 +00004136 QualType DeducedType = Deduced[0].getAsType();
4137
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004138 if (InitList) {
4139 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4140 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004141 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004142 }
4143
Richard Smith061f1e22013-04-30 21:23:01 +00004144 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004145 if (Result.isNull())
4146 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004147
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004148 // Check that the deduced argument type is compatible with the original
4149 // argument type per C++ [temp.deduct.call]p4.
Richard Smith061f1e22013-04-30 21:23:01 +00004150 if (!InitList && !Result.isNull() &&
4151 CheckOriginalCallArgDeduction(*this,
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004152 Sema::OriginalCallArg(FuncParam,0,InitType),
Richard Smith061f1e22013-04-30 21:23:01 +00004153 Result)) {
4154 Result = QualType();
Sebastian Redl09edce02012-01-23 22:09:39 +00004155 return DAR_Failed;
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004156 }
4157
Sebastian Redl09edce02012-01-23 22:09:39 +00004158 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004159}
4160
Simon Pilgrim728134c2016-08-12 11:43:57 +00004161QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004162 QualType TypeToReplaceAuto) {
4163 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4164 TransformType(TypeWithAuto);
4165}
4166
Simon Pilgrim728134c2016-08-12 11:43:57 +00004167TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004168 QualType TypeToReplaceAuto) {
4169 return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4170 TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004171}
4172
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004173void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4174 if (isa<InitListExpr>(Init))
4175 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004176 VDecl->isInitCapture()
4177 ? diag::err_init_capture_deduction_failure_from_init_list
4178 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004179 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4180 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004181 Diag(VDecl->getLocation(),
4182 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4183 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004184 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4185 << Init->getSourceRange();
4186}
4187
Richard Smith2a7d4812013-05-04 07:00:32 +00004188bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4189 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004190 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004191
4192 if (FD->getTemplateInstantiationPattern())
4193 InstantiateFunctionDefinition(Loc, FD);
4194
Alp Toker314cc812014-01-25 16:55:45 +00004195 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004196 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4197 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4198 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4199 }
4200
4201 return StillUndeduced;
4202}
4203
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004204static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004205MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004206 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004207 unsigned Level,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004208 llvm::SmallBitVector &Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004209
4210/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004211static void
4212AddImplicitObjectParameterType(ASTContext &Context,
4213 CXXMethodDecl *Method,
4214 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004215 // C++11 [temp.func.order]p3:
4216 // [...] The new parameter is of type "reference to cv A," where cv are
4217 // the cv-qualifiers of the function template (if any) and A is
4218 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004219 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004220 // The standard doesn't say explicitly, but we pick the appropriate kind of
4221 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004222 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4223 ArgTy = Context.getQualifiedType(ArgTy,
4224 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004225 if (Method->getRefQualifier() == RQ_RValue)
4226 ArgTy = Context.getRValueReferenceType(ArgTy);
4227 else
4228 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004229 ArgTypes.push_back(ArgTy);
4230}
4231
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004232/// \brief Determine whether the function template \p FT1 is at least as
4233/// specialized as \p FT2.
4234static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004235 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004236 FunctionTemplateDecl *FT1,
4237 FunctionTemplateDecl *FT2,
4238 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004239 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004240 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004241 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004242 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4243 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004244
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004245 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4246 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004247 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004248 Deduced.resize(TemplateParams->size());
4249
4250 // C++0x [temp.deduct.partial]p3:
4251 // The types used to determine the ordering depend on the context in which
4252 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004253 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004254 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004255 switch (TPOC) {
4256 case TPOC_Call: {
4257 // - In the context of a function call, the function parameter types are
4258 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004259 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4260 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004261
Eli Friedman3b5774a2012-09-19 23:27:04 +00004262 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004263 // [...] If only one of the function templates is a non-static
4264 // member, that function template is considered to have a new
4265 // first parameter inserted in its function parameter list. The
4266 // new parameter is of type "reference to cv A," where cv are
4267 // the cv-qualifiers of the function template (if any) and A is
4268 // the class of which the function template is a member.
4269 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004270 // Note that we interpret this to mean "if one of the function
4271 // templates is a non-static member and the other is a non-member";
4272 // otherwise, the ordering rules for static functions against non-static
4273 // functions don't make any sense.
4274 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004275 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4276 // it as wording was broken prior to it.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004277 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004278
Richard Smithe5b52202013-09-11 00:52:39 +00004279 unsigned NumComparedArguments = NumCallArguments1;
4280
4281 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004282 // Compare 'this' from Method1 against first parameter from Method2.
4283 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4284 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004285 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004286 // Compare 'this' from Method2 against first parameter from Method1.
4287 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004288 }
4289
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004290 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004291 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004292 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004293 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
Douglas Gregorb837ea42011-01-11 17:34:58 +00004295 // C++ [temp.func.order]p5:
4296 // The presence of unused ellipsis and default arguments has no effect on
4297 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004298 if (Args1.size() > NumComparedArguments)
4299 Args1.resize(NumComparedArguments);
4300 if (Args2.size() > NumComparedArguments)
4301 Args2.resize(NumComparedArguments);
Douglas Gregorb837ea42011-01-11 17:34:58 +00004302 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4303 Args1.data(), Args1.size(), Info, Deduced,
Richard Smithed563c22015-02-20 04:45:22 +00004304 TDF_None, /*PartialOrdering=*/true))
Richard Smith0a80d572014-05-29 01:12:14 +00004305 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004307 break;
4308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004310 case TPOC_Conversion:
4311 // - In the context of a call to a conversion operator, the return types
4312 // of the conversion function templates are used.
Alp Toker314cc812014-01-25 16:55:45 +00004313 if (DeduceTemplateArgumentsByTypeMatch(
4314 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4315 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004316 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004317 return false;
4318 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004320 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004321 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004322 // is used.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004323 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4324 FD2->getType(), FD1->getType(),
4325 Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004326 /*PartialOrdering=*/true))
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004327 return false;
4328 break;
4329 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004331 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332 // In most cases, all template parameters must have values in order for
4333 // deduction to succeed, but for partial ordering purposes a template
4334 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004335 // types being used for partial ordering. [ Note: a template parameter used
4336 // in a non-deduced context is considered used. -end note]
4337 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4338 for (; ArgIdx != NumArgs; ++ArgIdx)
4339 if (Deduced[ArgIdx].isNull())
4340 break;
4341
4342 if (ArgIdx == NumArgs) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343 // All template arguments were deduced. FT1 is at least as specialized
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004344 // as FT2.
4345 return true;
4346 }
4347
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004348 // Figure out which template parameters were used.
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004349 llvm::SmallBitVector UsedParameters(TemplateParams->size());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004350 switch (TPOC) {
Richard Smithe5b52202013-09-11 00:52:39 +00004351 case TPOC_Call:
4352 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4353 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
Douglas Gregor21610382009-10-29 00:04:11 +00004354 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004355 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004356 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004357
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004358 case TPOC_Conversion:
Alp Toker314cc812014-01-25 16:55:45 +00004359 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4360 TemplateParams->getDepth(), UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004361 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004362
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004363 case TPOC_Other:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004364 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
Douglas Gregor21610382009-10-29 00:04:11 +00004365 TemplateParams->getDepth(),
4366 UsedParameters);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004367 break;
4368 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004370 for (; ArgIdx != NumArgs; ++ArgIdx)
4371 // If this argument had no value deduced but was used in one of the types
4372 // used for partial ordering, then deduction fails.
4373 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4374 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004376 return true;
4377}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378
Douglas Gregorcef1a032011-01-16 16:03:23 +00004379/// \brief Determine whether this a function template whose parameter-type-list
4380/// ends with a function parameter pack.
4381static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4382 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4383 unsigned NumParams = Function->getNumParams();
4384 if (NumParams == 0)
4385 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004386
Douglas Gregorcef1a032011-01-16 16:03:23 +00004387 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4388 if (!Last->isParameterPack())
4389 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390
Douglas Gregorcef1a032011-01-16 16:03:23 +00004391 // Make sure that no previous parameter is a parameter pack.
4392 while (--NumParams > 0) {
4393 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4394 return false;
4395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004396
Douglas Gregorcef1a032011-01-16 16:03:23 +00004397 return true;
4398}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004399
Douglas Gregorbe999392009-09-15 16:23:51 +00004400/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004401/// to the rules of function template partial ordering (C++ [temp.func.order]).
4402///
4403/// \param FT1 the first function template
4404///
4405/// \param FT2 the second function template
4406///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004407/// \param TPOC the context in which we are performing partial ordering of
4408/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004409///
Richard Smithe5b52202013-09-11 00:52:39 +00004410/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4411/// only when \c TPOC is \c TPOC_Call.
4412///
4413/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4414/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004415///
Douglas Gregorbe999392009-09-15 16:23:51 +00004416/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004417/// template is more specialized, returns NULL.
4418FunctionTemplateDecl *
4419Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4420 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004421 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004422 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004423 unsigned NumCallArguments1,
4424 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004426 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004428 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004429
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004430 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004431 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004433 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004434 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004435
Douglas Gregorcef1a032011-01-16 16:03:23 +00004436 // FIXME: This mimics what GCC implements, but doesn't match up with the
4437 // proposed resolution for core issue 692. This area needs to be sorted out,
4438 // but for now we attempt to maintain compatibility.
4439 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4440 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4441 if (Variadic1 != Variadic2)
4442 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Craig Topperc3ec1492014-05-26 06:22:03 +00004444 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004445}
Douglas Gregor9b146582009-07-08 20:55:45 +00004446
Douglas Gregor450f00842009-09-25 18:43:00 +00004447/// \brief Determine if the two templates are equivalent.
4448static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4449 if (T1 == T2)
4450 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451
Douglas Gregor450f00842009-09-25 18:43:00 +00004452 if (!T1 || !T2)
4453 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454
Douglas Gregor450f00842009-09-25 18:43:00 +00004455 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4456}
4457
4458/// \brief Retrieve the most specialized of the given function template
4459/// specializations.
4460///
John McCall58cc69d2010-01-27 01:50:18 +00004461/// \param SpecBegin the start iterator of the function template
4462/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004463///
John McCall58cc69d2010-01-27 01:50:18 +00004464/// \param SpecEnd the end iterator of the function template
4465/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004466///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004468/// diagnostic should occur.
4469///
4470/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4471/// no matching candidates.
4472///
4473/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4474/// occurs.
4475///
4476/// \param CandidateDiag partial diagnostic used for each function template
4477/// specialization that is a candidate in the ambiguous ordering. One parameter
4478/// in this diagnostic should be unbound, which will correspond to the string
4479/// describing the template arguments for the function template specialization.
4480///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004482/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004483UnresolvedSetIterator Sema::getMostSpecialized(
4484 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4485 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004486 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4487 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4488 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004489 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004490 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004491 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004492 FailedCandidates.NoteCandidates(*this, Loc);
4493 }
John McCall58cc69d2010-01-27 01:50:18 +00004494 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004496
4497 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004498 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499
Douglas Gregor450f00842009-09-25 18:43:00 +00004500 // Find the function template that is better than all of the templates it
4501 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004502 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004504 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004505 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004506 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4507 FunctionTemplateDecl *Challenger
4508 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004509 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004510 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004511 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004512 Challenger)) {
4513 Best = I;
4514 BestTemplate = Challenger;
4515 }
4516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Douglas Gregor450f00842009-09-25 18:43:00 +00004518 // Make sure that the "best" function template is more specialized than all
4519 // of the others.
4520 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004521 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4522 FunctionTemplateDecl *Challenger
4523 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004524 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004526 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004527 BestTemplate)) {
4528 Ambiguous = true;
4529 break;
4530 }
4531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004532
Douglas Gregor450f00842009-09-25 18:43:00 +00004533 if (!Ambiguous) {
4534 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004535 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004536 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004537
Douglas Gregor450f00842009-09-25 18:43:00 +00004538 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004539 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004540 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541
Richard Smithb875c432013-05-04 01:51:08 +00004542 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004543 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4544 PartialDiagnostic PD = CandidateDiag;
4545 PD << getTemplateArgumentBindingsText(
Douglas Gregorb491ed32011-02-19 21:32:49 +00004546 cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
John McCall58cc69d2010-01-27 01:50:18 +00004547 *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004548 if (!TargetType.isNull())
4549 HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4550 TargetType);
4551 Diag((*I)->getLocation(), PD);
4552 }
Richard Smithb875c432013-05-04 01:51:08 +00004553 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554
John McCall58cc69d2010-01-27 01:50:18 +00004555 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004556}
4557
Douglas Gregorbe999392009-09-15 16:23:51 +00004558/// \brief Returns the more specialized class template partial specialization
4559/// according to the rules of partial ordering of class template partial
4560/// specializations (C++ [temp.class.order]).
4561///
4562/// \param PS1 the first class template partial specialization
4563///
4564/// \param PS2 the second class template partial specialization
4565///
4566/// \returns the more specialized class template partial specialization. If
4567/// neither partial specialization is more specialized, returns NULL.
4568ClassTemplatePartialSpecializationDecl *
4569Sema::getMoreSpecializedPartialSpecialization(
4570 ClassTemplatePartialSpecializationDecl *PS1,
John McCallbc077cf2010-02-08 23:07:23 +00004571 ClassTemplatePartialSpecializationDecl *PS2,
4572 SourceLocation Loc) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004573 // C++ [temp.class.order]p1:
4574 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575 // specialized as the second if, given the following rewrite to two
4576 // function templates, the first function template is at least as
4577 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004578 // templates (14.6.6.2):
4579 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580 // first partial specialization and has a single function parameter
4581 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004582 // arguments of the first partial specialization, and
4583 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584 // second partial specialization and has a single function parameter
4585 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004586 // arguments of the second partial specialization.
4587 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004588 // Rather than synthesize function templates, we merely perform the
4589 // equivalent partial ordering by performing deduction directly on
4590 // the template arguments of the class template partial
4591 // specializations. This computation is slightly simpler than the
4592 // general problem of function template partial ordering, because
4593 // class template partial specializations are more constrained. We
4594 // know that every template parameter is deducible from the class
4595 // template partial specialization's template arguments, for
4596 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004597 SmallVector<DeducedTemplateArgument, 4> Deduced;
Craig Toppere6706e42012-09-19 02:26:47 +00004598 TemplateDeductionInfo Info(Loc);
John McCall2408e322010-04-27 00:57:59 +00004599
4600 QualType PT1 = PS1->getInjectedSpecializationType();
4601 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004602
Douglas Gregorbe999392009-09-15 16:23:51 +00004603 // Determine whether PS1 is at least as specialized as PS2
4604 Deduced.resize(PS2->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004605 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4606 PS2->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004607 PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004608 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004609 if (Better1) {
Richard Smith80934652012-07-16 01:09:10 +00004610 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004611 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004612 Better1 = !::FinishTemplateArgumentDeduction(
4613 *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4614 }
4615
4616 // Determine whether PS2 is at least as specialized as PS1
4617 Deduced.clear();
4618 Deduced.resize(PS1->getTemplateParameters()->size());
4619 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4620 *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004621 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004622 if (Better2) {
4623 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4624 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004625 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004626 Better2 = !::FinishTemplateArgumentDeduction(
4627 *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4628 }
4629
4630 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004631 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004632
4633 return Better1 ? PS1 : PS2;
4634}
4635
Larisse Voufo30616382013-08-23 22:21:36 +00004636/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4637/// May require unifying ClassTemplate(Partial)SpecializationDecl and
4638/// VarTemplate(Partial)SpecializationDecl with a new data
4639/// structure Template(Partial)SpecializationDecl, and
4640/// using Template(Partial)SpecializationDecl as input type.
Larisse Voufo39a1e502013-08-06 01:03:05 +00004641VarTemplatePartialSpecializationDecl *
4642Sema::getMoreSpecializedPartialSpecialization(
4643 VarTemplatePartialSpecializationDecl *PS1,
4644 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4645 SmallVector<DeducedTemplateArgument, 4> Deduced;
4646 TemplateDeductionInfo Info(Loc);
4647
Richard Smithf04fd0b2013-12-12 23:14:16 +00004648 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004649 "the partial specializations being compared should specialize"
4650 " the same template.");
4651 TemplateName Name(PS1->getSpecializedTemplate());
4652 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4653 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004654 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004655 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004656 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004657
4658 // Determine whether PS1 is at least as specialized as PS2
4659 Deduced.resize(PS2->getTemplateParameters()->size());
4660 bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4661 *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004662 /*PartialOrdering=*/true);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004663 if (Better1) {
4664 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4665 Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004666 InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004667 Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4668 PS1->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004669 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671
Douglas Gregorbe999392009-09-15 16:23:51 +00004672 // Determine whether PS2 is at least as specialized as PS1
Douglas Gregoradee3e32009-11-11 23:06:43 +00004673 Deduced.clear();
Douglas Gregorbe999392009-09-15 16:23:51 +00004674 Deduced.resize(PS1->getTemplateParameters()->size());
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004675 bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4676 PS1->getTemplateParameters(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00004677 PT1, PT2, Info, Deduced, TDF_None,
Richard Smithed563c22015-02-20 04:45:22 +00004678 /*PartialOrdering=*/true);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004679 if (Better2) {
Richard Smith80934652012-07-16 01:09:10 +00004680 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00004681 InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004682 Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4683 PS2->getTemplateArgs(),
Douglas Gregor9225b022010-04-29 06:31:36 +00004684 Deduced, Info);
Argyrios Kyrtzidis7d391552010-11-05 23:25:18 +00004685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686
Douglas Gregorbe999392009-09-15 16:23:51 +00004687 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004688 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689
Douglas Gregorbe999392009-09-15 16:23:51 +00004690 return Better1? PS1 : PS2;
4691}
4692
Mike Stump11289f42009-09-09 15:08:12 +00004693static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004694MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004695 const TemplateArgument &TemplateArg,
4696 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004697 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004698 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004699
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004700/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004701/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004702static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004703MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004704 const Expr *E,
4705 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004706 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004707 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004708 // We can deduce from a pack expansion.
4709 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4710 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004711
Richard Smith34349002012-07-09 03:07:20 +00004712 // Skip through any implicit casts we added while type-checking, and any
4713 // substitutions performed by template alias expansion.
4714 while (1) {
4715 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4716 E = ICE->getSubExpr();
4717 else if (const SubstNonTypeTemplateParmExpr *Subst =
4718 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4719 E = Subst->getReplacement();
4720 else
4721 break;
4722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004723
4724 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004725 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004726 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004727 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004728 return;
4729
Mike Stump11289f42009-09-09 15:08:12 +00004730 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004731 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4732 if (!NTTP)
4733 return;
4734
Douglas Gregor21610382009-10-29 00:04:11 +00004735 if (NTTP->getDepth() == Depth)
4736 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004737
4738 // In C++1z mode, additional arguments may be deduced from the type of a
4739 // non-type argument.
4740 if (Ctx.getLangOpts().CPlusPlus1z)
4741 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004742}
4743
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004744/// \brief Mark the template parameters that are used by the given
4745/// nested name specifier.
4746static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004747MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004748 NestedNameSpecifier *NNS,
4749 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004750 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004751 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004752 if (!NNS)
4753 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004754
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004755 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004756 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004757 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004758 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004759}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004761/// \brief Mark the template parameters that are used by the given
4762/// template name.
4763static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004764MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004765 TemplateName Name,
4766 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004767 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004768 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004769 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4770 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00004771 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4772 if (TTP->getDepth() == Depth)
4773 Used[TTP->getIndex()] = true;
4774 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004775 return;
4776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004778 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004779 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004780 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004781 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004782 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004783 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004784}
4785
4786/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004787/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004788static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004789MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004790 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004791 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004792 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004793 if (T.isNull())
4794 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795
Douglas Gregor91772d12009-06-13 00:26:55 +00004796 // Non-dependent types have nothing deducible
4797 if (!T->isDependentType())
4798 return;
4799
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004800 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00004801 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00004802 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004803 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004804 cast<PointerType>(T)->getPointeeType(),
4805 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004806 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004807 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004808 break;
4809
4810 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004811 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004812 cast<BlockPointerType>(T)->getPointeeType(),
4813 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004814 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004815 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004816 break;
4817
4818 case Type::LValueReference:
4819 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004820 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004821 cast<ReferenceType>(T)->getPointeeType(),
4822 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004823 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004824 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004825 break;
4826
4827 case Type::MemberPointer: {
4828 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004829 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004830 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004831 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004832 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004833 break;
4834 }
4835
4836 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004837 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004838 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00004839 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004840 // Fall through to check the element type
4841
4842 case Type::ConstantArray:
4843 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004844 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004845 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004846 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004847 break;
4848
4849 case Type::Vector:
4850 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004851 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004852 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004853 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004854 break;
4855
Douglas Gregor758a8692009-06-17 21:51:59 +00004856 case Type::DependentSizedExtVector: {
4857 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004858 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004859 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004860 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004861 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004862 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00004863 break;
4864 }
4865
Douglas Gregor91772d12009-06-13 00:26:55 +00004866 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004867 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00004868 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4869 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00004870 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4871 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004872 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004873 break;
4874 }
4875
Douglas Gregor21610382009-10-29 00:04:11 +00004876 case Type::TemplateTypeParm: {
4877 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4878 if (TTP->getDepth() == Depth)
4879 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00004880 break;
Douglas Gregor21610382009-10-29 00:04:11 +00004881 }
Douglas Gregor91772d12009-06-13 00:26:55 +00004882
Douglas Gregorfb322d82011-01-14 05:11:40 +00004883 case Type::SubstTemplateTypeParmPack: {
4884 const SubstTemplateTypeParmPackType *Subst
4885 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004886 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00004887 QualType(Subst->getReplacedParameter(), 0),
4888 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004889 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00004890 OnlyDeduced, Depth, Used);
4891 break;
4892 }
4893
John McCall2408e322010-04-27 00:57:59 +00004894 case Type::InjectedClassName:
4895 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4896 // fall through
4897
Douglas Gregor91772d12009-06-13 00:26:55 +00004898 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00004899 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004900 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004901 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004902 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004903
Douglas Gregord0ad2942010-12-23 01:24:45 +00004904 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00004905 // If the template argument list of P contains a pack expansion that is
4906 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00004907 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004908 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00004909 hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4910 break;
4911
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004912 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004913 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004914 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004915 break;
4916 }
4917
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004918 case Type::Complex:
4919 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004920 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004921 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00004922 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004923 break;
4924
Eli Friedman0dfb8892011-10-06 23:00:33 +00004925 case Type::Atomic:
4926 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004927 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00004928 cast<AtomicType>(T)->getValueType(),
4929 OnlyDeduced, Depth, Used);
4930 break;
4931
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004932 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004933 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004934 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004935 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00004936 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004937 break;
4938
John McCallc392f372010-06-11 00:33:02 +00004939 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00004940 // C++14 [temp.deduct.type]p5:
4941 // The non-deduced contexts are:
4942 // -- The nested-name-specifier of a type that was specified using a
4943 // qualified-id
4944 //
4945 // C++14 [temp.deduct.type]p6:
4946 // When a type name is specified in a way that includes a non-deduced
4947 // context, all of the types that comprise that type name are also
4948 // non-deduced.
4949 if (OnlyDeduced)
4950 break;
4951
John McCallc392f372010-06-11 00:33:02 +00004952 const DependentTemplateSpecializationType *Spec
4953 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004954
Richard Smith50d5b972015-12-30 20:56:05 +00004955 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4956 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00004957
John McCallc392f372010-06-11 00:33:02 +00004958 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004959 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00004960 Used);
4961 break;
4962 }
4963
John McCallbd8d9bd2010-03-01 23:49:17 +00004964 case Type::TypeOf:
4965 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004966 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004967 cast<TypeOfType>(T)->getUnderlyingType(),
4968 OnlyDeduced, Depth, Used);
4969 break;
4970
4971 case Type::TypeOfExpr:
4972 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004973 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004974 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4975 OnlyDeduced, Depth, Used);
4976 break;
4977
4978 case Type::Decltype:
4979 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004980 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00004981 cast<DecltypeType>(T)->getUnderlyingExpr(),
4982 OnlyDeduced, Depth, Used);
4983 break;
4984
Alexis Hunte852b102011-05-24 22:41:36 +00004985 case Type::UnaryTransform:
4986 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004987 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00004988 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00004989 OnlyDeduced, Depth, Used);
4990 break;
4991
Douglas Gregord2fa7662010-12-20 02:24:11 +00004992 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004993 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00004994 cast<PackExpansionType>(T)->getPattern(),
4995 OnlyDeduced, Depth, Used);
4996 break;
4997
Richard Smith30482bc2011-02-20 03:19:35 +00004998 case Type::Auto:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004999 MarkUsedTemplateParameters(Ctx,
Richard Smith30482bc2011-02-20 03:19:35 +00005000 cast<AutoType>(T)->getDeducedType(),
5001 OnlyDeduced, Depth, Used);
5002
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005003 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005004 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005005 case Type::VariableArray:
5006 case Type::FunctionNoProto:
5007 case Type::Record:
5008 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005009 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005010 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005011 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005012 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005013 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005014#define TYPE(Class, Base)
5015#define ABSTRACT_TYPE(Class, Base)
5016#define DEPENDENT_TYPE(Class, Base)
5017#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5018#include "clang/AST/TypeNodes.def"
5019 break;
5020 }
5021}
5022
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005023/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005024/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005025static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005026MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005027 const TemplateArgument &TemplateArg,
5028 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005029 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005030 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005031 switch (TemplateArg.getKind()) {
5032 case TemplateArgument::Null:
5033 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005034 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005035 break;
Mike Stump11289f42009-09-09 15:08:12 +00005036
Eli Friedmanb826a002012-09-26 02:36:12 +00005037 case TemplateArgument::NullPtr:
5038 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5039 Depth, Used);
5040 break;
5041
Douglas Gregor91772d12009-06-13 00:26:55 +00005042 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005043 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005044 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005045 break;
5046
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005047 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005048 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005049 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005050 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005051 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005052 break;
5053
5054 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005055 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005056 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005057 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005058
Anders Carlssonbc343912009-06-15 17:04:53 +00005059 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005060 for (const auto &P : TemplateArg.pack_elements())
5061 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005062 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005063 }
5064}
5065
James Dennett41725122012-06-22 10:16:05 +00005066/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005067/// template argument list.
5068///
5069/// \param TemplateArgs the template argument list from which template
5070/// parameters will be deduced.
5071///
James Dennett41725122012-06-22 10:16:05 +00005072/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005073/// to indicate when the corresponding template parameter will be
5074/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005075void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005076Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005077 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005078 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005079 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005080 // If the template argument list of P contains a pack expansion that is not
5081 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005082 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005083 if (OnlyDeduced &&
Douglas Gregord0ad2942010-12-23 01:24:45 +00005084 hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5085 return;
5086
Douglas Gregor91772d12009-06-13 00:26:55 +00005087 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005088 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005089 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005090}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005091
5092/// \brief Marks all of the template parameters that will be deduced by a
5093/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005094void Sema::MarkDeducedTemplateParameters(
5095 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5096 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005098 = FunctionTemplate->getTemplateParameters();
5099 Deduced.clear();
5100 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101
Douglas Gregorce23bae2009-09-18 23:21:38 +00005102 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5103 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005104 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005105 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005106}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005107
5108bool hasDeducibleTemplateParameters(Sema &S,
5109 FunctionTemplateDecl *FunctionTemplate,
5110 QualType T) {
5111 if (!T->isDependentType())
5112 return false;
5113
5114 TemplateParameterList *TemplateParams
5115 = FunctionTemplate->getTemplateParameters();
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005116 llvm::SmallBitVector Deduced(TemplateParams->size());
Simon Pilgrim728134c2016-08-12 11:43:57 +00005117 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
Douglas Gregore65aacb2011-06-16 16:50:48 +00005118 Deduced);
5119
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005120 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005121}